Skip to content

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

Add ORDER_REFUNDED, ORDER_FULLY_REFUNDED, ORDER_PAID webhooks (#12533)

Maciej Korycinski302237048beb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 196f788525..dd41f3c95a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,6 +28,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Remove default `EMAIL_URL` value pointing to console output; from now on EMAIL_URL has to be set explicitly - #12580 by @maarcingebala
- Fix sending `product_created` event in `ProductBulkCreate` mutation - #12605 by @SzymJ
+- Add `ORDER_REFUNDED`, `ORDER_FULLY_REFUNDED`, `ORDER_PAID` webhooks - #12533 by @korycins
# 3.13.0
diff --git a/saleor/core/utils/events.py b/saleor/core/utils/events.py
index 045c95f1e7..c992a4548f 100644
--- a/saleor/core/utils/events.py
+++ b/saleor/core/utils/events.py
@@ -1,13 +1,13 @@
from django.db import transaction
-def call_event(func_obj, *func_args):
+def call_event(func_obj, *func_args, **func_kwargs):
"""Call webhook event with given args.
Ensures that in atomic transaction event is called on_commit.
"""
connection = transaction.get_connection()
if connection.in_atomic_block:
- transaction.on_commit(lambda: func_obj(*func_args))
+ transaction.on_commit(lambda: func_obj(*func_args, **func_kwargs))
else:
- func_obj(*func_args)
+ func_obj(*func_args, **func_kwargs)
diff --git a/saleor/graphql/order/mutations/order_refund.py b/saleor/graphql/order/mutations/order_refund.py
index 6e260f6127..bdfcc49082 100644
--- a/saleor/graphql/order/mutations/order_refund.py
+++ b/saleor/graphql/order/mutations/order_refund.py
@@ -101,6 +101,7 @@ class OrderRefund(BaseMutation):
# Confirm that we changed the status to refund. Some payment can receive
# asynchronous webhook with update status
if transaction.kind == TransactionKind.REFUND:
+ payment.refresh_from_db()
order_refunded(
order,
info.context.user,
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
index 3d89aafed3..3cfd0c866e 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_refund_products.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
+import mock
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
@@ -11,6 +12,7 @@ from .....order.fetch import OrderLineInfo
from .....order.models import FulfillmentLine, FulfillmentStatus
from .....payment import ChargeStatus, PaymentError
from .....payment.interface import RefundData
+from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Allocation, Stock
from ....tests.utils import get_graphql_content
@@ -900,3 +902,86 @@ def test_fulfillment_refund_products_fulfillment_lines_and_order_lines(
],
),
)
+
+
+@patch("saleor.order.actions.order_refunded")
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_refund_products_calls_order_refunded(
+ mocked_refund,
+ mocked_order_refunded,
+ 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
+ )
+ 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)
+ variant.track_inventory = False
+ variant.save()
+ unit_price = TaxedMoney(net=net, gross=gross)
+ quantity = 5
+ order_line = fulfilled_order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=quantity,
+ quantity_fulfilled=2,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * quantity,
+ tax_rate=Decimal("0.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_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)
+
+ # when
+ staff_api_client.post_graphql(ORDER_FULFILL_REFUND_MUTATION, variables)
+
+ # then
+ flush_post_commit_hooks()
+ amount = fulfillment_line_to_refund.order_line.unit_price_gross_amount * 2
+ amount += order_line.unit_price_gross_amount * 2
+ amount = amount.quantize(Decimal("0.001"))
+
+ mocked_order_refunded.assert_called_once_with(
+ order=fulfilled_order,
+ user=staff_api_client.user,
+ app=None,
+ amount=amount,
+ payment=payment_dummy,
+ manager=mock.ANY,
+ trigger_order_updated=False,
+ )
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
index d7aa6f14ed..f5f77e0929 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_return_products.py
@@ -2,6 +2,7 @@ from decimal import Decimal
from unittest.mock import ANY, patch
import graphene
+import mock
from prices import Money, TaxedMoney
from .....core.prices import quantize_price
@@ -11,6 +12,7 @@ from .....order.fetch import OrderLineInfo
from .....order.models import FulfillmentStatus, Order
from .....payment import ChargeStatus, PaymentError
from .....payment.interface import RefundData
+from .....tests.utils import flush_post_commit_hooks
from .....warehouse.models import Stock
from ....tests.utils import get_graphql_content
@@ -969,3 +971,91 @@ def test_fulfillment_return_products_fulfillment_lines_and_order_lines(
],
),
)
+
+
+@patch("saleor.order.actions.order_refunded")
+@patch("saleor.order.actions.gateway.refund")
+def test_fulfillment_return_products_calls_order_refunded(
+ mocked_refund,
+ mocked_order_refunded,
+ warehouse,
+ variant,
+ channel_USD,
+ staff_api_client,
+ permission_manage_orders,
+ fulfilled_order,
+ payment_dummy,
+):
+ # given
+ 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
+ )
+ 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)
+ variant.track_inventory = False
+ variant.save()
+ unit_price = TaxedMoney(net=net, gross=gross)
+ quantity = 5
+ order_line = fulfilled_order.lines.create(
+ product_name=str(variant.product),
+ variant_name=str(variant),
+ product_sku=variant.sku,
+ product_variant_id=variant.get_global_id(),
+ is_shipping_required=variant.is_shipping_required(),
+ is_gift_card=variant.is_gift_card(),
+ quantity=quantity,
+ quantity_fulfilled=2,
+ variant=variant,
+ unit_price=unit_price,
+ total_price=unit_price * quantity,
+ tax_rate=Decimal("0.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)
+
+ # when
+ staff_api_client.post_graphql(ORDER_FULFILL_RETURN_MUTATION, variables)
+
+ # then
+ flush_post_commit_hooks()
+ amount = order_line.unit_price_gross_amount * 2
+ amount = amount.quantize(Decimal("0.001"))
+
+ mocked_order_refunded.assert_called_once_with(
+ order=fulfilled_order,
+ user=staff_api_client.user,
+ app=None,
+ amount=amount,
+ payment=payment_dummy,
+ manager=mock.ANY,
+ trigger_order_updated=False,
+ )
diff --git a/saleor/graphql/order/tests/mutations/test_order_refund.py b/saleor/graphql/order/tests/mutations/test_order_refund.py
index d214717651..5c47c6593f 100644
--- a/saleor/graphql/order/tests/mutations/test_order_refund.py
+++ b/saleor/graphql/order/tests/mutations/test_order_refund.py
@@ -1,9 +1,13 @@
+from decimal import Decimal
+
import graphene
+from mock import patch
from .....order import FulfillmentStatus
from .....order import events as order_events
from .....order.error_codes import OrderErrorCode
from .....payment import ChargeStatus
+from .....tests.utils import flush_post_commit_hooks
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import get_graphql_content
@@ -25,15 +29,88 @@ ORDER_REFUND_MUTATION = """
"""
-def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_captured):
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_refund(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+):
+ # given
order = payment_txn_captured.order
+ query = ORDER_REFUND_MUTATION
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ amount = Decimal(10)
+ variables = {"id": order_id, "amount": amount}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["orderRefund"]["order"]
+ order.refresh_from_db()
+ assert data["status"] == order.status.upper()
+ assert data["paymentStatus"] == PaymentChargeStatusEnum.PARTIALLY_REFUNDED.name
+ payment_status_display = dict(ChargeStatus.CHOICES).get(
+ ChargeStatus.PARTIALLY_REFUNDED
+ )
+ assert data["paymentStatusDisplay"] == payment_status_display
+ assert data["isPaid"] is False
+
+ refund_order_event = order.events.filter(
+ type=order_events.OrderEvents.PAYMENT_REFUNDED
+ ).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 == amount
+ assert refunded_fulfillment.shipping_refund_amount is None
+
+ flush_post_commit_hooks()
+ mock_order_updated.assert_called_once_with(order)
+ mock_order_refunded.assert_called_once_with(order)
+ assert amount < order.total.gross.amount
+ assert not mock_order_fully_refunded.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_fully_refunded(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+):
+ # given
+ order = payment_txn_captured.order
+ payment_txn_captured.total = order.total.gross.amount
+ payment_txn_captured.captured_amount = payment_txn_captured.total
+ payment_txn_captured.save()
+
query = ORDER_REFUND_MUTATION
order_id = graphene.Node.to_global_id("Order", order.id)
amount = float(payment_txn_captured.total)
variables = {"id": order_id, "amount": amount}
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["orderRefund"]["order"]
order.refresh_from_db()
@@ -55,6 +132,11 @@ def test_order_refund(staff_api_client, permission_manage_orders, payment_txn_ca
assert refunded_fulfillment.total_refund_amount == payment_txn_captured.total
assert refunded_fulfillment.shipping_refund_amount is None
+ flush_post_commit_hooks()
+ mock_order_updated.assert_called_once_with(order)
+ mock_order_refunded.assert_called_once_with(order)
+ mock_order_fully_refunded.assert_called_once_with(order)
+
def test_order_refund_with_gift_card_lines(
staff_api_client, permission_manage_orders, gift_card_shippable_order_line
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 6fd926dad1..c7705eb239 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1940,7 +1940,10 @@ class Order(ModelObjectType[models.Order]):
# over payment's transactions
total_refund_amount = Decimal(0)
for transaction in transactions:
- if transaction.kind == TransactionKind.REFUND:
+ if (
+ transaction.kind == TransactionKind.REFUND
+ and transaction.is_success
+ ):
total_refund_amount += transaction.amount
return prices.Money(total_refund_amount, root.currency)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 06fde7cc07..c2b2f27ffa 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -29,7 +29,7 @@ from ...core.utils import get_client_ip
from ...core.utils.url import validate_storefront_url
from ...order import OrderStatus
from ...order import models as order_models
-from ...order.actions import order_transaction_updated
+from ...order.actions import order_refunded, order_transaction_updated
from ...order.events import transaction_event as order_transaction_event
from ...order.fetch import fetch_order_info
from ...order.models import Order
@@ -40,6 +40,7 @@ from ...payment import (
StorePaymentMethod,
TransactionAction,
TransactionEventType,
+ TransactionKind,
gateway,
)
from ...payment import models as payment_models
@@ -458,6 +459,10 @@ class PaymentRefund(PaymentCapture):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, amount=None, payment_id
):
+ app = get_app_promise(info.context).get()
+ user = info.context.user
+ manager = get_plugin_manager_promise(info.context).get()
+
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
@@ -467,8 +472,9 @@ class PaymentRefund(PaymentCapture):
else payment.checkout.channel.slug
)
manager = get_plugin_manager_promise(info.context).get()
+ payment_transaction = None
try:
- gateway.refund(
+ payment_transaction = gateway.refund(
payment,
manager,
amount=amount,
@@ -477,6 +483,20 @@ class PaymentRefund(PaymentCapture):
payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR.value)
+ if (
+ payment.order_id
+ and payment_transaction
+ and payment_transaction.kind == TransactionKind.REFUND
+ ):
+ order = cast(order_models.Order, payment.order)
+ order_refunded(
+ order=order,
+ user=user,
+ app=app,
+ amount=amount,
+ payment=payment,
+ manager=manager,
+ )
return PaymentRefund(payment=payment)
@@ -1088,6 +1108,7 @@ class TransactionCreate(BaseMutation):
app=app,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
if transaction_data.get("checkout_id") and money_data:
discounts = load_discounts(info.context)
@@ -1261,6 +1282,7 @@ class TransactionUpdate(TransactionCreate):
previous_transaction_psp_reference = instance.psp_reference
previous_authorized_value = instance.authorized_value
previous_charged_value = instance.charged_value
+ previous_refunded_value = instance.refunded_value
if transaction:
cls.validate_transaction_input(instance, transaction)
@@ -1300,6 +1322,7 @@ class TransactionUpdate(TransactionCreate):
app=app,
previous_authorized_value=previous_authorized_value,
previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
)
if instance.checkout_id and money_data:
discounts = load_discounts(info.context)
@@ -1604,6 +1627,7 @@ class TransactionEventReport(ModelMutation):
if not already_processed:
previous_authorized_value = transaction.authorized_value
previous_charged_value = transaction.charged_value
+ previous_refunded_value = transaction.refunded_value
if available_actions is not None:
transaction.available_actions = available_actions
transaction.save(update_fields=["available_actions"])
@@ -1631,6 +1655,7 @@ class TransactionEventReport(ModelMutation):
app=app,
previous_authorized_value=previous_authorized_value,
previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
)
if transaction.checkout_id:
discounts = load_discounts(info.context)
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_refund.py b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
index 80f72cee62..584efde448 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_refund.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_refund.py
@@ -1,7 +1,9 @@
import graphene
+from mock import patch
from .....payment import TransactionKind
from .....payment.models import ChargeStatus
+from .....tests.utils import flush_post_commit_hooks
from ....core.enums import PaymentErrorCode
from ....tests.utils import get_graphql_content
@@ -22,19 +24,34 @@ REFUND_QUERY = """
"""
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
def test_payment_refund_success(
- staff_api_client, permission_manage_orders, payment_txn_captured
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+ order_with_lines,
):
+ # given
payment = payment_txn_captured
+ payment.total = order_with_lines.total.gross.amount
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = payment.total
payment.save()
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": str(payment.total)}
+
+ # when
response = staff_api_client.post_graphql(
REFUND_QUERY, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["paymentRefund"]
assert not data["errors"]
@@ -44,10 +61,24 @@ def test_payment_refund_success(
txn = payment.transactions.last()
assert txn.kind == TransactionKind.REFUND
+ flush_post_commit_hooks()
+ mock_order_updated.assert_called_once_with(payment.order)
+ mock_order_refunded.assert_called_once_with(payment.order)
+ mock_order_fully_refunded.assert_called_once_with(payment.order)
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
def test_payment_refund_with_invalid_argument(
- staff_api_client, permission_manage_orders, payment_txn_captured
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
):
+ # given
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = payment.total
@@ -55,18 +86,36 @@ def test_payment_refund_with_invalid_argument(
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": 0}
+
+ # when
response = staff_api_client.post_graphql(
REFUND_QUERY, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["paymentRefund"]
assert len(data["errors"]) == 1
assert data["errors"][0]["message"] == "Amount should be a positive number."
+ assert not mock_order_fully_refunded.called
+ assert not mock_order_refunded.called
+ assert not mock_order_updated.called
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
def test_payment_refund_error(
- staff_api_client, permission_manage_orders, payment_txn_captured, monkeypatch
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ staff_api_client,
+ permission_manage_orders,
+ payment_txn_captured,
+ monkeypatch,
):
+ # given
payment = payment_txn_captured
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = payment.total
@@ -74,9 +123,13 @@ def test_payment_refund_error(
payment_id = graphene.Node.to_global_id("Payment", payment.pk)
variables = {"paymentId": payment_id, "amount": str(payment.total)}
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
+
+ # when
response = staff_api_client.post_graphql(
REFUND_QUERY, variables, permissions=[permission_manage_orders]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["paymentRefund"]
@@ -93,3 +146,7 @@ def test_payment_refund_error(
txn = payment.transactions.last()
assert txn.kind == TransactionKind.REFUND
assert not txn.is_success
+
+ assert not mock_order_fully_refunded.called
+ assert not mock_order_refunded.called
+ assert not mock_order_updated.called
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 48b3e9c1db..7fafbaf296 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -1769,11 +1769,13 @@ def test_transaction_create_creates_calculation_events(
assert cancel_event.amount.amount == canceled_value
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
def test_transaction_create_for_order_triggers_webhooks_when_fully_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
order_with_lines,
permission_manage_payments,
staff_api_client,
@@ -1807,13 +1809,16 @@ def test_transaction_create_for_order_triggers_webhooks_when_fully_paid(
assert order_with_lines.charge_status == OrderChargeStatus.FULL
mock_order_fully_paid.assert_called_once_with(order_with_lines)
mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_paid.assert_called_once_with(order_with_lines)
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
def test_transaction_create_for_order_triggers_webhook_when_partially_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
order_with_lines,
permission_manage_payments,
staff_api_client,
@@ -1847,6 +1852,7 @@ def test_transaction_create_for_order_triggers_webhook_when_partially_paid(
assert order_with_lines.charge_status == OrderChargeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_paid.assert_called_once_with(order_with_lines)
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -1887,3 +1893,87 @@ def test_transaction_create_for_order_triggers_webhook_when_authorized(
assert order_with_lines.authorize_status == OrderAuthorizeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_create_for_order_triggers_webhooks_when_fully_refunded(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ refunded_value = order_with_lines.total.gross.amount
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": "Charged 10$",
+ "type": "Credit Card",
+ "pspReference": "PSP reference - 123",
+ "availableActions": [],
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ get_graphql_content(response)
+
+ mock_order_fully_refunded.assert_called_once_with(order_with_lines)
+ mock_order_refunded.assert_called_once_with(order_with_lines)
+ mock_order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_create_for_order_triggers_webhook_when_partially_refunded(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ refunded_value = Decimal("10")
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "status": "Charged 10$",
+ "type": "Credit Card",
+ "pspReference": "PSP reference - 123",
+ "availableActions": [],
+ "amountRefunded": {
+ "amount": refunded_value,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ get_graphql_content(response)
+
+ assert not mock_order_fully_refunded.called
+ mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_refunded.assert_called_once_with(order_with_lines)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
index c60758c296..e67a3a5d04 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1232,11 +1232,13 @@ def test_transaction_event_report_doesnt_accept_old_id_for_new_transaction(
assert error["field"] == "id"
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
def test_transaction_event_report_for_order_triggers_webhooks_when_fully_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
transaction_item_generator,
app_api_client,
permission_manage_payments,
@@ -1285,6 +1287,7 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_paid(
assert order.charge_status == OrderChargeStatusEnum.FULL.value
mock_order_fully_paid.assert_called_once_with(order)
mock_order_updated.assert_called_once_with(order)
+ mock_order_paid.assert_called_once_with(order)
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -1450,3 +1453,117 @@ def test_transaction_event_report_for_order_triggers_webhooks_when_fully_authori
assert order.authorize_status == OrderAuthorizeStatusEnum.FULL.value
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_event_report_for_order_triggers_webhooks_when_fully_refunded(
+ mock_order_fully_refunded,
+ mock_order_updated,
+ mock_order_refunded,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(app=app_api_client.app, order_id=order.pk)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.REFUND_SUCCESS.name,
+ "amount": order.total.gross.amount,
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ mock_order_fully_refunded.assert_called_once_with(order)
+ mock_order_updated.assert_called_once_with(order)
+ mock_order_refunded.assert_called_once_with(order)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_event_report_for_order_triggers_webhooks_when_partially_refunded(
+ mock_order_fully_refunded,
+ mock_order_updated,
+ mock_order_refunded,
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ psp_reference = "111-abc"
+ transaction = transaction_item_generator(app=app_api_client.app, order_id=order.pk)
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.REFUND_SUCCESS.name,
+ "amount": Decimal(10),
+ "pspReference": psp_reference,
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID!
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert not mock_order_fully_refunded.called
+ mock_order_refunded.assert_called_once_with(order)
+ mock_order_updated.assert_called_once_with(order)
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 1b2d48d447..2e66630ed8 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -2633,11 +2633,13 @@ def test_transaction_update_doesnt_accept_old_id_for_new_transactions(
assert error["field"] == "id"
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
def test_transaction_update_for_order_triggers_webhooks_when_fully_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
order_with_lines,
permission_manage_payments,
app_api_client,
@@ -2677,13 +2679,16 @@ def test_transaction_update_for_order_triggers_webhooks_when_fully_paid(
assert order_with_lines.charge_status == OrderChargeStatus.FULL
mock_order_fully_paid.assert_called_once_with(order_with_lines)
mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_paid.assert_called_once_with(order_with_lines)
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
def test_transaction_update_for_order_triggers_webhook_when_partially_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
order_with_lines,
permission_manage_payments,
app_api_client,
@@ -2723,6 +2728,7 @@ def test_transaction_update_for_order_triggers_webhook_when_partially_paid(
assert order_with_lines.charge_status == OrderChargeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_paid.assert_called_once_with(order_with_lines)
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@@ -2769,3 +2775,95 @@ def test_transaction_update_for_order_triggers_webhook_when_authorized(
assert order_with_lines.authorize_status == OrderAuthorizeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_update_for_order_triggers_webhooks_when_fully_refunded(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+ transaction_item_generator,
+):
+ # given
+ current_refunded_value = Decimal("2")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ refunded_value=current_refunded_value,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountRefunded": {
+ "amount": order_with_lines.total.gross.amount,
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+
+ get_graphql_content(response)
+
+ mock_order_refunded.assert_called_once_with(order_with_lines)
+ mock_order_fully_refunded.assert_called_once_with(order_with_lines)
+ mock_order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_transaction_update_for_order_triggers_webhook_when_partially_refunded(
+ mock_order_fully_refunded,
+ mock_order_refunded,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+ transaction_item_generator,
+):
+ # given
+ current_refunded_value = Decimal("2")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ refunded_value=current_refunded_value,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountRefunded": {
+ "amount": Decimal("10"),
+ "currency": "USD",
+ },
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+
+ get_graphql_content(response)
+
+ assert not mock_order_fully_refunded.called
+ mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_refunded.assert_called_once_with(order_with_lines)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index f64094af16..97eb560ffd 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -1759,9 +1759,36 @@ enum WebhookEventTypeEnum @doc(category: "Webhooks") {
"""
ORDER_CONFIRMED
+ """
+ Payment has been made. The order may be partially or fully paid.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_PAID
+
"""Payment is made and an order is fully paid."""
ORDER_FULLY_PAID
+ """
+ The order received a refund. The order may be partially or fully refunded.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_REFUNDED
+
+ """
+ The order is fully refunded.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_FULLY_REFUNDED
+
"""
An order is updated; triggered for all changes related to an order; covers all other order webhooks, except for ORDER_CREATED.
"""
@@ -2354,9 +2381,36 @@ enum WebhookEventTypeAsyncEnum @doc(category: "Webhooks") {
"""
ORDER_CONFIRMED
+ """
+ Payment has been made. The order may be partially or fully paid.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_PAID
+
"""Payment is made and an order is fully paid."""
ORDER_FULLY_PAID
+ """
+ The order received a refund. The order may be partially or fully refunded.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_REFUNDED
+
+ """
+ The order is fully refunded.
+
+ Added in Saleor 3.14.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ ORDER_FULLY_REFUNDED
+
"""
An order is updated; triggered for all changes related to an order; covers all other order webhooks, except for ORDER_CREATED.
"""
@@ -3165,7 +3219,10 @@ enum WebhookSampleEventTypeEnum @doc(category: "Webhooks") {
MENU_ITEM_DELETED
ORDER_CREATED
ORDER_CONFIRMED
+ ORDER_PAID
ORDER_FULLY_PAID
+ ORDER_REFUNDED
+ ORDER_FULLY_REFUNDED
ORDER_UPDATED
ORDER_CANCELLED
ORDER_EXPIRED
@@ -26722,6 +26779,78 @@ type OrderFullyPaid implements Event @doc(category: "Orders") {
order: Order
}
+"""
+Payment has been made. The order may be partially or fully paid.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type OrderPaid implements Event @doc(category: "Orders") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The order the event relates to."""
+ order: Order
+}
+
+"""
+The order received a refund. The order may be partially or fully refunded.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type OrderRefunded implements Event @doc(category: "Orders") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The order the event relates to."""
+ order: Order
+}
+
+"""
+The order is fully refunded.
+
+Added in Saleor 3.14.
+
+Note: this API is currently in Feature Preview and can be subject to changes at later point.
+"""
+type OrderFullyRefunded implements Event @doc(category: "Orders") {
+ """Time of the event."""
+ issuedAt: DateTime
+
+ """Saleor version that triggered the event."""
+ version: String
+
+ """The user or application that triggered the event."""
+ issuingPrincipal: IssuingPrincipal
+
+ """The application receiving the webhook."""
+ recipient: App
+
+ """The order the event relates to."""
+ order: Order
+}
+
"""
Event sent when order is fulfilled.
diff --git a/saleor/graphql/webhook/enums.py b/saleor/graphql/webhook/enums.py
index 74745cb60b..a459a9eeb7 100644
--- a/saleor/graphql/webhook/enums.py
+++ b/saleor/graphql/webhook/enums.py
@@ -6,6 +6,7 @@ from ..core.descriptions import (
ADDED_IN_38,
ADDED_IN_312,
ADDED_IN_313,
+ ADDED_IN_314,
PREVIEW_FEATURE,
)
from ..core.doc_category import DOC_CATEGORY_WEBHOOKS
@@ -91,7 +92,20 @@ WEBHOOK_EVENT_DESCRIPTION = {
WebhookEventAsyncType.NOTIFY_USER: "User notification triggered.",
WebhookEventAsyncType.ORDER_CREATED: "A new order is placed.",
WebhookEventAsyncType.ORDER_CONFIRMED: order_confirmed_event_enum_description,
+ WebhookEventAsyncType.ORDER_PAID: (
+ "Payment has been made. The order may be partially or fully paid."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ ),
WebhookEventAsyncType.ORDER_FULLY_PAID: order_fully_paid_event_enum_description,
+ WebhookEventAsyncType.ORDER_REFUNDED: (
+ "The order received a refund. The order may be partially or fully refunded."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ ),
+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED: (
+ "The order is fully refunded." + ADDED_IN_314 + PREVIEW_FEATURE
+ ),
WebhookEventAsyncType.ORDER_UPDATED: order_updated_event_enum_description,
WebhookEventAsyncType.ORDER_CANCELLED: "An order is cancelled.",
WebhookEventAsyncType.ORDER_EXPIRED: "An order is expired.",
diff --git a/saleor/graphql/webhook/subscription_types.py b/saleor/graphql/webhook/subscription_types.py
index 5b03c66b47..6db39d995e 100644
--- a/saleor/graphql/webhook/subscription_types.py
+++ b/saleor/graphql/webhook/subscription_types.py
@@ -38,6 +38,7 @@ from ..core.descriptions import (
ADDED_IN_311,
ADDED_IN_312,
ADDED_IN_313,
+ ADDED_IN_314,
PREVIEW_FEATURE,
)
from ..core.doc_category import (
@@ -404,6 +405,38 @@ class OrderFullyPaid(SubscriptionObjectType, OrderBase):
description = "Event sent when order is fully paid." + ADDED_IN_32
+class OrderPaid(SubscriptionObjectType, OrderBase):
+ class Meta:
+ root_type = "Order"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = (
+ "Payment has been made. The order may be partially or fully paid."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ )
+
+
+class OrderRefunded(SubscriptionObjectType, OrderBase):
+ class Meta:
+ root_type = "Order"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = (
+ "The order received a refund. The order may be partially or fully refunded."
+ + ADDED_IN_314
+ + PREVIEW_FEATURE
+ )
+
+
+class OrderFullyRefunded(SubscriptionObjectType, OrderBase):
+ class Meta:
+ root_type = "Order"
+ enable_dry_run = True
+ interfaces = (Event,)
+ description = "The order is fully refunded." + ADDED_IN_314 + PREVIEW_FEATURE
+
+
class OrderFulfilled(SubscriptionObjectType, OrderBase):
class Meta:
root_type = "Order"
@@ -2008,6 +2041,9 @@ WEBHOOK_TYPES_MAP = {
WebhookEventAsyncType.ORDER_UPDATED: OrderUpdated,
WebhookEventAsyncType.ORDER_CONFIRMED: OrderConfirmed,
WebhookEventAsyncType.ORDER_FULLY_PAID: OrderFullyPaid,
+ WebhookEventAsyncType.ORDER_PAID: OrderPaid,
+ WebhookEventAsyncType.ORDER_REFUNDED: OrderRefunded,
+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED: OrderFullyRefunded,
WebhookEventAsyncType.ORDER_FULFILLED: OrderFulfilled,
WebhookEventAsyncType.ORDER_CANCELLED: OrderCancelled,
WebhookEventAsyncType.ORDER_EXPIRED: OrderExpired,
diff --git a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
index 38e2bab091..6a6d60a50e 100644
--- a/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
+++ b/saleor/graphql/webhook/tests/mutations/test_webhook_dry_run.py
@@ -253,6 +253,9 @@ def async_subscription_webhooks_with_root_objects(
subscription_order_updated_webhook,
subscription_order_confirmed_webhook,
subscription_order_fully_paid_webhook,
+ subscription_order_refunded_webhook,
+ subscription_order_fully_refunded_webhook,
+ subscription_order_paid_webhook,
subscription_order_cancelled_webhook,
subscription_order_expired_webhook,
subscription_order_fulfilled_webhook,
@@ -399,6 +402,9 @@ def async_subscription_webhooks_with_root_objects(
events.ORDER_UPDATED: [subscription_order_updated_webhook, order],
events.ORDER_CONFIRMED: [subscription_order_confirmed_webhook, order],
events.ORDER_FULLY_PAID: [subscription_order_fully_paid_webhook, order],
+ events.ORDER_PAID: [subscription_order_paid_webhook, order],
+ events.ORDER_REFUNDED: [subscription_order_refunded_webhook, order],
+ events.ORDER_FULLY_REFUNDED: [subscription_order_fully_refunded_webhook, order],
events.ORDER_FULFILLED: [subscription_order_fulfilled_webhook, order],
events.ORDER_CANCELLED: [subscription_order_cancelled_webhook, order],
events.ORDER_EXPIRED: [subscription_order_expired_webhook, order],
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 17d0e89a96..fbf0f7d5da 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -201,18 +201,55 @@ def order_refunded(
user: Optional[User],
app: Optional["App"],
amount: "Decimal",
- payment: "Payment",
+ payment: Optional["Payment"],
manager: "PluginsManager",
+ trigger_order_updated: bool = True,
):
- events.payment_refunded_event(
- order=order, user=user, app=app, amount=amount, payment=payment
+ if payment:
+ call_event(
+ events.payment_refunded_event,
+ order=order,
+ user=user,
+ app=app,
+ amount=amount,
+ payment=payment,
+ )
+
+ call_event(
+ send_order_refunded_confirmation,
+ order,
+ user,
+ app,
+ amount,
+ order.currency,
+ manager,
)
- call_event(manager.order_updated, order)
- send_order_refunded_confirmation(
- order, user, app, amount, payment.currency, manager
+ call_event(manager.order_refunded, order)
+ if trigger_order_updated:
+ call_event(manager.order_updated, order)
+
+ total_refunded = Decimal(0)
+ last_payment = payment if payment else order.get_last_payment()
+ if last_payment and last_payment.charge_status in [
+ ChargeStatus.PARTIALLY_REFUNDED,
+ ChargeStatus.FULLY_REFUNDED,
+ ]:
+ total_refunded += sum(
+ last_payment.transactions.filter(
+ kind=TransactionKind.REFUND, is_success=True
+ ).values_list("amount", flat=True),
+ Decimal(0),
+ )
+
+ total_refunded += sum(
+ order.payment_transactions.all().values_list("refunded_value", flat=True),
+ Decimal(0),
)
+ if total_refunded >= order.total.gross.amount:
+ call_event(manager.order_fully_refunded, order)
+
def order_voided(
order: "Order",
@@ -325,6 +362,7 @@ def order_charged(
events.payment_captured_event(
order=order, user=user, app=app, amount=amount, payment=payment
)
+ call_event(manager.order_paid, order)
if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:
handle_fully_paid_order(manager, order_info, user, app, site_settings)
else:
@@ -339,6 +377,7 @@ def order_transaction_updated(
app: Optional["App"],
previous_authorized_value: Decimal,
previous_charged_value: Decimal,
+ previous_refunded_value: Decimal,
site_settings: Optional["SiteSettings"] = None,
):
order_updated = False
@@ -359,6 +398,18 @@ def order_transaction_updated(
elif transaction_item.charged_value != previous_charged_value:
order_updated = True
+ if transaction_item.refunded_value > previous_refunded_value:
+ # order_updated False as order_refunded triggers order_updated
+ order_updated = False
+ order_refunded(
+ order=order_info.order,
+ user=user,
+ app=app,
+ amount=transaction_item.refunded_value - previous_refunded_value,
+ payment=None,
+ manager=manager,
+ )
+
if order_updated:
call_event(manager.order_updated, order_info.order)
@@ -1597,20 +1648,18 @@ def _process_refund(
channel_slug=order.channel.slug,
refund_data=refund_data,
)
-
- transaction.on_commit(
- lambda: events.payment_refunded_event(
- order=order,
- user=user,
- app=app,
- amount=amount, # type: ignore
- payment=payment, # type: ignore
- )
- )
- transaction.on_commit(
- lambda: send_order_refunded_confirmation(
- order, user, app, amount, payment.currency, manager # type: ignore
- )
+ payment.refresh_from_db()
+ order_refunded(
+ order=order,
+ user=user,
+ app=app,
+ amount=amount,
+ payment=payment,
+ manager=manager,
+ # The mutations that use this function, always trigger order_updated at the
+ # end of the block. In that case we don't want to duplicate the webhooks
+ # triggered by single mutation.
+ trigger_order_updated=False,
)
transaction.on_commit(
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index ab6fe6c289..948e44b06e 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -433,9 +433,13 @@ def test_cancel_order(
)
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
@patch("saleor.order.actions.send_order_refunded_confirmation")
def test_order_refunded_by_user(
send_order_refunded_confirmation_mock,
+ order_fully_refunded_mock,
+ order_refunded_mock,
order,
checkout_with_item,
):
@@ -451,17 +455,24 @@ def test_order_refunded_by_user(
order_refunded(order, order.user, app, amount, payment, manager)
# then
+ flush_post_commit_hooks()
order_event = order.events.last()
assert order_event.type == OrderEvents.PAYMENT_REFUNDED
send_order_refunded_confirmation_mock.assert_called_once_with(
- order, order.user, None, amount, payment.currency, manager
+ order, order.user, None, amount, order.currency, manager
)
+ order_fully_refunded_mock.assert_called_once_with(order)
+ order_refunded_mock.assert_called_once_with(order)
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
@patch("saleor.order.actions.send_order_refunded_confirmation")
def test_order_refunded_by_app(
send_order_refunded_confirmation_mock,
+ order_fully_refunded_mock,
+ order_refunded_mock,
order,
checkout_with_item,
app,
@@ -477,12 +488,15 @@ def test_order_refunded_by_app(
order_refunded(order, None, app, amount, payment, manager)
# then
+ flush_post_commit_hooks()
order_event = order.events.last()
assert order_event.type == OrderEvents.PAYMENT_REFUNDED
send_order_refunded_confirmation_mock.assert_called_once_with(
- order, None, app, amount, payment.currency, manager
+ order, None, app, amount, order.currency, manager
)
+ order_fully_refunded_mock.assert_called_once_with(order)
+ order_refunded_mock.assert_called_once_with(order)
def test_fulfill_order_lines(order_with_lines):
@@ -706,6 +720,7 @@ def test_order_transaction_updated_order_fully_paid(
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
@@ -738,6 +753,7 @@ def test_order_transaction_updated_order_partially_paid(
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
@@ -773,6 +789,7 @@ def test_order_transaction_updated_order_partially_paid_and_multiple_transaction
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
@@ -807,6 +824,7 @@ def test_order_transaction_updated_with_the_same_transaction_charged_amount(
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=charged_value,
+ previous_refunded_value=Decimal(0),
)
# then
@@ -840,6 +858,7 @@ def test_order_transaction_updated_order_authorized(
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
@@ -875,6 +894,7 @@ def test_order_transaction_updated_order_partially_authorized_and_multiple_trans
app=None,
previous_authorized_value=Decimal(0),
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
@@ -909,9 +929,166 @@ def test_order_transaction_updated_with_the_same_transaction_authorized_amount(
app=None,
previous_authorized_value=authorized_value,
previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
)
# then
flush_post_commit_hooks()
assert not order_fully_paid.called
assert not order_updated.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_transaction_updated_order_fully_refunded(
+ order_fully_refunded, order_refunded, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, refunded_value=order_with_lines.total.gross.amount
+ )
+ manager = get_plugins_manager()
+ updates_amounts_for_order(
+ order_with_lines,
+ )
+
+ # when
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=None,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order_fully_refunded.assert_called_once_with(order_with_lines)
+ order_refunded.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_transaction_updated_order_partially_refunded(
+ order_fully_refunded, order_refunded, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, refunded_value=Decimal(10)
+ )
+ manager = get_plugins_manager()
+ updates_amounts_for_order(
+ order_with_lines,
+ )
+
+ # when
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=None,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_refunded.called
+ order_refunded.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_transaction_updated_order_fully_refunded_and_multiple_transactions(
+ order_fully_refunded, order_refunded, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item_generator(
+ order_id=order_with_lines.pk, refunded_value=Decimal("10")
+ )
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ refunded_value=order_with_lines.total.gross.amount - Decimal("10"),
+ )
+ manager = get_plugins_manager()
+ updates_amounts_for_order(
+ order_with_lines,
+ )
+
+ # when
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=None,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order_fully_refunded.assert_called_once_with(order_with_lines)
+ order_refunded.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+def test_order_transaction_updated_order_fully_refunded_with_transaction_and_payment(
+ order_fully_refunded,
+ order_refunded,
+ order_with_lines,
+ transaction_item_generator,
+ payment_dummy,
+):
+ # given
+ payment = payment_dummy
+ payment.order = order_with_lines
+ payment.charge_status = ChargeStatus.PARTIALLY_REFUNDED
+ payment.is_active = True
+ payment.save()
+
+ payment.transactions.create(
+ amount=Decimal("10"),
+ currency=payment.currency,
+ kind=TransactionKind.REFUND,
+ gateway_response={},
+ is_success=True,
+ )
+
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ refunded_value=order_with_lines.total.gross.amount - Decimal("10"),
+ )
+
+ manager = get_plugins_manager()
+ updates_amounts_for_order(
+ order_with_lines,
+ )
+
+ # when
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=None,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ previous_refunded_value=Decimal(0),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order_refunded.assert_called_once_with(order_with_lines)
+ order_fully_refunded.assert_called_once_with(order_with_lines)
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index b83f4a0ee8..0eae174992 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -499,12 +499,14 @@ def test_create_transaction_event_from_request_updates_order_charge(
assert order.search_vector
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_triggers_webhooks_when_fully_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
transaction_item_generator,
app,
order_with_lines,
@@ -541,14 +543,17 @@ def test_create_transaction_event_from_request_triggers_webhooks_when_fully_paid
assert order.charge_status == OrderChargeStatus.FULL
mock_order_fully_paid.assert_called_once_with(order)
mock_order_updated.assert_called_once_with(order)
+ mock_order_paid.assert_called_once_with(order)
+@patch("saleor.plugins.manager.PluginsManager.order_paid")
@patch("saleor.plugins.manager.PluginsManager.order_updated")
@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_triggers_webhooks_when_partially_paid(
mock_order_fully_paid,
mock_order_updated,
+ mock_order_paid,
transaction_item_generator,
app,
order_with_lines,
@@ -585,6 +590,101 @@ def test_create_transaction_event_from_request_triggers_webhooks_when_partially_
assert order_with_lines.charge_status == OrderChargeStatus.PARTIAL
assert not mock_order_fully_paid.called
mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_paid.assert_called_once_with(order)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_triggers_webhooks_when_fully_refunded(
+ mock_order_fully_refunded,
+ mock_order_updated,
+ mock_order_refunded,
+ transaction_item_generator,
+ app,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ transaction = transaction_item_generator(order_id=order.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=order.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = order.total.gross.amount
+ event_type = TransactionEventType.REFUND_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order.refresh_from_db()
+
+ mock_order_fully_refunded.assert_called_once_with(order)
+ mock_order_updated.assert_called_once_with(order)
+ mock_order_refunded.assert_called_once_with(order)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_refunded")
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_refunded")
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_triggers_webhooks_partially_refunded(
+ mock_order_fully_refunded,
+ mock_order_updated,
+ mock_order_refunded,
+ transaction_item_generator,
+ app,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ transaction = transaction_item_generator(order_id=order.pk)
+ request_event = TransactionEvent.objects.create(
+ type=TransactionEventType.REFUND_REQUEST,
+ amount_value=Decimal("12.00"),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = Decimal("12.00")
+ event_type = TransactionEventType.REFUND_SUCCESS
+
+ expected_psp_reference = "psp:122:222"
+
+ response_data = {
+ "pspReference": expected_psp_reference,
+ "amount": event_amount,
+ "result": event_type.upper(),
+ }
+
+ # when
+ create_transaction_event_from_request_and_webhook_response(
+ request_event, app, response_data
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order.refresh_from_db()
+
+ assert not mock_order_fully_refunded.called
+ mock_order_updated.assert_called_once_with(order_with_lines)
+ mock_order_refunded.assert_called_once_with(order)
@patch("saleor.plugins.manager.PluginsManager.order_updated")
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 8fb2bc3837..80e61e2908 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1130,6 +1130,7 @@ def create_transaction_event_for_transaction_session(
transaction_item = event.transaction
previous_authorized_value = transaction_item.authorized_value
previous_charged_value = transaction_item.charged_value
+ previous_refunded_value = transaction_item.refunded_value
transaction_item.psp_reference = event.psp_reference
recalculate_transaction_amounts(transaction_item, save=False)
@@ -1161,6 +1162,7 @@ def create_transaction_event_for_transaction_session(
app=app,
previous_authorized_value=previous_authorized_value,
previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
)
elif transaction_item.checkout_id:
transaction_amounts_for_checkout_updated(
@@ -1198,6 +1200,7 @@ def create_transaction_event_from_request_and_webhook_response(
transaction_item = request_event.transaction
previous_authorized_value = transaction_item.authorized_value
previous_charged_value = transaction_item.charged_value
+ previous_refunded_value = transaction_item.refunded_value
recalculate_transaction_amounts(transaction_item)
if transaction_item.order_id:
@@ -1216,6 +1219,7 @@ def create_transaction_event_from_request_and_webhook_response(
app=app,
previous_authorized_value=previous_authorized_value,
previous_charged_value=previous_charged_value,
+ previous_refunded_value=previous_refunded_value,
)
elif transaction_item.checkout_id:
discounts = fetch_active_discounts()
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index fad6a0a829..710de514f0 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -699,6 +699,24 @@ class BasePlugin:
# fully paid.
order_fully_paid: Callable[["Order", Any], Any]
+ # Trigger when order is paid.
+ #
+ # Overwrite this method if you need to trigger specific logic when an order is
+ # received the payment.
+ order_paid: Callable[["Order", Any], Any]
+
+ # Trigger when order is refunded.
+ #
+ # Overwrite this method if you need to trigger specific logic when an order is
+ # refunded.
+ order_refunded: Callable[["Order", Any], Any]
+
+ # Trigger when order is fully refunded.
+ #
+ # Overwrite this method if you need to trigger specific logic when an order is
+ # fully refunded.
+ order_fully_refunded: Callable[["Order", Any], Any]
+
# Trigger when order is updated.
#
# Overwrite this method if you need to trigger specific logic when an order is
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 388d6717b8..e6e6e31213 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -814,6 +814,27 @@ class PluginsManager(PaymentInterface):
"order_fully_paid", default_value, order, channel_slug=order.channel.slug
)
+ def order_paid(self, order: "Order"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "order_paid", default_value, order, channel_slug=order.channel.slug
+ )
+
+ def order_fully_refunded(self, order: "Order"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "order_fully_refunded",
+ default_value,
+ order,
+ channel_slug=order.channel.slug,
+ )
+
+ def order_refunded(self, order: "Order"):
+ default_value = None
+ return self.__run_method_on_plugins(
+ "order_refunded", default_value, order, channel_slug=order.channel.slug
+ )
+
def order_updated(self, order: "Order"):
default_value = None
return self.__run_method_on_plugins(
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 15a0f804b0..a146fd32cb 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -336,6 +336,15 @@ class PluginSample(BasePlugin):
def checkout_fully_paid(self, checkout):
return None
+ def order_fully_refunded(self, order):
+ return None
+
+ def order_paid(self, order):
+ return None
+
+ def order_refunded(self, order):
+ return None
+
class ChannelPluginSample(PluginSample):
PLUGIN_ID = "channel.plugin.sample"
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 22a5c2d9c8..a60b35dfe8 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -1299,5 +1299,55 @@ def test_checkout_fully_paid(mocked_sample_method, checkout):
manager.checkout_fully_paid(checkout)
# then
-
mocked_sample_method.assert_called_once_with(checkout, previous_value=None)
+
+
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.order_fully_refunded")
+def test_order_fully_refunded(mocked_sample_method, order):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ manager.order_fully_refunded(order)
+
+ # then
+ mocked_sample_method.assert_called_once_with(order, previous_value=None)
+
+
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.order_refunded")
+def test_order_refunded(mocked_sample_method, order):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ manager.order_refunded(order)
+
+ # then
+ mocked_sample_method.assert_called_once_with(order, previous_value=None)
+
+
+@patch("saleor.plugins.tests.sample_plugins.PluginSample.order_paid")
+def test_order_paid(mocked_sample_method, order):
+ # given
+ plugins = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ ]
+
+ manager = PluginsManager(plugins=plugins)
+
+ # when
+ manager.order_paid(order)
+
+ # then
+ mocked_sample_method.assert_called_once_with(order, previous_value=None)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 51761cf1da..fefeb1dbb3 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -525,6 +525,36 @@ class WebhookPlugin(BasePlugin):
order_data, event_type, webhooks, order, self.requestor
)
+ def order_paid(self, order: "Order", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.ORDER_PAID
+ if webhooks := get_webhooks_for_event(event_type):
+ order_data = generate_order_payload(order, self.requestor)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
+
+ def order_refunded(self, order: "Order", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.ORDER_REFUNDED
+ if webhooks := get_webhooks_for_event(event_type):
+ order_data = generate_order_payload(order, self.requestor)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
+
+ def order_fully_refunded(self, order: "Order", previous_value: Any) -> Any:
+ if not self.active:
+ return previous_value
+ event_type = WebhookEventAsyncType.ORDER_FULLY_REFUNDED
+ if webhooks := get_webhooks_for_event(event_type):
+ order_data = generate_order_payload(order, self.requestor)
+ trigger_webhooks_async(
+ order_data, event_type, webhooks, order, self.requestor
+ )
+
def order_updated(self, order: "Order", previous_value: Any) -> Any:
if not self.active:
return previous_value
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
index 9b924dbf6d..f11a4c7751 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/fixtures.py
@@ -436,6 +436,25 @@ def subscription_order_fully_paid_webhook(subscription_webhook):
)
+def subscription_order_paid_webhook(subscription_webhook):
+ return subscription_webhook(queries.ORDER_PAID, WebhookEventAsyncType.ORDER_PAID)
+
+
+def subscription_order_fully_refunded_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.ORDER_FULLY_REFUNDED, WebhookEventAsyncType.ORDER_FULLY_REFUNDED
+ )
+
+
+def subscription_order_refunded_webhook(subscription_webhook):
+ return subscription_webhook(
+ queries.ORDER_REFUNDED, WebhookEventAsyncType.ORDER_REFUNDED
+ )
+
+
@pytest.fixture
def subscription_order_cancelled_webhook(subscription_webhook):
return subscription_webhook(
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
index f6febe156a..0982f62b27 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/subscription_queries.py
@@ -884,6 +884,42 @@ ORDER_FULLY_PAID = """
}
"""
+ORDER_PAID = """
+ subscription{
+ event{
+ ...on OrderPaid{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+ORDER_FULLY_REFUNDED = """
+ subscription{
+ event{
+ ...on OrderFullyRefunded{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
+ORDER_REFUNDED = """
+ subscription{
+ event{
+ ...on OrderRefunded{
+ order{
+ id
+ }
+ }
+ }
+ }
+"""
+
ORDER_CANCELLED = """
subscription{
event{
diff --git a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
index 77c5c3d896..27fbc40ae5 100644
--- a/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
+++ b/saleor/plugins/webhook/tests/subscription_webhooks/test_create_deliveries_for_subscription.py
@@ -1200,6 +1200,42 @@ def test_order_fully_paid(order, subscription_order_fully_paid_webhook):
assert deliveries[0].webhook == webhooks[0]
+def test_order_paid(order, subscription_order_paid_webhook):
+ webhooks = [subscription_order_paid_webhook]
+ event_type = WebhookEventAsyncType.ORDER_PAID
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps({"order": {"id": order_id}})
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_fully_refunded(order, subscription_order_fully_refunded_webhook):
+ webhooks = [subscription_order_fully_refunded_webhook]
+ event_type = WebhookEventAsyncType.ORDER_FULLY_REFUNDED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps({"order": {"id": order_id}})
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
+def test_order_refunded(order, subscription_order_refunded_webhook):
+ webhooks = [subscription_order_refunded_webhook]
+ event_type = WebhookEventAsyncType.ORDER_REFUNDED
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ deliveries = create_deliveries_for_subscriptions(event_type, order, webhooks)
+ expected_payload = json.dumps({"order": {"id": order_id}})
+
+ assert deliveries[0].payload.payload == expected_payload
+ assert len(deliveries) == len(webhooks)
+ assert deliveries[0].webhook == webhooks[0]
+
+
def test_order_updated(order, subscription_order_updated_webhook):
webhooks = [subscription_order_updated_webhook]
event_type = WebhookEventAsyncType.ORDER_UPDATED
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index 18f842f518..23f0e1a8e6 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -348,6 +348,96 @@ def test_order_fully_paid(
)
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_order_paid(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order_with_lines,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+
+ # when
+ manager.order_paid(order_with_lines)
+
+ # then
+ expected_data = generate_order_payload(order_with_lines)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.ORDER_PAID,
+ [any_webhook],
+ order_with_lines,
+ None,
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_order_refunded(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order_with_lines,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+
+ # when
+ manager.order_refunded(order_with_lines)
+
+ # then
+ expected_data = generate_order_payload(order_with_lines)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.ORDER_REFUNDED,
+ [any_webhook],
+ order_with_lines,
+ None,
+ )
+
+
+@freeze_time("1914-06-28 10:50")
[email protected]("saleor.plugins.webhook.plugin.get_webhooks_for_event")
[email protected]("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_order_fully_refunded(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ settings,
+ order_with_lines,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+ manager = get_plugins_manager()
+
+ # when
+ manager.order_fully_refunded(order_with_lines)
+
+ # then
+ expected_data = generate_order_payload(order_with_lines)
+
+ mocked_webhook_trigger.assert_called_once_with(
+ expected_data,
+ WebhookEventAsyncType.ORDER_FULLY_REFUNDED,
+ [any_webhook],
+ order_with_lines,
+ None,
+ )
+
+
@freeze_time("1914-06-28 10:50")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/webhook/event_types.py b/saleor/webhook/event_types.py
index ad0a8cf9fa..0d0ddb1436 100644
--- a/saleor/webhook/event_types.py
+++ b/saleor/webhook/event_types.py
@@ -61,7 +61,10 @@ class WebhookEventAsyncType:
ORDER_CREATED = "order_created"
ORDER_CONFIRMED = "order_confirmed"
+ ORDER_PAID = "order_paid"
ORDER_FULLY_PAID = "order_fully_paid"
+ ORDER_REFUNDED = "order_refunded"
+ ORDER_FULLY_REFUNDED = "order_fully_refunded"
ORDER_UPDATED = "order_updated"
ORDER_CANCELLED = "order_cancelled"
ORDER_EXPIRED = "order_expired"
@@ -202,7 +205,10 @@ class WebhookEventAsyncType:
MENU_ITEM_DELETED: "Menu item deleted",
ORDER_CREATED: "Order created",
ORDER_CONFIRMED: "Order confirmed",
- ORDER_FULLY_PAID: "Order paid",
+ ORDER_PAID: "Order paid",
+ ORDER_FULLY_PAID: "Order fully paid",
+ ORDER_REFUNDED: "Order refunded",
+ ORDER_FULLY_REFUNDED: "Order fully refunded",
ORDER_UPDATED: "Order updated",
ORDER_CANCELLED: "Order cancelled",
ORDER_EXPIRED: "Order expired",
@@ -320,7 +326,10 @@ class WebhookEventAsyncType:
(MENU_ITEM_DELETED, DISPLAY_LABELS[MENU_ITEM_DELETED]),
(ORDER_CREATED, DISPLAY_LABELS[ORDER_CREATED]),
(ORDER_CONFIRMED, DISPLAY_LABELS[ORDER_CONFIRMED]),
+ (ORDER_PAID, DISPLAY_LABELS[ORDER_PAID]),
(ORDER_FULLY_PAID, DISPLAY_LABELS[ORDER_FULLY_PAID]),
+ (ORDER_REFUNDED, DISPLAY_LABELS[ORDER_REFUNDED]),
+ (ORDER_FULLY_REFUNDED, DISPLAY_LABELS[ORDER_FULLY_REFUNDED]),
(ORDER_UPDATED, DISPLAY_LABELS[ORDER_UPDATED]),
(ORDER_CANCELLED, DISPLAY_LABELS[ORDER_CANCELLED]),
(ORDER_EXPIRED, DISPLAY_LABELS[ORDER_EXPIRED]),
@@ -448,7 +457,10 @@ class WebhookEventAsyncType:
MENU_ITEM_DELETED: MenuPermissions.MANAGE_MENUS,
ORDER_CREATED: OrderPermissions.MANAGE_ORDERS,
ORDER_CONFIRMED: OrderPermissions.MANAGE_ORDERS,
+ ORDER_PAID: OrderPermissions.MANAGE_ORDERS,
ORDER_FULLY_PAID: OrderPermissions.MANAGE_ORDERS,
+ ORDER_REFUNDED: OrderPermissions.MANAGE_ORDERS,
+ ORDER_FULLY_REFUNDED: OrderPermissions.MANAGE_ORDERS,
ORDER_UPDATED: OrderPermissions.MANAGE_ORDERS,
ORDER_CANCELLED: OrderPermissions.MANAGE_ORDERS,
ORDER_EXPIRED: OrderPermissions.MANAGE_ORDERS,