Skip to content

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

Merge branch 'master' of github.com:mirumee/saleor into feature/possibility-to-return-products

Tomasz Szymanskif5b033cc795c
diff --cc saleor/graphql/order/mutations/fulfillments.py
index 935d80c631,f4b085014c..d618b23847
--- a/saleor/graphql/order/mutations/fulfillments.py
+++ b/saleor/graphql/order/mutations/fulfillments.py
@@@ -6,12 -6,8 +6,8 @@@ from django.template.defaultfilters imp
from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
- from ....order import (
- FulfillmentLineData,
- FulfillmentStatus,
- OrderLineData,
- models as order_models,
- )
-from ....order import FulfillmentStatus
++from ....order import FulfillmentLineData, FulfillmentStatus, OrderLineData
+ from ....order import models as order_models
from ....order.actions import (
cancel_fulfillment,
create_fulfillments,
@@@ -442,20 -478,10 +442,24 @@@ class FulfillmentRefundAndReturnProduct
"FulfillmentLine",
line.pk,
"fulfillment_line_id",
- code=OrderErrorCode.CANNOT_REFUND_FULFILLMENT_LINE.value,
+ code=OrderErrorCode.INVALID.value,
+ )
+ 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,)
++ FulfillmentLineData(
++ line=line,
++ quantity=quantity,
++ replace=replace,
+ )
- cleaned_input["fulfillment_lines_quantities_to_refund"] = quantities_to_refund
- cleaned_input["fulfillment_lines_to_refund"] = lines_to_refund
+ )
+ cleaned_input["fulfillment_lines"] = cleaned_fulfillment_lines
@classmethod
def clean_lines(cls, lines_data, cleaned_input):
@@@ -569,150 -533,3 +573,153 @@@ class FulfillmentRefundProducts(Fulfill
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,
++ 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,
++ 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.",
++ 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", []),
+ info.context.plugins,
+ 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 --cc saleor/graphql/order/tests/test_order.py
index ed5aa9ef34,1292c8d928..71fbc0a738
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@@ -1,6 -1,6 +1,7 @@@
import uuid
+from copy import deepcopy
from datetime import date, timedelta
+ from decimal import Decimal
from unittest.mock import ANY, MagicMock, Mock, call, patch
import graphene
@@@ -12,9 -12,9 +13,10 @@@ from prices import Money, TaxedMone
from ....account.models import CustomerEvent
from ....core.taxes import TaxError, zero_taxed_money
- from ....order import OrderStatus, events as order_events
+ from ....order import OrderStatus
+ from ....order import 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
diff --cc saleor/order/actions.py
index eab10e8901,bd797f7a84..cf50054516
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@@ -463,37 -433,14 +468,39 @@@ 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,
++ 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] = []
@@@ -642,363 -639,7 +649,367 @@@ def create_refund_fulfillment
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],
+ manager: "PluginsManager",
+ 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,
+ )
+ order_returned(
+ order,
+ user=requester,
+ returned_lines=list(returned_lines.values()),
+ manager=manager,
+ )
+ 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=order,
++ user=requester,
++ replaced_lines=replaced_lines,
+ )
+ order_replacement_created(
- original_order=order, replace_order=new_order, user=requester,
++ original_order=order,
++ replace_order=new_order,
++ user=requester,
+ )
+
+ 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],
+ plugin_manager: PluginsManager,
+ 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,
+ manager=plugin_manager,
+ )
+
+ 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,
+ manager=plugin_manager,
+ 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,
+ manager: "PluginsManager",
+):
+ 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
diff --cc saleor/order/events.py
index 232154f851,04c2a315a8..8bfe42a08d
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@@ -373,33 -348,6 +383,39 @@@ def fulfillment_fulfilled_items_event
)
+def order_returned_event(
- *, order: Order, user: UserType, returned_lines: List[Tuple[int, OrderLine]],
++ *,
++ 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]],
++ *,
++ 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 --cc saleor/order/migrations/0097_auto_20210107_1148.py
index 003913aca4,0000000000..d6ba254602
mode 100644,000000..100644
--- a/saleor/order/migrations/0097_auto_20210107_1148.py
+++ b/saleor/order/migrations/0097_auto_20210107_1148.py
@@@ -1,89 -1,0 +1,89 @@@
- # Generated by Django 3.1.4 on 2020-12-16 15:05
++# Generated by Django 3.1.4 on 2021-01-07 11:48
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
- ("order", "0093_auto_20201130_1406"),
++ ("order", "0096_order_shipping_tax_rate"),
+ ]
+
+ 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 --cc saleor/order/tests/test_order_actions_refund_products.py
index 63aee29690,0000000000..d5c20b9d6f
mode 100644,000000..100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@@ -1,343 -1,0 +1,346 @@@
+from decimal import Decimal
+from unittest.mock import patch
+
+from prices import Money, TaxedMoney
+
+from ...payment import ChargeStatus
+from ...plugins.manager import get_plugins_manager
+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=[],
+ plugin_manager=get_plugins_manager(),
+ )
+
+ 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=[],
+ plugin_manager=get_plugins_manager(),
+ )
+
+ 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=[],
+ plugin_manager=get_plugins_manager(),
+ 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
+ ],
+ plugin_manager=get_plugins_manager(),
+ )
+ 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
+ ],
+ plugin_manager=get_plugins_manager(),
+ )
+
+ 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
+ ],
+ plugin_manager=get_plugins_manager(),
+ 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
+):
++ import ipdb
++
++ ipdb.set_trace()
+ 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
+ )
+ channel_listing = variant.channel_listings.get()
+ net = variant.get_price(variant.product, [], channel_USD, channel_listing)
+ 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
+ ],
+ plugin_manager=get_plugins_manager(),
+ )
+
+ 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