Skip to content

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

Add refund amount fields to refunded fulfillments (#7364)

Maciej Korycinski7316b93a8db8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5c902c8b10..5eef11a108 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -75,6 +75,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Raise ValidationError when refund cannot be performed - #7260 by @IKarbowiak
- Extend order with origin and original order values - #7326 by @IKarbowiak
- Fix customer addresses missing after customer creation - #7327 by @tomaszszymanski129
+- Extend order webhook payload with fulfillment fields - #7364 by @korycins
- Extend order payload with undiscounted prices and add psp_reference to payment model - #7339 by @IKarbowiak
- order payload extended with the following fields:
- `undiscounted_total_net_amount`
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 462b30f402..e39723a407 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -6,7 +6,7 @@ from ....core.exceptions import InsufficientStock
from ....core.permissions import OrderPermissions
from ....core.taxes import TaxError, zero_taxed_money
from ....core.tracing import traced_atomic_transaction
-from ....order import OrderLineData, OrderStatus, events, models
+from ....order import FulfillmentStatus, OrderLineData, OrderStatus, events, models
from ....order.actions import (
cancel_order,
clean_mark_order_as_paid,
@@ -571,6 +571,9 @@ class OrderRefund(BaseMutation):
amount=amount,
channel_slug=order.channel.slug,
)
+ order.fulfillments.create(
+ status=FulfillmentStatus.REFUNDED, total_refund_amount=amount
+ )
# Confirm that we changed the status to refund. Some payment can receive
# asynchronous webhook with update status
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 8388f4063d..9e5292a27b 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -4028,6 +4028,13 @@ def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_ca
).first()
assert refund_order_event.parameters["amount"] == str(amount)
+ refunded_fulfillment = order.fulfillments.filter(
+ status=FulfillmentStatus.REFUNDED
+ ).first()
+ assert refunded_fulfillment
+ assert refunded_fulfillment.total_refund_amount == payment_txn_captured.total
+ assert refunded_fulfillment.shipping_refund_amount is None
+
@pytest.mark.parametrize(
"requires_amount, mutation_name",
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 134c1f22a0..f12f47f2dd 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -695,6 +695,18 @@ def _move_fulfillment_lines_to_target_fulfillment(
).delete()
+def __get_shipping_refund_amount(
+ refund_shipping_costs: bool,
+ refund_amount: Optional[Decimal],
+ shipping_price: Decimal,
+) -> Optional[Decimal]:
+ # We set shipping refund amount only when refund amount is calculated by Saleor
+ shipping_refund_amount = None
+ if refund_shipping_costs and refund_amount is None:
+ shipping_refund_amount = shipping_price
+ return shipping_refund_amount
+
+
def create_refund_fulfillment(
requester: Optional["User"],
order,
@@ -713,8 +725,12 @@ def create_refund_fulfillment(
unfulfilled lines will be deallocated.
"""
+ shipping_refund_amount = __get_shipping_refund_amount(
+ refund_shipping_costs, amount, order.shipping_price_gross_amount
+ )
+
with transaction_with_commit_on_errors():
- _process_refund(
+ total_refund_amount = _process_refund(
requester=requester,
order=order,
payment=payment,
@@ -726,7 +742,10 @@ def create_refund_fulfillment(
)
refunded_fulfillment = Fulfillment.objects.create(
- status=FulfillmentStatus.REFUNDED, order=order
+ status=FulfillmentStatus.REFUNDED,
+ order=order,
+ total_refund_amount=total_refund_amount,
+ shipping_refund_amount=shipping_refund_amount,
)
created_fulfillment_lines = _move_order_lines_to_target_fulfillment(
order_lines_to_move=order_lines_to_refund,
@@ -739,7 +758,9 @@ def create_refund_fulfillment(
target_fulfillment=refunded_fulfillment,
)
- Fulfillment.objects.filter(order=order, lines=None).delete()
+ Fulfillment.objects.filter(
+ order=order, lines=None, status=FulfillmentStatus.FULFILLED
+ ).delete()
transaction.on_commit(lambda: manager.order_updated(order))
return refunded_fulfillment
@@ -841,9 +862,14 @@ def _move_lines_to_return_fulfillment(
fulfillment_lines: List[FulfillmentLineData],
fulfillment_status: str,
order: "Order",
+ total_refund_amount: Optional[Decimal],
+ shipping_refund_amount: Optional[Decimal],
) -> Fulfillment:
target_fulfillment = Fulfillment.objects.create(
- status=fulfillment_status, order=order
+ status=fulfillment_status,
+ order=order,
+ total_refund_amount=total_refund_amount,
+ shipping_refund_amount=shipping_refund_amount,
)
lines_in_target_fulfillment = _move_order_lines_to_target_fulfillment(
order_lines_to_move=order_lines,
@@ -914,10 +940,11 @@ def create_return_fulfillment(
order: "Order",
order_lines: List[OrderLineData],
fulfillment_lines: List[FulfillmentLineData],
- refund: bool = False,
+ total_refund_amount: Optional[Decimal],
+ shipping_refund_amount: Optional[Decimal],
) -> Fulfillment:
status = FulfillmentStatus.RETURNED
- if refund:
+ if total_refund_amount is not None:
status = FulfillmentStatus.REFUNDED_AND_RETURNED
with traced_atomic_transaction():
return_fulfillment = _move_lines_to_return_fulfillment(
@@ -925,6 +952,8 @@ def create_return_fulfillment(
fulfillment_lines=fulfillment_lines,
fulfillment_status=status,
order=order,
+ total_refund_amount=total_refund_amount,
+ shipping_refund_amount=shipping_refund_amount,
)
returned_lines: Dict[OrderLineIDType, Tuple[QuantityType, OrderLine]] = dict()
order_lines_with_fulfillment = OrderLine.objects.in_bulk(
@@ -1030,9 +1059,13 @@ def create_fulfillments_for_returned_products(
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]
+ shipping_refund_amount = __get_shipping_refund_amount(
+ refund_shipping_costs, amount, order.shipping_price_gross_amount
+ )
+ total_refund_amount = None
with traced_atomic_transaction():
if refund and payment:
- _process_refund(
+ total_refund_amount = _process_refund(
requester=requester,
order=order,
payment=payment,
@@ -1059,9 +1092,12 @@ def create_fulfillments_for_returned_products(
order=order,
order_lines=return_order_lines,
fulfillment_lines=return_fulfillment_lines,
- refund=refund,
+ total_refund_amount=total_refund_amount,
+ shipping_refund_amount=shipping_refund_amount,
)
- Fulfillment.objects.filter(order=order, lines=None).delete()
+ Fulfillment.objects.filter(
+ order=order, lines=None, status=FulfillmentStatus.FULFILLED
+ ).delete()
transaction.on_commit(lambda: manager.order_updated(order))
return return_fulfillment, replace_fulfillment, new_order
@@ -1155,3 +1191,4 @@ def _process_refund(
shipping_costs_included=refund_shipping_costs,
)
)
+ return amount
diff --git a/saleor/order/migrations/0110_auto_20210518_0918.py b/saleor/order/migrations/0110_auto_20210518_0918.py
new file mode 100644
index 0000000000..9dc10819dd
--- /dev/null
+++ b/saleor/order/migrations/0110_auto_20210518_0918.py
@@ -0,0 +1,27 @@
+# Generated by Django 3.2.2 on 2021-05-18 09:18
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0109_undiscounted_prices"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="fulfillment",
+ name="shipping_refund_amount",
+ field=models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ migrations.AddField(
+ model_name="fulfillment",
+ name="total_refund_amount",
+ field=models.DecimalField(
+ blank=True, decimal_places=3, max_digits=12, null=True
+ ),
+ ),
+ ]
diff --git a/saleor/order/migrations/0111_auto_20210518_1357.py b/saleor/order/migrations/0111_auto_20210518_1357.py
new file mode 100644
index 0000000000..46b5fc5ba5
--- /dev/null
+++ b/saleor/order/migrations/0111_auto_20210518_1357.py
@@ -0,0 +1,100 @@
+# Generated by Django 3.2.2 on 2021-05-18 13:57
+from decimal import Decimal
+
+from django.db import migrations
+
+
+def populate_refund_amounts_in_fulfillments(apps, schema_editor):
+ Order = apps.get_model("order", "Order")
+
+ orders = Order.objects.filter(events__type="fulfillment_refunded")
+ for order in orders.iterator():
+ fulfillments = order.fulfillments.filter(
+ status__in=["refunded", "refunded_and_returned"]
+ )
+ refunded_fulfillments = order.fulfillments.filter(status="refunded")
+ refunded_and_replaced_fulfillments = order.fulfillments.filter(
+ status="refunded_and_returned"
+ )
+ refunded_events = order.events.filter(type="fulfillment_refunded")
+ refunded_events = [
+ event for event in refunded_events if "lines" in event.parameters
+ ]
+ total_amount = sum(
+ [Decimal(event.parameters.get("amount", 0)) for event in refunded_events]
+ )
+ included_shipping_costs = any(
+ [
+ event.parameters.get("shipping_costs_included", False)
+ for event in refunded_events
+ ]
+ )
+
+ fulfillment_count = fulfillments.count()
+ refunded_events_count = len(refunded_events)
+ if fulfillment_count == refunded_events_count:
+ for fulfillment, event in zip(fulfillments, refunded_events):
+ amount = event.parameters.get("amount") or 0
+ included_shipping_costs = event.parameters.get(
+ "shipping_costs_included", False
+ )
+ fulfillment.total_refund_amount = amount
+ if included_shipping_costs:
+ fulfillment.shipping_refund_amount = (
+ order.shipping_price_gross_amount
+ )
+ fulfillment.save(
+ update_fields=["total_refund_amount", "shipping_refund_amount"]
+ )
+ elif (
+ refunded_fulfillments.count() == 1
+ and not refunded_and_replaced_fulfillments
+ ):
+ refunded_fulfillment = refunded_fulfillments.first()
+ if included_shipping_costs:
+ refunded_fulfillment.shipping_refund_amount = (
+ order.shipping_price_gross_amount
+ )
+ refunded_fulfillment.total_refund_amount = total_amount
+ refunded_fulfillment.save(
+ update_fields=["total_refund_amount", "shipping_refund_amount"]
+ )
+ elif (
+ not refunded_fulfillments
+ and refunded_and_replaced_fulfillments.count() == 1
+ ):
+ refunded_and_replaced_fulfillment = (
+ refunded_and_replaced_fulfillments.first()
+ )
+ if included_shipping_costs:
+ refunded_and_replaced_fulfillment.shipping_refund_amount = (
+ order.shipping_price_gross_amount
+ )
+ refunded_and_replaced_fulfillment.total_refund_amount = total_amount
+ refunded_and_replaced_fulfillment.save(
+ update_fields=["total_refund_amount", "shipping_refund_amount"]
+ )
+ else:
+ fulfillment = fulfillments.first()
+ if fulfillment:
+ fulfillment.total_refund_amount = total_amount
+ if included_shipping_costs:
+ fulfillment.shipping_refund_amount = (
+ order.shipping_price_gross_amount
+ )
+ fulfillment.save(
+ update_fields=["total_refund_amount", "shipping_refund_amount"]
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0110_auto_20210518_0918"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ populate_refund_amounts_in_fulfillments, migrations.RunPython.noop
+ )
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index a29b73f7bf..3f92b188c1 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -551,6 +551,19 @@ class Fulfillment(ModelWithMetadata):
tracking_number = models.CharField(max_length=255, default="", blank=True)
created = models.DateTimeField(auto_now_add=True)
+ shipping_refund_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ null=True,
+ blank=True,
+ )
+ total_refund_amount = models.DecimalField(
+ max_digits=settings.DEFAULT_MAX_DIGITS,
+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,
+ null=True,
+ blank=True,
+ )
+
class Meta(ModelWithMetadata.Meta):
ordering = ("pk",)
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
index 3c1b74862e..489bf9f235 100644
--- 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
@@ -155,6 +155,9 @@ def test_create_return_fulfillment_only_order_lines_with_refund(
)
assert not replace_order
+ assert returned_fulfillment.total_refund_amount == amount
+ assert returned_fulfillment.shipping_refund_amount is None
+
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -225,6 +228,12 @@ def test_create_return_fulfillment_only_order_lines_included_shipping_costs(
)
assert not replace_order
+ assert returned_fulfillment.total_refund_amount == amount
+ assert (
+ returned_fulfillment.shipping_refund_amount
+ == order_with_lines.shipping_price_gross_amount
+ )
+
mocked_order_updated.assert_called_once_with(order_with_lines)
@@ -604,4 +613,7 @@ def test_create_return_fulfillment_with_lines_already_refunded(
channel_slug=fulfilled_order.channel.slug,
)
+ assert returned_and_refunded_fulfillment.total_refund_amount == amount
+ assert returned_and_refunded_fulfillment.shipping_refund_amount is None
+
mocked_order_updated.assert_called_once_with(fulfilled_order)
diff --git a/saleor/order/tests/test_order_actions_refund_products.py b/saleor/order/tests/test_order_actions_refund_products.py
index cf1cf1bd03..875b227d3d 100644
--- a/saleor/order/tests/test_order_actions_refund_products.py
+++ b/saleor/order/tests/test_order_actions_refund_products.py
@@ -62,6 +62,10 @@ def test_create_refund_fulfillment_only_order_lines(
== current_allocation.quantity_allocated
)
amount = sum([line.unit_price_gross_amount * 2 for line in order_lines_to_refund])
+
+ assert returned_fulfillemnt.total_refund_amount == amount
+ assert returned_fulfillemnt.shipping_refund_amount is None
+
mocked_refund.assert_called_once_with(
payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
)
@@ -108,6 +112,13 @@ def test_create_refund_fulfillment_included_shipping_costs(
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
+
+ assert returned_fulfillemnt.total_refund_amount == amount
+ assert (
+ returned_fulfillemnt.shipping_refund_amount
+ == order_with_lines.shipping_price_gross_amount
+ )
+
mocked_refund.assert_called_once_with(
payment_dummy, ANY, amount=amount, channel_slug=order_with_lines.channel.slug
)
@@ -159,6 +170,9 @@ def test_create_refund_fulfillment_only_fulfillment_lines(
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
+ assert returned_fulfillemnt.total_refund_amount == amount
+ assert returned_fulfillemnt.shipping_refund_amount is None
+
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.order.actions.gateway.refund")
@@ -203,3 +217,6 @@ def test_create_refund_fulfillment_custom_amount(
payment_dummy, ANY, amount=amount, channel_slug=fulfilled_order.channel.slug
)
mocked_order_updated.assert_called_once_with(fulfilled_order)
+
+ assert returned_fulfillemnt.total_refund_amount == amount
+ assert returned_fulfillemnt.shipping_refund_amount is None
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index f1ee566551..f7bc5381ec 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -119,7 +119,13 @@ def generate_order_lines_payload(lines: Iterable[OrderLine]):
def generate_order_payload(order: "Order"):
serializer = PayloadSerializer()
- fulfillment_fields = ("status", "tracking_number", "created")
+ fulfillment_fields = (
+ "status",
+ "tracking_number",
+ "created",
+ "shipping_refund_amount",
+ "total_refund_amount",
+ )
payment_fields = (
"gateway",
"payment_method_type",
@@ -401,13 +407,16 @@ def generate_product_variant_payload(product_variants: Iterable["ProductVariant"
def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
serializer = PayloadSerializer()
lines = FulfillmentLine.objects.prefetch_related(
- "order_line__variant__product__product_type"
+ "order_line__variant__product__product_type", "stock"
).filter(fulfillment=fulfillment)
line_fields = ("quantity",)
return serializer.serialize(
lines,
fields=line_fields,
extra_dict_data={
+ "product_name": lambda fl: fl.order_line.product_name,
+ "variant_name": lambda fl: fl.order_line.variant_name,
+ "product_sku": lambda fl: fl.order_line.product_sku,
"weight": (lambda fl: fl.order_line.variant.get_weight().g),
"weight_unit": "gram",
"product_type": (
@@ -421,11 +430,20 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
"undiscounted_unit_price_gross": (
lambda fl: fl.order_line.undiscounted_unit_price.gross.amount
),
- "total_price_net_amount": lambda fl: fl.order_line.total_price_net_amount,
+ "total_price_net_amount": (
+ lambda fl: fl.order_line.undiscounted_unit_price.net.amount
+ * fl.quantity
+ ),
"total_price_gross_amount": (
- lambda fl: fl.order_line.total_price_gross_amount
+ lambda fl: fl.order_line.undiscounted_unit_price.gross.amount
+ * fl.quantity
),
"currency": lambda fl: fl.order_line.currency,
+ "warehouse_id": lambda fl: graphene.Node.to_global_id(
+ "Warehouse", fl.stock.warehouse_id
+ )
+ if fl.stock
+ else None,
},
)
@@ -434,7 +452,13 @@ def generate_fulfillment_payload(fulfillment: Fulfillment):
serializer = PayloadSerializer()
# fulfillment fields to serialize
- fulfillment_fields = ("status", "tracking_code", "order__user_email")
+ fulfillment_fields = (
+ "status",
+ "tracking_code",
+ "order__user_email",
+ "shipping_refund_amount",
+ "total_refund_amount",
+ )
order = fulfillment.order
order_country = get_order_country(order)
fulfillment_line = fulfillment.lines.first()
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index 5d6a4fab83..2b5593bae4 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -118,13 +118,21 @@ def test_generate_fulfillment_lines_payload(order_with_lines):
]
)
payload = json.loads(generate_fulfillment_lines_payload(fulfillment))[0]
+
assert payload == {
"currency": "USD",
+ "product_name": line.product_name,
+ "variant_name": line.variant_name,
+ "product_sku": line.product_sku,
"id": graphene.Node.to_global_id("FulfillmentLine", fulfillment_line.id),
"product_type": "Default Type",
"quantity": fulfillment_line.quantity,
- "total_price_gross_amount": str(line.total_price.gross.amount),
- "total_price_net_amount": str(line.total_price.net.amount),
+ "total_price_gross_amount": str(
+ line.unit_price.gross.amount * fulfillment_line.quantity
+ ),
+ "total_price_net_amount": str(
+ line.unit_price.net.amount * fulfillment_line.quantity
+ ),
"type": "FulfillmentLine",
"undiscounted_unit_price_gross": str(line.undiscounted_unit_price.gross.amount),
"undiscounted_unit_price_net": str(line.undiscounted_unit_price.net.amount),
@@ -132,6 +140,9 @@ def test_generate_fulfillment_lines_payload(order_with_lines):
"unit_price_net": str(line.unit_price.net.amount),
"weight": 0.0,
"weight_unit": "gram",
+ "warehouse_id": graphene.Node.to_global_id(
+ "Warehouse", fulfillment_line.stock.warehouse_id
+ ),
}