Skip to content

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

Return Products (#6599)

Maciej Korycinski05bdc7feb9ac
diff --git a/saleor/graphql/order/mutations/fulfillments.py b/saleor/graphql/order/mutations/fulfillments.py
index 2b8483b070..c3b050006d 100644
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@ -6,10 +6,16 @@ from django.template.defaultfilters import pluralize
from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
-from ....order import FulfillmentStatus, models as order_models
+from ....order import (
+ FulfillmentLineData,
+ FulfillmentStatus,
+ OrderLineData,
+ models as order_models,
+)
from ....order.actions import (
cancel_fulfillment,
create_fulfillments,
+ create_fulfillments_for_returned_products,
create_refund_fulfillment,
fulfillment_tracking_updated,
)
@@ -358,24 +364,9 @@ class OrderRefundProductsInput(graphene.InputObjectType):
)
-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 FulfillmentRefundAndReturnProductBase(BaseMutation):
class Meta:
- description = "Refund products."
- permissions = (OrderPermissions.MANAGE_ORDERS,)
- error_type_class = OrderError
- error_type_field = "order_errors"
+ abstract = True
@classmethod
def clean_order_payment(cls, payment, cleaned_input):
@@ -406,38 +397,11 @@ class FulfillmentRefundProducts(BaseMutation):
)
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
+ code = OrderErrorCode.INVALID_QUANTITY.value
raise ValidationError(
{
field_name: ValidationError(
@@ -447,70 +411,148 @@ class FulfillmentRefundProducts(BaseMutation):
)
@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,
+ def clean_fulfillment_lines(
+ cls, fulfillment_lines_data, cleaned_input, whitelisted_statuses
+ ):
+ fulfillment_lines = cls.get_nodes_or_error(
+ [line["fulfillment_line_id"] for line in fulfillment_lines_data],
field="fulfillment_lines",
only_type=FulfillmentLine,
- qs=order_models.FulfillmentLine.objects.prefetch_related("fulfillment"),
+ qs=order_models.FulfillmentLine.objects.prefetch_related(
+ "fulfillment", "order_line"
+ ),
)
- lines_to_refund = list(lines_to_refund)
- for line, quantity in zip(lines_to_refund, quantities_to_refund):
+ fulfillment_lines = list(fulfillment_lines)
+ cleaned_fulfillment_lines = []
+ for line, line_data in zip(fulfillment_lines, fulfillment_lines_data):
+ quantity = line_data["quantity"]
if line.quantity < quantity:
cls._raise_error_for_line(
- "Quantity provided to refund is bigger than quantity from "
+ "Provided quantity is bigger than quantity from "
"fulfillment line",
"FulfillmentLine",
line.pk,
"fulfillment_line_id",
)
- if line.fulfillment.status != FulfillmentStatus.FULFILLED:
+ if line.fulfillment.status not in whitelisted_statuses:
+ allowed_statuses_str = ", ".join(whitelisted_statuses)
cls._raise_error_for_line(
- "Unable to refund fulfillmentLine with different type than "
- "FULFILLED.",
+ f"Unable to process action for fulfillmentLine with different "
+ f"status than {allowed_statuses_str}.",
"FulfillmentLine",
line.pk,
"fulfillment_line_id",
- code=OrderErrorCode.CANNOT_REFUND_FULFILLMENT_LINE.value,
+ code=OrderErrorCode.INVALID.value,
)
- cleaned_input["fulfillment_lines_quantities_to_refund"] = quantities_to_refund
- cleaned_input["fulfillment_lines_to_refund"] = lines_to_refund
+ replace = line_data.get("replace", False)
+ if replace and not line.order_line.variant_id:
+ cls._raise_error_for_line(
+ "Unable to replace line as the assigned product doesn't exist.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+ cleaned_fulfillment_lines.append(
+ FulfillmentLineData(line=line, quantity=quantity, replace=replace,)
+ )
+ cleaned_input["fulfillment_lines"] = cleaned_fulfillment_lines
@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,
+ order_lines = cls.get_nodes_or_error(
+ [line["order_line_id"] for line in lines_data],
field="order_lines",
only_type=OrderLine,
qs=order_models.OrderLine.objects.prefetch_related(
"fulfillment_lines__fulfillment", "variant", "allocations"
),
)
- lines_to_refund = list(lines_to_refund)
- for line, quantity in zip(lines_to_refund, quantities_to_refund):
+ order_lines = list(order_lines)
+ cleaned_order_lines = []
+ for line, line_data in zip(order_lines, lines_data):
+ quantity = line_data["quantity"]
if line.quantity < quantity:
cls._raise_error_for_line(
- "Quantity provided to refund is bigger than quantity from order "
- "line.",
+ "Provided quantity is bigger than quantity from order line.",
+ "OrderLine",
+ line.pk,
+ "order_line_id",
+ )
+ quantity_ready_to_move = line.quantity_unfulfilled
+ if quantity_ready_to_move < quantity:
+ cls._raise_error_for_line(
+ "Provided quantity is bigger than unfulfilled quantity.",
"OrderLine",
line.pk,
"order_line_id",
)
- quantity_ready_to_refund = line.quantity_unfulfilled
- if quantity_ready_to_refund < quantity:
+ replace = line_data.get("replace", False)
+ if replace and not line.variant_id:
cls._raise_error_for_line(
- "Quantity provided to refund is bigger than unfulfilled quantity.",
+ "Unable to replace line as the assigned product doesn't exist.",
"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
+ cleaned_order_lines.append(
+ OrderLineData(line=line, quantity=quantity, replace=replace)
+ )
+ cleaned_input["order_lines"] = cleaned_order_lines
+
+
+class FulfillmentRefundProducts(FulfillmentRefundAndReturnProductBase):
+ 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_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,
+ whitelisted_statuses=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.RETURNED,
+ ],
+ )
+ return cleaned_input
@classmethod
def perform_mutation(cls, _root, info, **data):
@@ -520,11 +562,155 @@ class FulfillmentRefundProducts(BaseMutation):
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.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
cleaned_input["amount_to_refund"],
cleaned_input["include_shipping_costs"],
)
return cls(order=order, fulfillment=refund_fulfillment)
+
+
+class OrderReturnLineInput(graphene.InputObjectType):
+ order_line_id = graphene.ID(
+ description="The ID of the order line to return.",
+ name="orderLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be returned.", required=True,
+ )
+ replace = graphene.Boolean(
+ description="Determines, if the line should be added to replace order.",
+ default_value=False,
+ )
+
+
+class OrderReturnFulfillmentLineInput(graphene.InputObjectType):
+ fulfillment_line_id = graphene.ID(
+ description="The ID of the fulfillment line to return.",
+ name="fulfillmentLineId",
+ required=True,
+ )
+ quantity = graphene.Int(
+ description="The number of items to be returned.", required=True,
+ )
+ replace = graphene.Boolean(
+ description="Determines, if the line should be added to replace order.",
+ default_value=False,
+ )
+
+
+class OrderReturnProductsInput(graphene.InputObjectType):
+ order_lines = graphene.List(
+ graphene.NonNull(OrderReturnLineInput),
+ description="List of unfulfilled lines to return.",
+ )
+ fulfillment_lines = graphene.List(
+ graphene.NonNull(OrderReturnFulfillmentLineInput),
+ description="List of fulfilled lines to return.",
+ )
+ 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,
+ )
+ refund = graphene.Boolean(
+ description="If true, Saleor will call refund action for all lines.",
+ default_value=False,
+ )
+
+
+class FulfillmentReturnProducts(FulfillmentRefundAndReturnProductBase):
+ return_fulfillment = graphene.Field(
+ Fulfillment, description="A return fulfillment."
+ )
+ replace_fulfillment = graphene.Field(
+ Fulfillment, description="A replace fulfillment."
+ )
+ order = graphene.Field(Order, description="Order which fulfillment was returned.")
+ replace_order = graphene.Field(
+ Order,
+ description="A draft order which was created for products with replace flag.",
+ )
+
+ class Meta:
+ description = "Return products."
+ permissions = (OrderPermissions.MANAGE_ORDERS,)
+ error_type_class = OrderError
+ error_type_field = "order_errors"
+
+ class Arguments:
+ order = graphene.ID(
+ description="ID of the order to be returned.", required=True
+ )
+ input = OrderReturnProductsInput(
+ required=True, description="Fields required to return products.",
+ )
+
+ @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"]
+ refund = input["refund"]
+
+ 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()
+ if refund:
+ 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,
+ "refund": refund,
+ }
+ )
+
+ 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,
+ whitelisted_statuses=[
+ FulfillmentStatus.FULFILLED,
+ FulfillmentStatus.REFUNDED,
+ ],
+ )
+ return cleaned_input
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ cleaned_input = cls.clean_input(info, data.get("order"), data.get("input"))
+ order = cleaned_input["order"]
+ response = create_fulfillments_for_returned_products(
+ get_user_or_app_from_context(info.context),
+ order,
+ cleaned_input.get("payment"),
+ cleaned_input.get("order_lines", []),
+ cleaned_input.get("fulfillment_lines", []),
+ cleaned_input["refund"],
+ cleaned_input.get("amount_to_refund"),
+ cleaned_input["include_shipping_costs"],
+ )
+ return_fulfillment, replace_fulfillment, replace_order = response
+ return cls(
+ order=order,
+ return_fulfillment=return_fulfillment,
+ replace_fulfillment=replace_fulfillment,
+ replace_order=replace_order,
+ )
diff --git a/saleor/graphql/order/schema.py b/saleor/graphql/order/schema.py
index 662d3f27ee..2d66509703 100644
--- a/saleor/graphql/order/schema.py
+++ b/saleor/graphql/order/schema.py
@@ -22,6 +22,7 @@ from .mutations.draft_orders import (
from .mutations.fulfillments import (
FulfillmentCancel,
FulfillmentRefundProducts,
+ FulfillmentReturnProducts,
FulfillmentUpdateTracking,
OrderFulfill,
)
@@ -166,6 +167,7 @@ class OrderMutations(graphene.ObjectType):
order_fulfillment_cancel = FulfillmentCancel.Field()
order_fulfillment_update_tracking = FulfillmentUpdateTracking.Field()
order_fulfillment_refund_products = FulfillmentRefundProducts.Field()
+ order_fulfillment_return_products = FulfillmentReturnProducts.Field()
order_mark_as_paid = OrderMarkAsPaid.Field()
order_refund = OrderRefund.Field()
diff --git a/saleor/graphql/order/tests/test_fulfillment.py b/saleor/graphql/order/tests/test_fulfillment.py
index fb0a67c9b2..e61b9d5a68 100644
--- a/saleor/graphql/order/tests/test_fulfillment.py
+++ b/saleor/graphql/order/tests/test_fulfillment.py
@@ -1,17 +1,13 @@
-from decimal import Decimal
from unittest.mock import patch
import graphene
from django.contrib.auth.models import AnonymousUser
-from prices import Money, TaxedMoney
from ....core.exceptions import InsufficientStock
-from ....core.prices import quantize_price
from ....order import OrderStatus
from ....order.error_codes import OrderErrorCode
from ....order.events import OrderEvents
from ....order.models import FulfillmentStatus
-from ....payment import ChargeStatus
from ....warehouse.models import Allocation, Stock
from ...tests.utils import assert_no_permission, get_graphql_content
@@ -831,540 +827,3 @@ 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)
- variant.track_inventory = False
- variant.save()
- 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,
- )
- 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/tests/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
new file mode 100644
index 0000000000..c540adca06
--- /dev/null
+++ b/saleor/graphql/order/tests/test_fulfillment_refund_products.py
@@ -0,0 +1,548 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+from prices import Money, TaxedMoney
+
+from ....core.prices import quantize_price
+from ....order.error_codes import OrderErrorCode
+from ....order.models import FulfillmentStatus
+from ....payment import ChargeStatus
+from ....warehouse.models import Stock
+from ...tests.utils import get_graphql_content
+
+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_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_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_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)
+ variant.track_inventory = False
+ variant.save()
+ 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,
+ )
+ 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/tests/test_fulfillment_return_products.py b/saleor/graphql/order/tests/test_fulfillment_return_products.py
new file mode 100644
index 0000000000..0676cdc024
--- /dev/null
+++ b/saleor/graphql/order/tests/test_fulfillment_return_products.py
@@ -0,0 +1,694 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+import graphene
+from prices import Money, TaxedMoney
+
+from ....core.prices import quantize_price
+from ....order import OrderStatus
+from ....order.error_codes import OrderErrorCode
+from ....order.models import FulfillmentStatus, Order
+from ....payment import ChargeStatus
+from ....warehouse.models import Stock
+from ...tests.utils import get_graphql_content
+
+ORDER_FULFILL_RETURN_MUTATION = """
+mutation OrderFulfillmentReturnProducts(
+ $order: ID!, $input: OrderReturnProductsInput!
+) {
+ orderFulfillmentReturnProducts(
+ order: $order,
+ input: $input
+ ) {
+ returnFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ replaceFulfillment{
+ id
+ status
+ lines{
+ id
+ quantity
+ orderLine{
+ id
+ }
+ }
+ }
+ order{
+ id
+ status
+ }
+ replaceOrder{
+ id
+ status
+ }
+ orderErrors {
+ field
+ code
+ message
+ warehouse
+ orderLine
+ }
+ }
+}
+"""
+
+
+def test_fulfillment_return_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": {"refund": True, "amountToRefund": "11.00"},
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ fulfillment = data["returnFulfillment"]
+ 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_return_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": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "includeShippingCosts": True,
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ staff_api_client.post_graphql(ORDER_FULFILL_RETURN_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_return_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_return = order_with_lines.lines.first()
+ line_unfulfilled_quantity = line_to_return.quantity_unfulfilled
+ line_quantity_to_return = 2
+
+ line_to_replace = order_with_lines.lines.last()
+ line_quantity_to_replace = 1
+
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_return.pk)
+ replace_line_id = graphene.Node.to_global_id("OrderLine", line_to_replace.pk)
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "orderLines": [
+ {
+ "orderLineId": line_id,
+ "quantity": line_quantity_to_return,
+ "replace": False,
+ },
+ {
+ "orderLineId": replace_line_id,
+ "quantity": line_quantity_to_replace,
+ "replace": True,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ order_with_lines.refresh_from_db()
+ order_return_fulfillment = order_with_lines.fulfillments.get(
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ return_fulfillment_line = order_return_fulfillment.lines.filter(
+ order_line_id=line_to_return.pk
+ ).first()
+ assert return_fulfillment_line
+ assert return_fulfillment_line.quantity == line_quantity_to_return
+
+ order_replace_fulfillment = order_with_lines.fulfillments.get(
+ status=FulfillmentStatus.REPLACED
+ )
+ replace_fulfillment_line = order_replace_fulfillment.lines.filter(
+ order_line_id=line_to_replace.pk
+ ).first()
+ assert replace_fulfillment_line
+ assert replace_fulfillment_line.quantity == line_quantity_to_replace
+
+ line_to_return.refresh_from_db()
+ assert (
+ line_to_return.quantity_unfulfilled
+ == line_unfulfilled_quantity - line_quantity_to_return
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ replace_fulfillment = data["replaceFulfillment"]
+ replace_order = data["replaceOrder"]
+ errors = data["orderErrors"]
+
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"]["id"] == line_id
+ assert return_fulfillment["lines"][0]["quantity"] == line_quantity_to_return
+
+ assert replace_fulfillment["status"] == FulfillmentStatus.REPLACED.upper()
+ assert len(replace_fulfillment["lines"]) == 1
+ assert replace_fulfillment["lines"][0]["orderLine"]["id"] == replace_line_id
+ assert replace_fulfillment["lines"][0]["quantity"] == line_quantity_to_replace
+
+ assert replace_order["status"] == OrderStatus.DRAFT.upper()
+ replace_order = Order.objects.get(status=OrderStatus.DRAFT)
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.get()
+ assert replaced_line.variant_id == line_to_replace.variant_id
+ assert (
+ replaced_line.unit_price_gross_amount == line_to_replace.unit_price_gross_amount
+ )
+ assert replaced_line.quantity == line_quantity_to_replace
+
+ amount = line_to_return.unit_price_gross_amount * line_quantity_to_return
+ amount += order_with_lines.shipping_price_gross_amount
+ mocked_refund.assert_called_with(payment_dummy, amount)
+
+
+def test_fulfillment_return_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, "replace": False}]
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ errors = data["orderErrors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "orderLineId"
+ assert errors[0]["code"] == OrderErrorCode.INVALID_QUANTITY.name
+ assert return_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_return = order_with_lines.lines.first()
+ line_to_return.quantity = 3
+ line_to_return.quantity_fulfilled = 3
+ line_to_return.save()
+ order_id = graphene.Node.to_global_id("Order", order_with_lines.pk)
+ line_id = graphene.Node.to_global_id("OrderLine", line_to_return.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_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ errors = data["orderErrors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "orderLineId"
+ assert errors[0]["code"] == OrderErrorCode.INVALID_QUANTITY.name
+ assert return_fulfillment is None
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_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_return = 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_return.pk)
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "amountToRefund": amount_to_refund,
+ "orderLines": [{"orderLineId": line_id, "quantity": 2, "replace": False}],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ errors = data["orderErrors"]
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"]["id"] == line_id
+ assert return_fulfillment["lines"][0]["quantity"] == 2
+ mocked_refund.assert_called_with(payment_dummy, amount_to_refund)
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_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)
+ order_fulfillment = fulfilled_order.fulfillments.first()
+ fulfillment_line_to_return = order_fulfillment.lines.first()
+ original_fulfillment_line_quantity = fulfillment_line_to_return.quantity
+ quantity_to_return = 2
+
+ fulfillment_line_to_replace = order_fulfillment.lines.last()
+ quantity_to_replace = 1
+
+ order_id = graphene.Node.to_global_id("Order", fulfilled_order.pk)
+ fulfillment_line_id = graphene.Node.to_global_id(
+ "FulfillmentLine", fulfillment_line_to_return.pk
+ )
+ fulfillment_line_to_replace_id = graphene.Node.to_global_id(
+ "FulfillmentLine", fulfillment_line_to_replace.pk
+ )
+ order_line_id = graphene.Node.to_global_id(
+ "OrderLine", fulfillment_line_to_return.order_line.pk
+ )
+
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "includeShippingCosts": True,
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": fulfillment_line_id,
+ "quantity": quantity_to_return,
+ "replace": False,
+ },
+ {
+ "fulfillmentLineId": fulfillment_line_to_replace_id,
+ "quantity": quantity_to_replace,
+ "replace": True,
+ },
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ fulfilled_order.refresh_from_db()
+ order_return_fulfillment = fulfilled_order.fulfillments.get(
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ return_fulfillment_line = order_return_fulfillment.lines.filter(
+ order_line_id=fulfillment_line_to_return.order_line_id
+ ).first()
+ assert return_fulfillment_line
+ assert return_fulfillment_line.quantity == quantity_to_return
+
+ order_replace_fulfillment = fulfilled_order.fulfillments.get(
+ status=FulfillmentStatus.REPLACED
+ )
+ replace_fulfillment_line = order_replace_fulfillment.lines.filter(
+ order_line_id=fulfillment_line_to_replace.order_line_id
+ ).first()
+ assert replace_fulfillment_line
+ assert replace_fulfillment_line.quantity == quantity_to_replace
+
+ fulfillment_line_to_return.refresh_from_db()
+ assert (
+ fulfillment_line_to_return.quantity
+ == original_fulfillment_line_quantity - quantity_to_return
+ )
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["orderErrors"]
+ return_fulfillment = data["returnFulfillment"]
+ replace_fulfillment = data["replaceFulfillment"]
+ replace_order = data["replaceOrder"]
+
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"]["id"] == order_line_id
+ assert return_fulfillment["lines"][0]["quantity"] == 2
+
+ assert replace_fulfillment["status"] == FulfillmentStatus.REPLACED.upper()
+ assert len(replace_fulfillment["lines"]) == 1
+ assert replace_fulfillment["lines"][0]["quantity"] == quantity_to_replace
+
+ assert replace_order["status"] == OrderStatus.DRAFT.upper()
+ replace_order = Order.objects.get(status=OrderStatus.DRAFT)
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.get()
+ assert replaced_line.variant_id == fulfillment_line_to_replace.order_line.variant_id
+ assert (
+ replaced_line.unit_price_gross_amount
+ == fulfillment_line_to_replace.order_line.unit_price_gross_amount
+ )
+ assert replaced_line.quantity == quantity_to_replace
+
+ amount = (
+ fulfillment_line_to_return.order_line.unit_price_gross_amount
+ * quantity_to_return
+ )
+ amount += fulfilled_order.shipping_price_gross_amount
+ mocked_refund.assert_called_with(payment_dummy, amount)
+
+
+def test_fulfillment_return_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_return = 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_return.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "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_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+
+ errors = data["orderErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "fulfillmentLineId"
+ assert errors[0]["code"] == OrderErrorCode.INVALID_QUANTITY.name
+ assert return_fulfillment is None
+
+
+def test_fulfillment_return_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_return = 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_return.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "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_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+
+ errors = data["orderErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "amountToRefund"
+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
+ assert return_fulfillment is None
+
+
+def test_fulfillment_return_products_lines_with_incorrect_status(
+ 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 = fulfilled_order.fulfillments.first()
+ fulfillment.status = FulfillmentStatus.RETURNED
+ fulfillment.save()
+ fulfillment_line_to_return = 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_return.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "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_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+
+ errors = data["orderErrors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "amountToRefund"
+ assert errors[0]["code"] == OrderErrorCode.CANNOT_REFUND.name
+ assert return_fulfillment is None
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_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_return = 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_return.pk
+ )
+ order_line_id = graphene.Node.to_global_id(
+ "OrderLine", fulfillment_line_to_return.order_line.pk
+ )
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "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_RETURN_MUTATION, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ return_fulfillment = data["returnFulfillment"]
+ errors = data["orderErrors"]
+
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"]["id"] == order_line_id
+ assert return_fulfillment["lines"][0]["quantity"] == 2
+ amount = fulfillment_line_to_return.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_return_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)
+ variant.track_inventory = False
+ variant.save()
+ 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,
+ )
+ fulfillment = fulfilled_order.fulfillments.get()
+ fulfillment.lines.create(order_line=order_line, quantity=2, stock=stock)
+ fulfillment_line_to_replace = 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_replace.pk
+ )
+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.pk)
+ variables = {
+ "order": order_id,
+ "input": {
+ "refund": True,
+ "orderLines": [
+ {"orderLineId": order_line_id, "quantity": 2, "replace": False}
+ ],
+ "fulfillmentLines": [
+ {
+ "fulfillmentLineId": fulfillment_line_id,
+ "quantity": 1,
+ "replace": True,
+ }
+ ],
+ },
+ }
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+
+ response = staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ content = get_graphql_content(response)
+ data = content["data"]["orderFulfillmentReturnProducts"]
+ errors = data["orderErrors"]
+ return_fulfillment = data["returnFulfillment"]
+ replace_fulfillment = data["replaceFulfillment"]
+ replace_order = data["replaceOrder"]
+
+ assert not errors
+ assert (
+ return_fulfillment["status"] == FulfillmentStatus.REFUNDED_AND_RETURNED.upper()
+ )
+ assert len(return_fulfillment["lines"]) == 1
+ assert return_fulfillment["lines"][0]["orderLine"]["id"] == order_line_id
+ assert return_fulfillment["lines"][0]["quantity"] == 2
+
+ assert replace_fulfillment["status"] == FulfillmentStatus.REPLACED.upper()
+ assert len(replace_fulfillment["lines"]) == 1
+ assert replace_fulfillment["lines"][0]["quantity"] == 1
+
+ assert replace_order["status"] == OrderStatus.DRAFT.upper()
+ replace_order = Order.objects.get(status=OrderStatus.DRAFT)
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.get()
+ assert replaced_line.variant_id == fulfillment_line_to_replace.order_line.variant_id
+ assert (
+ replaced_line.unit_price_gross_amount
+ == fulfillment_line_to_replace.order_line.unit_price_gross_amount
+ )
+ assert replaced_line.quantity == 1
+
+ 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/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index f224f10abd..b659b1d656 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -1,4 +1,5 @@
import uuid
+from copy import deepcopy
from datetime import date, timedelta
from unittest.mock import ANY, MagicMock, Mock, call, patch
@@ -13,6 +14,7 @@ from ....account.models import CustomerEvent
from ....core.taxes import TaxError, zero_taxed_money
from ....order import OrderStatus, events as order_events
from ....order.error_codes import OrderErrorCode
+from ....order.events import order_replacement_created
from ....order.models import Order, OrderEvent
from ....payment import ChargeStatus, CustomPaymentChoices, PaymentError
from ....payment.models import Payment
@@ -831,6 +833,48 @@ def test_nested_order_events_query(
assert data["warehouse"]["name"] == warehouse.name
+def test_related_order_events_query(
+ staff_api_client, permission_manage_orders, order, payment_dummy, staff_user
+):
+ query = """
+ query OrdersQuery {
+ orders(first: 2) {
+ edges {
+ node {
+ id
+ events {
+ relatedOrder{
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+
+ new_order = deepcopy(order)
+ new_order.id = None
+ new_order.token = None
+ new_order.save()
+
+ related_order_id = graphene.Node.to_global_id("Order", new_order.id)
+
+ order_replacement_created(
+ original_order=order, replace_order=new_order, user=staff_user
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_orders)
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+
+ data = content["data"]["orders"]["edges"]
+ for order_data in data:
+ events_data = order_data["node"]["events"]
+ if order_data["node"]["id"] != related_order_id:
+ assert events_data[0]["relatedOrder"]["id"] == related_order_id
+
+
def test_payment_information_order_events_query(
staff_api_client, permission_manage_orders, order, payment_dummy, staff_user
):
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 55f52faa37..4f280e6d59 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -32,7 +32,11 @@ from ..product.types import ProductVariant
from ..shipping.dataloaders import ShippingMethodByIdLoader
from ..shipping.types import ShippingMethod
from ..warehouse.types import Allocation, Warehouse
-from .dataloaders import AllocationsByOrderLineIdLoader, OrderLinesByOrderIdLoader
+from .dataloaders import (
+ AllocationsByOrderLineIdLoader,
+ OrderByIdLoader,
+ OrderLinesByOrderIdLoader,
+)
from .enums import OrderEventsEmailsEnum, OrderEventsEnum
from .utils import validate_draft_order
@@ -79,6 +83,9 @@ class OrderEvent(CountableDjangoObjectType):
shipping_costs_included = graphene.Boolean(
description="Define if shipping costs were included to the refund."
)
+ related_order = graphene.Field(
+ lambda: Order, description="The order which is related to this order."
+ )
class Meta:
description = "History log of the order."
@@ -190,6 +197,13 @@ class OrderEvent(CountableDjangoObjectType):
def resolve_shipping_costs_included(root: models.OrderEvent, _info):
return root.parameters.get("shipping_costs_included")
+ @staticmethod
+ def resolve_related_order(root: models.OrderEvent, info):
+ order_pk = root.parameters.get("related_order_pk")
+ if not order_pk:
+ return None
+ return OrderByIdLoader(info.context).load(order_pk)
+
class FulfillmentLine(CountableDjangoObjectType):
order_line = graphene.Field(lambda: OrderLine)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 0939b68bf5..f04bd8ae86 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2023,9 +2023,21 @@ type FulfillmentRefundProducts {
orderErrors: [OrderError!]!
}
+type FulfillmentReturnProducts {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ returnFulfillment: Fulfillment
+ replaceFulfillment: Fulfillment
+ order: Order
+ replaceOrder: Order
+ orderErrors: [OrderError!]!
+}
+
enum FulfillmentStatus {
FULFILLED
REFUNDED
+ RETURNED
+ REPLACED
+ REFUNDED_AND_RETURNED
CANCELED
}
@@ -2678,6 +2690,7 @@ type Mutation {
orderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancel
orderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking
orderFulfillmentRefundProducts(input: OrderRefundProductsInput!, order: ID!): FulfillmentRefundProducts
+ orderFulfillmentReturnProducts(input: OrderReturnProductsInput!, order: ID!): FulfillmentReturnProducts
orderMarkAsPaid(id: ID!, transactionReference: String): OrderMarkAsPaid
orderRefund(amount: PositiveDecimal!, id: ID!): OrderRefund
orderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate
@@ -2975,8 +2988,7 @@ enum OrderErrorCode {
UNIQUE
VOID_INACTIVE_PAYMENT
ZERO_QUANTITY
- INVALID_REFUND_QUANTITY
- CANNOT_REFUND_FULFILLMENT_LINE
+ INVALID_QUANTITY
INSUFFICIENT_STOCK
DUPLICATED_INPUT_ITEM
NOT_AVAILABLE_IN_CHANNEL
@@ -3004,6 +3016,7 @@ type OrderEvent implements Node {
warehouse: Warehouse
transactionReference: String
shippingCostsIncluded: Boolean
+ relatedOrder: Order
}
type OrderEventCountableConnection {
@@ -3037,6 +3050,7 @@ enum OrderEventsEmailsEnum {
enum OrderEventsEnum {
DRAFT_CREATED
+ DRAFT_CREATED_FROM_REPLACE
DRAFT_ADDED_PRODUCTS
DRAFT_REMOVED_PRODUCTS
PLACED
@@ -3045,6 +3059,7 @@ enum OrderEventsEnum {
CANCELED
ORDER_MARKED_AS_PAID
ORDER_FULLY_PAID
+ ORDER_REPLACEMENT_CREATED
UPDATED_ADDRESS
EMAIL_SENT
CONFIRMED
@@ -3062,6 +3077,8 @@ enum OrderEventsEnum {
FULFILLMENT_RESTOCKED_ITEMS
FULFILLMENT_FULFILLED_ITEMS
FULFILLMENT_REFUNDED
+ FULFILLMENT_RETURNED
+ FULFILLMENT_REPLACED
TRACKING_UPDATED
NOTE_ADDED
OTHER
@@ -3154,6 +3171,26 @@ input OrderRefundProductsInput {
includeShippingCosts: Boolean = false
}
+input OrderReturnFulfillmentLineInput {
+ fulfillmentLineId: ID!
+ quantity: Int!
+ replace: Boolean = false
+}
+
+input OrderReturnLineInput {
+ orderLineId: ID!
+ quantity: Int!
+ replace: Boolean = false
+}
+
+input OrderReturnProductsInput {
+ orderLines: [OrderReturnLineInput!]
+ fulfillmentLines: [OrderReturnFulfillmentLineInput!]
+ amountToRefund: PositiveDecimal
+ includeShippingCosts: Boolean = false
+ refund: Boolean = false
+}
+
type OrderSettings {
automaticallyConfirmAllNewOrders: Boolean!
}
@@ -3196,6 +3233,8 @@ enum OrderStatus {
UNCONFIRMED
UNFULFILLED
PARTIALLY_FULFILLED
+ PARTIALLY_RETURNED
+ RETURNED
FULFILLED
CANCELED
}
diff --git a/saleor/order/__init__.py b/saleor/order/__init__.py
index 7262c098ab..37a4dd90af 100644
--- a/saleor/order/__init__.py
+++ b/saleor/order/__init__.py
@@ -1,3 +1,10 @@
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .models import FulfillmentLine, OrderLine
+
+
class OrderStatus:
DRAFT = "draft" # fully editable, not finalized order created by staff users
UNCONFIRMED = (
@@ -8,6 +15,11 @@ class OrderStatus:
"partially fulfilled" # order with some items marked as fulfilled
)
FULFILLED = "fulfilled" # order with all items marked as fulfilled
+
+ PARTIALLY_RETURNED = (
+ "partially_returned" # order with some items marked as returned
+ )
+ RETURNED = "returned" # order with all items marked as returned
CANCELED = "canceled" # permanently canceled order
CHOICES = [
@@ -15,6 +27,8 @@ class OrderStatus:
(UNCONFIRMED, "Unconfirmed"),
(UNFULFILLED, "Unfulfilled"),
(PARTIALLY_FULFILLED, "Partially fulfilled"),
+ (PARTIALLY_RETURNED, "Partially returned"),
+ (RETURNED, "Returned"),
(FULFILLED, "Fulfilled"),
(CANCELED, "Canceled"),
]
@@ -23,11 +37,19 @@ class OrderStatus:
class FulfillmentStatus:
FULFILLED = "fulfilled" # group of products in an order marked as fulfilled
REFUNDED = "refunded" # group of refunded products
+ RETURNED = "returned" # group of returned products
+ REFUNDED_AND_RETURNED = (
+ "refunded_and_returned" # group of returned and replaced products
+ )
+ REPLACED = "replaced" # group of replaced products
CANCELED = "canceled" # fulfilled group of products in an order marked as canceled
CHOICES = [
(FULFILLED, "Fulfilled"),
(REFUNDED, "Refunded"),
+ (RETURNED, "Returned"),
+ (REPLACED, "Replaced"),
+ (REFUNDED_AND_RETURNED, "Refunded and returned"),
(CANCELED, "Canceled"),
]
@@ -37,6 +59,8 @@ class OrderEvents:
CONFIRMED = "confirmed"
DRAFT_CREATED = "draft_created"
+ DRAFT_CREATED_FROM_REPLACE = "draft_created_from_replace"
+
DRAFT_ADDED_PRODUCTS = "draft_added_products"
DRAFT_REMOVED_PRODUCTS = "draft_removed_products"
@@ -48,6 +72,7 @@ class OrderEvents:
ORDER_MARKED_AS_PAID = "order_marked_as_paid"
ORDER_FULLY_PAID = "order_fully_paid"
+ ORDER_REPLACEMENT_CREATED = "order_replacement_created"
UPDATED_ADDRESS = "updated_address"
@@ -69,6 +94,8 @@ class OrderEvents:
FULFILLMENT_RESTOCKED_ITEMS = "fulfillment_restocked_items"
FULFILLMENT_FULFILLED_ITEMS = "fulfillment_fulfilled_items"
FULFILLMENT_REFUNDED = "fulfillment_refunded"
+ FULFILLMENT_RETURNED = "fulfillment_returned"
+ FULFILLMENT_REPLACED = "fulfillment_replaced"
TRACKING_UPDATED = "tracking_updated"
NOTE_ADDED = "note_added"
@@ -77,6 +104,7 @@ class OrderEvents:
CHOICES = [
(DRAFT_CREATED, "The draft order was created"),
+ (DRAFT_CREATED_FROM_REPLACE, "The draft order with replace lines was created"),
(DRAFT_ADDED_PRODUCTS, "Some products were added to the draft order"),
(DRAFT_REMOVED_PRODUCTS, "Some products were removed from the draft order"),
(PLACED, "The order was placed"),
@@ -85,6 +113,7 @@ class OrderEvents:
(CANCELED, "The order was canceled"),
(ORDER_MARKED_AS_PAID, "The order was manually marked as fully paid"),
(ORDER_FULLY_PAID, "The order was fully paid"),
+ (ORDER_REPLACEMENT_CREATED, "The draft order was created based on this order."),
(UPDATED_ADDRESS, "The address from the placed order was updated"),
(EMAIL_SENT, "The email was sent"),
(CONFIRMED, "Order was confirmed"),
@@ -102,6 +131,8 @@ class OrderEvents:
(FULFILLMENT_RESTOCKED_ITEMS, "The items of the fulfillment were restocked"),
(FULFILLMENT_FULFILLED_ITEMS, "Some items were fulfilled"),
(FULFILLMENT_REFUNDED, "Some items were refunded"),
+ (FULFILLMENT_RETURNED, "Some items were returned"),
+ (FULFILLMENT_REPLACED, "Some items were replaced"),
(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"),
@@ -132,3 +163,17 @@ class OrderEventsEmails:
(FULFILLMENT, "The fulfillment confirmation email was sent"),
(DIGITAL_LINKS, "The email containing the digital links was sent"),
]
+
+
+@dataclass
+class OrderLineData:
+ line: "OrderLine"
+ quantity: int
+ replace: bool = False
+
+
+@dataclass
+class FulfillmentLineData:
+ line: "FulfillmentLine"
+ quantity: int
+ replace: bool = False
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 1112f94d5a..6a5dc5a23f 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -1,10 +1,12 @@
import logging
+from copy import deepcopy
from decimal import Decimal
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
from django.contrib.sites.models import Site
from django.db import transaction
+from ..account.models import User
from ..core import analytics
from ..core.exceptions import AllocationError, InsufficientStock
from ..order.emails import send_order_confirmed
@@ -23,15 +25,29 @@ from ..warehouse.management import (
deallocate_stock_for_order,
decrease_stock,
)
-from . import FulfillmentStatus, OrderStatus, emails, events, utils
+from . import (
+ FulfillmentLineData,
+ FulfillmentStatus,
+ OrderLineData,
+ OrderStatus,
+ emails,
+ events,
+ utils,
+)
from .emails import (
send_fulfillment_confirmation_to_customer,
send_order_canceled_confirmation,
send_order_refunded_confirmation,
send_payment_confirmation,
)
-from .events import fulfillment_refunded_event
-from .models import Fulfillment, FulfillmentLine, OrderLine
+from .events import (
+ draft_order_created_from_replace_event,
+ fulfillment_refunded_event,
+ fulfillment_replaced_event,
+ fulfillment_returned_event,
+ order_replacement_created,
+)
+from .models import Fulfillment, FulfillmentLine, Order, OrderLine
from .utils import (
order_line_needs_automatic_fulfillment,
recalculate_order,
@@ -40,13 +56,15 @@ from .utils import (
)
if TYPE_CHECKING:
- from ..account.models import User
from ..warehouse.models import Warehouse
- from .models import Order
logger = logging.getLogger(__name__)
+OrderLineIDType = int
+QuantityType = int
+
+
def order_created(order: "Order", user: "User", from_draft: bool = False):
events.order_created_event(order=order, user=user, from_draft=from_draft)
manager = get_plugins_manager()
@@ -428,126 +446,108 @@ def _get_fulfillment_line_if_exists(
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]],
+def _get_fulfillment_line(
+ target_fulfillment: Fulfillment,
+ lines_in_target_fulfillment: List[FulfillmentLine],
+ order_line_id: int,
+ stock_id: Optional[int] = None,
+) -> Tuple[FulfillmentLine, bool]:
+ """Get fulfillment line if extists or create new fulfillment line object."""
+ # Check if line for order_line_id and stock_id does not exist in DB.
+ moved_line = _get_fulfillment_line_if_exists(
+ lines_in_target_fulfillment, order_line_id, stock_id,
+ )
+ fulfillment_line_existed = True
+ if not moved_line:
+ # Create new not saved FulfillmentLine object and assign it to target
+ # fulfillment
+ fulfillment_line_existed = False
+ moved_line = FulfillmentLine(
+ fulfillment=target_fulfillment,
+ order_line_id=order_line_id,
+ stock_id=stock_id,
+ quantity=0,
+ )
+ return moved_line, fulfillment_line_existed
+
+
+def _move_order_lines_to_target_fulfillment(
+ order_lines_to_move: List[OrderLineData],
+ lines_in_target_fulfillment: List[FulfillmentLine],
+ target_fulfillment: Fulfillment,
):
- """Proceed the refund for unfulfilled order lines."""
+ """Move order lines with given quantity to the target fulfillment."""
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
+ for line_data in order_lines_to_move:
+ line_to_move = line_data.line
+ quantity_to_move = line_data.quantity
+ moved_line, fulfillment_line_existed = _get_fulfillment_line(
+ target_fulfillment=target_fulfillment,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ order_line_id=line_to_move.id,
+ stock_id=None,
)
- 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
+ # calculate the quantity fulfilled/unfulfilled to move
+ unfulfilled_to_move = min(line_to_move.quantity_unfulfilled, quantity_to_move)
+ quantity_to_move -= unfulfilled_to_move
+ line_to_move.quantity_fulfilled += unfulfilled_to_move
+ moved_line.quantity += unfulfilled_to_move
# update current lines with new value of quantity
- order_lines_to_update.append(line_to_refund)
+ order_lines_to_update.append(line_to_move)
- 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
+ if moved_line.quantity > 0 and not fulfillment_line_existed:
+ # If this is new type of (order_line, stock) then we create new fulfillment
# line
- fulfillment_lines_to_create.append(refunded_line)
+ fulfillment_lines_to_create.append(moved_line)
elif fulfillment_line_existed:
- # if refund fulfillment already have the same line, we just update the
+ # if target fulfillment already have the same line, we just update the
# quantity
- fulfillment_lines_to_update.append(refunded_line)
+ fulfillment_lines_to_update.append(moved_line)
- line_allocations_exists = line_to_refund.allocations.exists()
+ line_allocations_exists = line_to_move.allocations.exists()
if line_allocations_exists:
try:
- deallocate_stock(line_to_refund, unfulfilled_to_refund)
+ deallocate_stock(line_to_move, unfulfilled_to_move)
except AllocationError:
- logger.warning(
- f"Unable to deallocate stock for line {line_to_refund.id}"
- )
-
- # prepare structure which will be used to create new order event.
- all_refunded_lines[line_to_refund.id] = (
- unfulfilled_to_refund,
- line_to_refund,
- )
+ logger.warning(f"Unable to deallocate stock for line {line_to_move.id}")
- # update the fulfillment lines with new calues
+ # update the fulfillment lines with new values
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]],
+def _move_fulfillment_lines_to_target_fulfillment(
+ fulfillment_lines_to_move: List[FulfillmentLineData],
+ lines_in_target_fulfillment: List[FulfillmentLine],
+ target_fulfillment: Fulfillment,
):
- """Proceed the refund for fulfillment lines."""
+ """Move fulfillment lines with given quantity to the target fulfillment."""
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
+ for fulfillment_line_data in fulfillment_lines_to_move:
+ fulfillment_line = fulfillment_line_data.line
+ quantity_to_move = fulfillment_line_data.quantity
- order_line: OrderLine = order_lines_with_fulfillment.get( # type: ignore
- fulfillment_line.order_line_id
+ moved_line, fulfillment_line_existed = _get_fulfillment_line(
+ target_fulfillment=target_fulfillment,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ order_line_id=fulfillment_line.order_line_id,
+ stock_id=fulfillment_line.stock_id,
)
- refund_amount += order_line.unit_price_gross_amount * fulfilled_to_refund
+
+ # calculate the quantity fulfilled/unfulfilled/to move
+ fulfilled_to_move = min(fulfillment_line.quantity, quantity_to_move)
+ quantity_to_move -= fulfilled_to_move
+ moved_line.quantity += fulfilled_to_move
+ fulfillment_line.quantity -= fulfilled_to_move
if fulfillment_line.quantity == 0:
# the fulfillment line without any items will be deleted
@@ -556,26 +556,16 @@ def _refund_fulfillment_for_fulfillment_lines(
# 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
+ if moved_line.quantity > 0 and not fulfillment_line_existed:
+ # If this is new type of (order_line, stock) then we create new fulfillment
# line
- fulfillment_lines_to_create.append(refunded_line)
+ fulfillment_lines_to_create.append(moved_line)
elif fulfillment_line_existed:
- # if refund fulfillment already have the same line, we just update the
+ # if target 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)
+ fulfillment_lines_to_update.append(moved_line)
- # update the fulfillment lines with new calues
+ # update the fulfillment lines with new values
FulfillmentLine.objects.bulk_update(fulfillment_lines_to_update, ["quantity"])
FulfillmentLine.objects.bulk_create(fulfillment_lines_to_create)
@@ -583,17 +573,14 @@ def _refund_fulfillment_for_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],
+ order_lines_to_refund: List[OrderLineData],
+ fulfillment_lines_to_refund: List[FulfillmentLineData],
amount=None,
refund_shipping_costs=False,
):
@@ -607,32 +594,386 @@ def create_refund_fulfillment(
refunded line. The refund fulfillment can have assigned lines with the same
products but with the different stocks.
"""
+
+ _process_refund(
+ requester=requester,
+ order=order,
+ payment=payment,
+ order_lines_to_refund=order_lines_to_refund,
+ fulfillment_lines_to_refund=fulfillment_lines_to_refund,
+ amount=amount,
+ refund_shipping_costs=refund_shipping_costs,
+ )
+
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,
+ _move_order_lines_to_target_fulfillment(
+ order_lines_to_move=order_lines_to_refund,
+ lines_in_target_fulfillment=already_refunded_lines,
+ target_fulfillment=refunded_fulfillment,
)
- 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,
+ _move_fulfillment_lines_to_target_fulfillment(
+ fulfillment_lines_to_move=fulfillment_lines_to_refund,
+ lines_in_target_fulfillment=already_refunded_lines,
+ target_fulfillment=refunded_fulfillment,
)
- refund_amount = refund_order_lines + refund_fulfillment_lines
Fulfillment.objects.filter(order=order, lines=None).delete()
+ return refunded_fulfillment
+
+
+def create_replace_order(
+ requester: Optional["User"],
+ original_order: "Order",
+ order_lines_to_replace: List[OrderLineData],
+ fulfillment_lines_to_replace: List[FulfillmentLineData],
+) -> "Order":
+ """Create draft order with lines to replace."""
+ replace_order = Order()
+ replace_order.status = OrderStatus.DRAFT
+ replace_order.user_id = original_order.user_id
+ replace_order.language_code = original_order.language_code
+ replace_order.user_email = original_order.user_email
+ replace_order.currency = original_order.currency
+ replace_order.channel = original_order.channel
+ replace_order.display_gross_prices = original_order.display_gross_prices
+ replace_order.redirect_url = original_order.redirect_url
+
+ if original_order.billing_address:
+ original_order.billing_address.pk = None
+ replace_order.billing_address = original_order.billing_address
+ replace_order.billing_address.save()
+ if original_order.shipping_address:
+ original_order.shipping_address.pk = None
+ replace_order.shipping_address = original_order.shipping_address
+ replace_order.shipping_address.save()
+ replace_order.save()
+ original_order.refresh_from_db()
+
+ order_line_to_create: Dict[OrderLineIDType, OrderLine] = dict()
+
+ # iterate over lines without fulfillment to get the items for replace.
+ # deepcopy to not lose the refence for lines assigned to original order
+ for line_data in deepcopy(order_lines_to_replace):
+ order_line = line_data.line
+ order_line_id = order_line.pk
+ order_line.pk = None
+ order_line.order = replace_order
+ order_line.quantity = line_data.quantity
+ order_line.quantity_fulfilled = 0
+ # we set order_line_id as a key to use it for iterating over fulfillment items
+ order_line_to_create[order_line_id] = order_line
+
+ order_lines_with_fulfillment = OrderLine.objects.in_bulk(
+ [line_data.line.order_line_id for line_data in fulfillment_lines_to_replace]
+ )
+ for fulfillment_line_data in fulfillment_lines_to_replace:
+ fulfillment_line = fulfillment_line_data.line
+ order_line_id = fulfillment_line.order_line_id
+
+ # if order_line_id exists in order_line_to_create, it means that we already have
+ # prepared new order_line for this fulfillment. In that case we need to increase
+ # quantity amount of new order_line by fulfillment_line.quantity
+ if order_line_id in order_line_to_create:
+ order_line_to_create[
+ order_line_id
+ ].quantity += fulfillment_line_data.quantity
+ continue
+
+ order_line_from_fulfillment = order_lines_with_fulfillment.get(order_line_id)
+ order_line = order_line_from_fulfillment # type: ignore
+ order_line_id = order_line.pk
+ order_line.pk = None
+ order_line.order = replace_order
+ order_line.quantity = fulfillment_line_data.quantity
+ order_line.quantity_fulfilled = 0
+ order_line_to_create[order_line_id] = order_line
+
+ lines_to_create = order_line_to_create.values()
+ OrderLine.objects.bulk_create(lines_to_create)
+
+ recalculate_order(replace_order)
+
+ draft_order_created_from_replace_event(
+ draft_order=replace_order,
+ original_order=original_order,
+ user=requester,
+ lines=[(line.quantity, line) for line in lines_to_create],
+ )
+ return replace_order
+
+
+def _move_lines_to_return_fulfillment(
+ order_lines: List[OrderLineData],
+ fulfillment_lines: List[FulfillmentLineData],
+ fulfillment_status: str,
+ order: "Order",
+) -> Fulfillment:
+ target_fulfillment, _ = Fulfillment.objects.get_or_create(
+ status=fulfillment_status, order=order
+ )
+ lines_in_target_fulfillment = list(target_fulfillment.lines.all())
+ _move_order_lines_to_target_fulfillment(
+ order_lines_to_move=order_lines,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ target_fulfillment=target_fulfillment,
+ )
+
+ fulfillment_lines_already_refunded = FulfillmentLine.objects.filter(
+ fulfillment__order=order, fulfillment__status=FulfillmentStatus.REFUNDED
+ ).values_list("id", flat=True)
+
+ refunded_fulfillment_lines_to_return = []
+ fulfillment_lines_to_return = []
+
+ for line_data in fulfillment_lines:
+ if line_data.line.id in fulfillment_lines_already_refunded:
+ # item already refunded should be moved to fulfillment with status
+ # REFUNDED_AND_RETURNED
+ refunded_fulfillment_lines_to_return.append(line_data)
+ else:
+ # the rest of the items should be moved to target fulfillment
+ fulfillment_lines_to_return.append(line_data)
+
+ _move_fulfillment_lines_to_target_fulfillment(
+ fulfillment_lines_to_move=fulfillment_lines_to_return,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ target_fulfillment=target_fulfillment,
+ )
+
+ if refunded_fulfillment_lines_to_return:
+ refund_and_return_fulfillment, _ = Fulfillment.objects.get_or_create(
+ status=FulfillmentStatus.REFUNDED_AND_RETURNED, order=order
+ )
+ lines_in_target_fulfillment = list(refund_and_return_fulfillment.lines.all())
+ _move_fulfillment_lines_to_target_fulfillment(
+ fulfillment_lines_to_move=refunded_fulfillment_lines_to_return,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ target_fulfillment=refund_and_return_fulfillment,
+ )
+
+ return target_fulfillment
+
+
+def _move_lines_to_replace_fulfillment(
+ order_lines_to_replace: List[OrderLineData],
+ fulfillment_lines_to_replace: List[FulfillmentLineData],
+ order: "Order",
+) -> Fulfillment:
+ target_fulfillment, _ = Fulfillment.objects.get_or_create(
+ status=FulfillmentStatus.REPLACED, order=order
+ )
+ lines_in_target_fulfillment = list(target_fulfillment.lines.all())
+ _move_order_lines_to_target_fulfillment(
+ order_lines_to_move=order_lines_to_replace,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ target_fulfillment=target_fulfillment,
+ )
+ _move_fulfillment_lines_to_target_fulfillment(
+ fulfillment_lines_to_move=fulfillment_lines_to_replace,
+ lines_in_target_fulfillment=lines_in_target_fulfillment,
+ target_fulfillment=target_fulfillment,
+ )
+ return target_fulfillment
+
+
+def create_return_fulfillment(
+ requester: Optional["User"],
+ order: "Order",
+ order_lines: List[OrderLineData],
+ fulfillment_lines: List[FulfillmentLineData],
+ refund: bool = False,
+) -> Fulfillment:
+ status = FulfillmentStatus.RETURNED
+ if refund:
+ status = FulfillmentStatus.REFUNDED_AND_RETURNED
+ with transaction.atomic():
+ return_fulfillment = _move_lines_to_return_fulfillment(
+ order_lines=order_lines,
+ fulfillment_lines=fulfillment_lines,
+ fulfillment_status=status,
+ order=order,
+ )
+ returned_lines: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ order_lines_with_fulfillment = OrderLine.objects.in_bulk(
+ [line_data.line.order_line_id for line_data in fulfillment_lines]
+ )
+ for line_data in order_lines:
+ returned_lines[line_data.line.id] = (line_data.quantity, line_data.line)
+ for line_data in fulfillment_lines:
+ order_line = order_lines_with_fulfillment.get(line_data.line.order_line_id)
+ returned_line = returned_lines.get(order_line.id) # type: ignore
+ if returned_line:
+ quantity, line = returned_line
+ quantity += line_data.quantity
+ returned_lines[order_line.id] = (quantity, line) # type: ignore
+ else:
+ returned_lines[order_line.id] = ( # type: ignore
+ line_data.quantity,
+ order_line,
+ )
+
+ fulfillment_returned_event(
+ order=order, user=requester, returned_lines=list(returned_lines.values()),
+ )
+ return return_fulfillment
+
+
+def process_replace(
+ requester: Optional["User"],
+ order: "Order",
+ order_lines: List[OrderLineData],
+ fulfillment_lines: List[FulfillmentLineData],
+) -> Tuple[Fulfillment, Optional["Order"]]:
+ """Create replace fulfillment and new draft order.
+
+ Move all requested lines to fulfillment with status replaced. Based on original
+ order create the draft order with all user details, and requested lines.
+ """
+
+ replace_fulfillment = _move_lines_to_replace_fulfillment(
+ order_lines_to_replace=order_lines,
+ fulfillment_lines_to_replace=fulfillment_lines,
+ order=order,
+ )
+ new_order = create_replace_order(
+ requester=requester,
+ original_order=order,
+ order_lines_to_replace=order_lines,
+ fulfillment_lines_to_replace=fulfillment_lines,
+ )
+ replaced_lines = [(line.quantity, line) for line in new_order.lines.all()]
+ fulfillment_replaced_event(
+ order=order, user=requester, replaced_lines=replaced_lines,
+ )
+ order_replacement_created(
+ original_order=order, replace_order=new_order, user=requester,
+ )
+ # TODO call order_returned
+
+ return replace_fulfillment, new_order
+
+
+def create_fulfillments_for_returned_products(
+ requester: Optional["User"],
+ order: "Order",
+ payment: Optional[Payment],
+ order_lines: List[OrderLineData],
+ fulfillment_lines: List[FulfillmentLineData],
+ refund: bool = False,
+ amount: Optional[Decimal] = None,
+ refund_shipping_costs=False,
+) -> Tuple[Fulfillment, Optional[Fulfillment], Optional[Order]]:
+ """Process the request for replacing or returning the products.
+
+ Process the refund when the refund is set to True. The amount of refund will be
+ calculated for all lines with statuses different from refunded. The lines which
+ are set to replace will not be included in the refund amount.
+
+ If the amount is provided, the refund will be used for this amount.
+
+ If refund_shipping_costs is True, the calculated refund amount will include
+ shipping costs.
+
+ All lines with replace set to True will be used to create a new draft order, with
+ the same order details as the original order. These lines will be moved to
+ fulfillment with status replaced. The events with relation to new order will be
+ created.
+
+ All lines with replace set to False will be moved to fulfillment with status
+ returned/refunded_and_returned - depends on refund flag and current line status.
+ If the fulfillment line has refunded status it will be moved to
+ returned_and_refunded
+ """
+ return_order_lines = [data for data in order_lines if not data.replace]
+ return_fulfillment_lines = [data for data in fulfillment_lines if not data.replace]
+ if refund and payment:
+ _process_refund(
+ requester=requester,
+ order=order,
+ payment=payment,
+ order_lines_to_refund=return_order_lines,
+ fulfillment_lines_to_refund=return_fulfillment_lines,
+ amount=amount,
+ refund_shipping_costs=refund_shipping_costs,
+ )
+
+ with transaction.atomic():
+ replace_order_lines = [data for data in order_lines if data.replace]
+ replace_fulfillment_lines = [data for data in fulfillment_lines if data.replace]
+
+ replace_fulfillment, new_order = None, None
+ if replace_order_lines or replace_fulfillment_lines:
+ replace_fulfillment, new_order = process_replace(
+ requester=requester,
+ order=order,
+ order_lines=replace_order_lines,
+ fulfillment_lines=replace_fulfillment_lines,
+ )
+ return_fulfillment = create_return_fulfillment(
+ requester=requester,
+ order=order,
+ order_lines=return_order_lines,
+ fulfillment_lines=return_fulfillment_lines,
+ refund=refund,
+ )
+ Fulfillment.objects.filter(order=order, lines=None).delete()
+ return return_fulfillment, replace_fulfillment, new_order
+
+
+def _calculate_refund_amount(
+ return_order_lines: List[OrderLineData],
+ return_fulfillment_lines: List[FulfillmentLineData],
+ lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]],
+) -> Decimal:
+ refund_amount = Decimal(0)
+ for line_data in return_order_lines:
+ refund_amount += line_data.quantity * line_data.line.unit_price_gross_amount
+ lines_to_refund[line_data.line.id] = (line_data.quantity, line_data.line)
+
+ if not return_fulfillment_lines:
+ return refund_amount
+
+ order_lines_with_fulfillment = OrderLine.objects.in_bulk(
+ [line_data.line.order_line_id for line_data in return_fulfillment_lines]
+ )
+ for line_data in return_fulfillment_lines:
+ # skip lines which were already refunded
+ if line_data.line.fulfillment.status == FulfillmentStatus.REFUNDED:
+ continue
+ order_line = order_lines_with_fulfillment[line_data.line.order_line_id]
+ refund_amount += line_data.quantity * order_line.unit_price_gross_amount
+
+ data_from_all_refunded_lines = lines_to_refund.get(order_line.id)
+ if data_from_all_refunded_lines:
+ quantity, line = data_from_all_refunded_lines
+ quantity += line_data.quantity
+ lines_to_refund[order_line.id] = (quantity, line)
+ else:
+ lines_to_refund[order_line.id] = (line_data.quantity, order_line)
+ return refund_amount
+
+
+def _process_refund(
+ requester: Optional["User"],
+ order: "Order",
+ payment: Payment,
+ order_lines_to_refund: List[OrderLineData],
+ fulfillment_lines_to_refund: List[FulfillmentLineData],
+ amount: Optional[Decimal],
+ refund_shipping_costs: bool,
+):
+ lines_to_refund: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
+ refund_amount = _calculate_refund_amount(
+ order_lines_to_refund, fulfillment_lines_to_refund, lines_to_refund
+ )
if amount is None:
amount = refund_amount
# we take into consideration the shipping costs only when amount is not
@@ -647,8 +988,7 @@ def create_refund_fulfillment(
fulfillment_refunded_event(
order=order,
user=requester,
- refunded_lines=list(all_refunded_lines.values()),
+ refunded_lines=list(lines_to_refund.values()),
amount=amount,
shipping_costs_included=refund_shipping_costs,
)
- return refunded_fulfillment
diff --git a/saleor/order/error_codes.py b/saleor/order/error_codes.py
index 84c963709d..442d84dc24 100644
--- a/saleor/order/error_codes.py
+++ b/saleor/order/error_codes.py
@@ -25,8 +25,7 @@ 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"
+ INVALID_QUANTITY = "invalid_quantity"
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.py
index 8960cd02e1..0314de8360 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -139,6 +139,27 @@ def draft_order_removed_products_event(
)
+def draft_order_created_from_replace_event(
+ *,
+ draft_order: Order,
+ original_order: Order,
+ user: UserType,
+ lines: List[Tuple[int, OrderLine]]
+):
+ if not _user_is_valid(user):
+ user = None
+ parameters = {
+ "related_order_pk": original_order.pk,
+ "lines": _lines_per_quantity_to_line_object_list(lines),
+ }
+ return OrderEvent.objects.create(
+ order=draft_order,
+ type=OrderEvents.DRAFT_CREATED_FROM_REPLACE,
+ user=user,
+ parameters=parameters,
+ )
+
+
def order_created_event(
*, order: Order, user: UserType, from_draft=False
) -> OrderEvent:
@@ -208,6 +229,20 @@ def order_fully_paid_event(*, order: Order, user: UserType) -> OrderEvent:
)
+def order_replacement_created(
+ *, original_order: Order, replace_order: Order, user: UserType
+) -> OrderEvent:
+ if not _user_is_valid(user):
+ user = None
+ parameters = {"related_order_pk": replace_order.pk}
+ return OrderEvent.objects.create(
+ order=original_order,
+ type=OrderEvents.ORDER_REPLACEMENT_CREATED,
+ user=user,
+ parameters=parameters,
+ )
+
+
def payment_authorized_event(
*, order: Order, user: UserType, amount: Decimal, payment: Payment
) -> OrderEvent:
@@ -338,6 +373,33 @@ def fulfillment_fulfilled_items_event(
)
+def fulfillment_returned_event(
+ *, order: Order, user: UserType, returned_lines: List[Tuple[int, OrderLine]],
+):
+ if not _user_is_valid(user):
+ user = None
+
+ return OrderEvent.objects.create(
+ order=order,
+ type=OrderEvents.FULFILLMENT_RETURNED,
+ user=user,
+ parameters={"lines": _lines_per_quantity_to_line_object_list(returned_lines)},
+ )
+
+
+def fulfillment_replaced_event(
+ *, order: Order, user: UserType, replaced_lines: List[Tuple[int, OrderLine]],
+):
+ if not _user_is_valid(user):
+ user = None
+ return OrderEvent.objects.create(
+ order=order,
+ type=OrderEvents.FULFILLMENT_REPLACED,
+ user=user,
+ parameters={"lines": _lines_per_quantity_to_line_object_list(replaced_lines)},
+ )
+
+
def fulfillment_refunded_event(
*,
order: Order,
diff --git a/saleor/order/migrations/0094_auto_20201216_1505.py b/saleor/order/migrations/0094_auto_20201216_1505.py
new file mode 100644
index 0000000000..003913aca4
--- /dev/null
+++ b/saleor/order/migrations/0094_auto_20201216_1505.py
@@ -0,0 +1,89 @@
+# Generated by Django 3.1.4 on 2020-12-16 15:05
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0093_auto_20201130_1406"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="fulfillment",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("fulfilled", "Fulfilled"),
+ ("refunded", "Refunded"),
+ ("returned", "Returned"),
+ ("replaced", "Replaced"),
+ ("refunded_and_returned", "Refunded and returned"),
+ ("canceled", "Canceled"),
+ ],
+ default="fulfilled",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="order",
+ name="status",
+ field=models.CharField(
+ choices=[
+ ("draft", "Draft"),
+ ("unconfirmed", "Unconfirmed"),
+ ("unfulfilled", "Unfulfilled"),
+ ("partially fulfilled", "Partially fulfilled"),
+ ("partially_returned", "Partially returned"),
+ ("returned", "Returned"),
+ ("fulfilled", "Fulfilled"),
+ ("canceled", "Canceled"),
+ ],
+ default="unfulfilled",
+ max_length=32,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="orderevent",
+ name="type",
+ field=models.CharField(
+ choices=[
+ ("DRAFT_CREATED", "draft_created"),
+ ("DRAFT_CREATED_FROM_REPLACE", "draft_created_from_replace"),
+ ("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"),
+ ("ORDER_REPLACEMENT_CREATED", "order_replacement_created"),
+ ("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"),
+ ("FULFILLMENT_RETURNED", "fulfillment_returned"),
+ ("FULFILLMENT_REPLACED", "fulfillment_replaced"),
+ ("TRACKING_UPDATED", "tracking_updated"),
+ ("NOTE_ADDED", "note_added"),
+ ("OTHER", "other"),
+ ],
+ max_length=255,
+ ),
+ ),
+ ]
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 19f400bc19..e94125baca 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -15,13 +15,12 @@ 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, FulfillmentLine
+from ..models import Fulfillment
@pytest.fixture
@@ -317,332 +316,3 @@ def test_fulfill_digital_lines(
assert fulfillment_lines.count() == 1
assert line.digital_content_url
assert 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
diff --git a/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
new file mode 100644
index 0000000000..8b80afc28e
--- /dev/null
+++ b/saleor/order/tests/test_order_actions_create_fulfillments_for_returned_products.py
@@ -0,0 +1,740 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+from prices import Money, TaxedMoney
+
+from ...warehouse.models import Allocation, Stock
+from .. import FulfillmentLineData, FulfillmentStatus, OrderEvents, OrderLineData
+from ..actions import create_fulfillments_for_returned_products
+from ..models import Fulfillment, FulfillmentLine
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_only_order_lines(
+ mocked_refund, order_with_lines, payment_dummy_fully_charged, staff_user
+):
+ order_with_lines.payments.add(payment_dummy_fully_charged)
+ payment = order_with_lines.get_last_payment()
+
+ order_lines_to_return = order_with_lines.lines.all()
+ original_quantity = {
+ line.id: line.quantity_unfulfilled for line in order_with_lines
+ }
+ order_line_ids = order_lines_to_return.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()
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=order_with_lines,
+ payment=payment,
+ order_lines=[
+ OrderLineData(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ],
+ fulfillment_lines=[],
+ )
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.RETURNED
+ 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_return:
+ 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
+ )
+ assert not mocked_refund.called
+ assert not replace_order
+
+ # check if we have correct events
+ events = order_with_lines.events.all()
+ assert events.count() == 1
+ returned_event = events[0]
+ assert returned_event.type == OrderEvents.FULFILLMENT_RETURNED
+ assert len(returned_event.parameters["lines"]) == 2
+ event_lines = returned_event.parameters["lines"]
+ assert order_lines_to_return.filter(id=event_lines[0]["line_pk"]).exists()
+ assert event_lines[0]["quantity"] == 2
+
+ assert order_lines_to_return.filter(id=event_lines[1]["line_pk"]).exists()
+ assert event_lines[1]["quantity"] == 2
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_only_order_lines_with_refund(
+ mocked_refund, order_with_lines, payment_dummy_fully_charged, staff_user
+):
+ order_with_lines.payments.add(payment_dummy_fully_charged)
+ payment = order_with_lines.get_last_payment()
+
+ order_lines_to_return = order_with_lines.lines.all()
+ original_quantity = {
+ line.id: line.quantity_unfulfilled for line in order_with_lines
+ }
+ order_line_ids = order_lines_to_return.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()
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=order_with_lines,
+ payment=payment,
+ order_lines=[
+ OrderLineData(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ],
+ fulfillment_lines=[],
+ refund=True,
+ )
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.REFUNDED_AND_RETURNED
+ 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_return:
+ 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_return])
+ mocked_refund.assert_called_once_with(payment_dummy_fully_charged, amount)
+ assert not replace_order
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
+ mocked_refund, order_with_lines, payment_dummy_fully_charged, staff_user
+):
+ order_with_lines.payments.add(payment_dummy_fully_charged)
+ payment = order_with_lines.get_last_payment()
+
+ order_lines_to_return = order_with_lines.lines.all()
+ original_quantity = {
+ line.id: line.quantity_unfulfilled for line in order_with_lines
+ }
+ order_line_ids = order_lines_to_return.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()
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=order_with_lines,
+ payment=payment,
+ order_lines=[
+ OrderLineData(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ],
+ fulfillment_lines=[],
+ refund=True,
+ refund_shipping_costs=True,
+ )
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.REFUNDED_AND_RETURNED
+ 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_return:
+ 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_return])
+ amount += order_with_lines.shipping_price_gross_amount
+ mocked_refund.assert_called_once_with(payment_dummy_fully_charged, amount)
+ assert not replace_order
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_only_order_lines_with_replace_request(
+ mocked_refund, order_with_lines, payment_dummy_fully_charged, staff_user
+):
+ order_with_lines.payments.add(payment_dummy_fully_charged)
+ payment = order_with_lines.get_last_payment()
+
+ order_lines_to_return = order_with_lines.lines.all()
+ original_quantity = {
+ line.id: line.quantity_unfulfilled for line in order_with_lines
+ }
+ order_line_ids = order_lines_to_return.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()
+ quantity_to_replace = 2
+ order_lines_data = [
+ OrderLineData(line=line, quantity=2, replace=False)
+ for line in order_lines_to_return
+ ]
+
+ # set replace request for the first line
+ order_lines_data[0].replace = True
+ order_lines_data[0].quantity = quantity_to_replace
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=order_with_lines,
+ payment=payment,
+ order_lines=order_lines_data,
+ fulfillment_lines=[],
+ )
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.RETURNED
+ # we replaced one line
+ assert len(returned_fulfillment_lines) == lines_count - 1
+
+ for fulfillment_line in returned_fulfillment_lines:
+ assert fulfillment_line.quantity == 2
+ assert fulfillment_line.order_line_id in order_line_ids
+
+ order_lines_to_return = order_with_lines.lines.all()
+ for line in order_lines_to_return:
+ assert line.quantity_unfulfilled == original_quantity.get(line.pk) - 2
+
+ replaced_fulfillment_lines = replaced_fulfillment.lines.all()
+ assert replaced_fulfillment_lines.count() == 1
+ assert replaced_fulfillment_lines[0].quantity == quantity_to_replace
+ assert replaced_fulfillment_lines[0].order_line_id == order_lines_data[0].line.id
+
+ 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
+ )
+
+ order_with_lines.refresh_from_db()
+
+ # refund should not be called
+ assert not mocked_refund.called
+
+ # new order should have own id
+ assert replace_order.id != order_with_lines.id
+
+ # make sure that we have new instances of addresses
+ assert replace_order.shipping_address.id != order_with_lines.shipping_address.id
+ assert replace_order.billing_address.id != order_with_lines.billing_address.id
+
+ # the rest of address data should be the same
+ replace_order.shipping_address.id = None
+ order_with_lines.shipping_address.id = None
+ assert replace_order.shipping_address == order_with_lines.shipping_address
+
+ replace_order.billing_address.id = None
+ order_with_lines.billing_address.id = None
+ assert replace_order.billing_address == order_with_lines.billing_address
+
+ expected_replaced_line = order_lines_to_return[0]
+
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.first()
+ # make sure that all data from original line is in replaced line
+ assert replaced_line.variant_id == expected_replaced_line.variant_id
+ assert replaced_line.product_name == expected_replaced_line.product_name
+ assert replaced_line.variant_name == expected_replaced_line.variant_name
+ assert replaced_line.product_sku == expected_replaced_line.product_sku
+ assert (
+ replaced_line.is_shipping_required
+ == expected_replaced_line.is_shipping_required
+ )
+ assert replaced_line.quantity == quantity_to_replace
+ assert replaced_line.quantity_fulfilled == 0
+ assert replaced_line.currency == expected_replaced_line.currency
+ assert (
+ replaced_line.unit_price_net_amount
+ == expected_replaced_line.unit_price_net_amount
+ )
+ assert (
+ replaced_line.unit_price_gross_amount
+ == expected_replaced_line.unit_price_gross_amount
+ )
+ assert replaced_line.tax_rate == expected_replaced_line.tax_rate
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_multiple_order_line_returns(
+ mocked_refund, order_with_lines, payment_dummy_fully_charged, staff_user
+):
+ order_with_lines.payments.add(payment_dummy_fully_charged)
+ payment = order_with_lines.get_last_payment()
+ order_lines_to_return = order_with_lines.lines.all()
+ original_quantity = {
+ line.id: line.quantity_unfulfilled for line in order_with_lines
+ }
+ order_line_ids = order_lines_to_return.values_list("id", flat=True)
+ lines_count = order_lines_to_return.count()
+
+ for _ in range(2):
+ # call refund two times
+ create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=order_with_lines,
+ payment=payment,
+ order_lines=[
+ OrderLineData(line=line, quantity=1) for line in order_lines_to_return
+ ],
+ fulfillment_lines=[],
+ refund=True,
+ )
+
+ returned_fulfillemnt = Fulfillment.objects.get(
+ order=order_with_lines, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ returned_fulfillment_lines = returned_fulfillemnt.lines.all()
+ 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_return:
+ 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_return_fulfillment_only_fulfillment_lines(
+ mocked_refund, fulfilled_order, payment_dummy_fully_charged, staff_user
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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}
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[],
+ fulfillment_lines=[
+ FulfillmentLineData(line=line, quantity=2, replace=False)
+ for line in fulfillment_lines
+ ],
+ )
+
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.RETURNED
+ assert returned_fulfillment_lines.count() == 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 not mocked_refund.called
+ assert not replace_order
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_only_fulfillment_lines_replace_order(
+ mocked_refund, fulfilled_order, payment_dummy_fully_charged, staff_user
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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}
+
+ # Prepare the structure for return method
+ fulfillment_lines_to_return = [
+ FulfillmentLineData(line=line, quantity=2, replace=False)
+ for line in fulfillment_lines
+ ]
+ # The line which should be replaced
+ replace_quantity = 2
+ fulfillment_lines_to_return[0].replace = True
+ fulfillment_lines_to_return[0].quantity = replace_quantity
+
+ response = create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[],
+ fulfillment_lines=fulfillment_lines_to_return,
+ )
+
+ returned_fulfillment, replaced_fulfillment, replace_order = response
+
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+ assert returned_fulfillment.status == FulfillmentStatus.RETURNED
+ # make sure that all order lines from refund are in expected fulfillment
+ # minus one as we replaced the one item
+ assert returned_fulfillment_lines.count() == len(order_line_ids) - 1
+
+ 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
+
+ replaced_fulfillment_lines = replaced_fulfillment.lines.all()
+ assert replaced_fulfillment_lines.count() == 1
+ assert replaced_fulfillment_lines[0].quantity == replace_quantity
+ assert (
+ replaced_fulfillment_lines[0].order_line_id
+ == fulfillment_lines_to_return[0].line.order_line_id
+ )
+
+ assert not mocked_refund.called
+
+ # new order should have own id
+ assert replace_order.id != fulfilled_order.id
+
+ # make sure that we have new instances of addresses
+ assert replace_order.shipping_address.id != fulfilled_order.shipping_address.id
+ assert replace_order.billing_address.id != fulfilled_order.billing_address.id
+
+ # the rest of address data should be the same
+ replace_order.shipping_address.id = None
+ fulfilled_order.shipping_address.id = None
+ assert replace_order.shipping_address == fulfilled_order.shipping_address
+
+ replace_order.billing_address.id = None
+ fulfilled_order.billing_address.id = None
+ assert replace_order.billing_address == fulfilled_order.billing_address
+
+ expected_replaced_line = fulfillment_lines[0].order_line
+
+ assert replace_order.lines.count() == 1
+ replaced_line = replace_order.lines.first()
+ # make sure that all data from original line is in replaced line
+ assert replaced_line.variant_id == expected_replaced_line.variant_id
+ assert replaced_line.product_name == expected_replaced_line.product_name
+ assert replaced_line.variant_name == expected_replaced_line.variant_name
+ assert replaced_line.product_sku == expected_replaced_line.product_sku
+ assert (
+ replaced_line.is_shipping_required
+ == expected_replaced_line.is_shipping_required
+ )
+ assert replaced_line.quantity == replace_quantity
+ assert replaced_line.quantity_fulfilled == 0
+ assert replaced_line.currency == expected_replaced_line.currency
+ assert (
+ replaced_line.unit_price_net_amount
+ == expected_replaced_line.unit_price_net_amount
+ )
+ assert (
+ replaced_line.unit_price_gross_amount
+ == expected_replaced_line.unit_price_gross_amount
+ )
+ assert replaced_line.tax_rate == expected_replaced_line.tax_rate
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_multiple_fulfillment_lines_returns(
+ mocked_refund, fulfilled_order, payment_dummy_fully_charged, staff_user
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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_to_return = fulfillment_lines
+
+ for _ in range(2):
+ create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[],
+ fulfillment_lines=[
+ FulfillmentLineData(line=line, quantity=1)
+ for line in fulfillment_lines_to_return
+ ],
+ refund=True,
+ )
+
+ returned_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+
+ assert returned_fulfillment_lines.count() == 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_return_fulfillment_multiple_lines_returns(
+ mocked_refund,
+ fulfilled_order,
+ payment_dummy_fully_charged,
+ staff_user,
+ channel_USD,
+ variant,
+ warehouse,
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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_to_return = fulfillment_lines
+
+ 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
+ )
+
+ for _ in range(2):
+ create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[OrderLineData(line=order_line, quantity=1)],
+ fulfillment_lines=[
+ FulfillmentLineData(line=line, quantity=1)
+ for line in fulfillment_lines_to_return
+ ],
+ refund=True,
+ )
+
+ returned_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+
+ assert returned_fulfillment_lines.count() == 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_return_fulfillment_multiple_lines_without_refund(
+ mocked_refund,
+ fulfilled_order,
+ payment_dummy_fully_charged,
+ staff_user,
+ channel_USD,
+ variant,
+ warehouse,
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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_to_return = fulfillment_lines
+
+ 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
+ )
+ refunded_fulfillment = Fulfillment.objects.create(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED
+ )
+ refunded_fulfillment_line = refunded_fulfillment.lines.create(
+ order_line=order_line, quantity=2
+ )
+
+ fulfillment_lines_to_process = [
+ FulfillmentLineData(line=line, quantity=1)
+ for line in fulfillment_lines_to_return
+ ]
+ fulfillment_lines_to_process.append(
+ FulfillmentLineData(line=refunded_fulfillment_line, quantity=1)
+ )
+ for _ in range(2):
+ create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[OrderLineData(line=order_line, quantity=1)],
+ fulfillment_lines=fulfillment_lines_to_process,
+ refund=False,
+ )
+
+ returned_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.RETURNED
+ )
+ returned_fulfillment_lines = returned_fulfillment.lines.all()
+
+ returned_and_refunded_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ returned_and_refunded_lines = returned_and_refunded_fulfillment.lines.all()
+
+ assert returned_fulfillment_lines.count() == 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 returned_and_refunded_lines.count() == 1
+ assert returned_and_refunded_lines[0].order_line_id == order_line.id
+
+ assert not mocked_refund.called
+
+
+@patch("saleor.order.actions.gateway.refund")
+def test_create_return_fulfillment_with_lines_already_refunded(
+ mocked_refund,
+ fulfilled_order,
+ payment_dummy_fully_charged,
+ staff_user,
+ channel_USD,
+ variant,
+ warehouse,
+):
+ fulfilled_order.payments.add(payment_dummy_fully_charged)
+ 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_to_return = fulfillment_lines
+
+ 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
+ )
+ refunded_fulfillment = Fulfillment.objects.create(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED
+ )
+ refunded_fulfillment_line = refunded_fulfillment.lines.create(
+ order_line=order_line, quantity=2
+ )
+
+ fulfillment_lines_to_process = [
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_to_return
+ ]
+ fulfillment_lines_to_process.append(
+ FulfillmentLineData(line=refunded_fulfillment_line, quantity=2)
+ )
+ create_fulfillments_for_returned_products(
+ requester=staff_user,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines=[],
+ fulfillment_lines=fulfillment_lines_to_process,
+ refund=True,
+ )
+
+ returned_and_refunded_fulfillment = Fulfillment.objects.get(
+ order=fulfilled_order, status=FulfillmentStatus.REFUNDED_AND_RETURNED
+ )
+ returned_and_refunded_lines = returned_and_refunded_fulfillment.lines.all()
+
+ assert returned_and_refunded_lines.count() == len(order_line_ids)
+ for fulfillment_line in returned_and_refunded_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
+
+ # the already refunded line is not included in amount
+ amount = sum(
+ [
+ line.order_line.unit_price_gross_amount * 2
+ for line in fulfillment_lines_to_return
+ ]
+ )
+ mocked_refund.assert_called_once_with(payment_dummy_fully_charged, amount)
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
new file mode 100644
index 0000000000..0f535ddb55
--- /dev/null
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -0,0 +1,334 @@
+from decimal import Decimal
+from unittest.mock import patch
+
+from prices import Money, TaxedMoney
+
+from ...payment import ChargeStatus
+from ...warehouse.models import Allocation, Stock
+from .. import FulfillmentLineData, FulfillmentStatus, OrderLineData
+from ..actions import create_refund_fulfillment
+from ..models import Fulfillment, FulfillmentLine
+
+
+@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()
+
+ returned_fulfillemnt = create_refund_fulfillment(
+ requester=None,
+ order=order_with_lines,
+ payment=payment,
+ order_lines_to_refund=[
+ OrderLineData(line=line, quantity=2) for line in order_lines_to_refund
+ ],
+ fulfillment_lines_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)
+ 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=[
+ OrderLineData(line=line, quantity=1) for line in order_lines_to_refund
+ ],
+ fulfillment_lines_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()
+
+ returned_fulfillemnt = create_refund_fulfillment(
+ requester=None,
+ order=order_with_lines,
+ payment=payment,
+ order_lines_to_refund=[
+ OrderLineData(line=line, quantity=2) for line in order_lines_to_refund
+ ],
+ fulfillment_lines_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_to_refund = fulfillment_lines
+
+ returned_fulfillemnt = create_refund_fulfillment(
+ requester=None,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines_to_refund=[],
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_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_to_refund = fulfillment_lines
+
+ for _ in range(2):
+ create_refund_fulfillment(
+ requester=None,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines_to_refund=[],
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=line, quantity=1)
+ for line in fulfillment_lines_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_to_refund = fulfillment_lines
+ amount = Decimal("10.00")
+
+ returned_fulfillemnt = create_refund_fulfillment(
+ requester=None,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines_to_refund=[],
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=line, quantity=2)
+ for line in fulfillment_lines_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_to_refund = fulfillment_lines
+
+ for _ in range(2):
+ create_refund_fulfillment(
+ requester=None,
+ order=fulfilled_order,
+ payment=payment,
+ order_lines_to_refund=[OrderLineData(line=order_line, quantity=1)],
+ fulfillment_lines_to_refund=[
+ FulfillmentLineData(line=line, quantity=1)
+ for line in fulfillment_lines_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
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 3b8835b7c0..d7846c3f33 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -2992,6 +2992,14 @@ def payment_dummy(db, order_with_lines):
)
+def payment_dummy_fully_charged(payment_dummy):
+ payment_dummy.captured_amount = payment_dummy.total
+ payment_dummy.charge_status = ChargeStatus.FULLY_CHARGED
+ payment_dummy.save()
+ return payment_dummy
+
+
@pytest.fixture
def payment_dummy_credit_card(db, order_with_lines):
return Payment.objects.create(