Skip to content

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

Add missing trigger webhooks for transactions (#12508)

Maciej Korycinski1a446947e9a7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f2c049257f..bc79e46ddf 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -134,6 +134,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Core now supports Dev Containers for local development - #12391 by @patrys
- Use mailhog smtp server on Dev Container - #12402 by @carlosa54
- Publish schema.graphql on releases - #12431 by @maarcingebala
+- Fix missing webhook triggers for `order_updated` and `order_fully_paid` when an order is paid with a `transactionItem` - #12508 by @korycins
### Saleor Apps
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 1f1e89e8a1..751e9ef071 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -1277,6 +1277,7 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(
(
order_marked_as_paid,
order_placed_event,
+ order_fully_paid,
order_confirmed_event,
) = order.events.all() # type: OrderEvent
@@ -1310,6 +1311,9 @@ def test_complete_checkout_0_total_captured_payment_creates_expected_events(
**get_site_context_payload(site_settings.site),
}
+ assert order_fully_paid.type == OrderEvents.ORDER_FULLY_PAID
+ assert order_fully_paid.user == checkout_user
+
# Ensure the correct order confirmed event was created
# should be order confirmed event
assert order_confirmed_event.type == OrderEvents.CONFIRMED
diff --git a/saleor/graphql/order/mutations/order_capture.py b/saleor/graphql/order/mutations/order_capture.py
index be7e5b226b..2cbe50b5c1 100644
--- a/saleor/graphql/order/mutations/order_capture.py
+++ b/saleor/graphql/order/mutations/order_capture.py
@@ -3,7 +3,7 @@ from typing import Optional
import graphene
from django.core.exceptions import ValidationError
-from ....order.actions import order_captured
+from ....order.actions import order_charged
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
from ....payment import TransactionKind, gateway
@@ -90,7 +90,7 @@ class OrderCapture(BaseMutation):
# asynchronous webhook with update status
if transaction.kind == TransactionKind.CAPTURE:
site = get_site_promise(info.context).get()
- order_captured(
+ order_charged(
order_info,
info.context.user,
app,
diff --git a/saleor/graphql/order/mutations/order_confirm.py b/saleor/graphql/order/mutations/order_confirm.py
index f1849b5277..e7cc6ba75c 100644
--- a/saleor/graphql/order/mutations/order_confirm.py
+++ b/saleor/graphql/order/mutations/order_confirm.py
@@ -7,7 +7,7 @@ from django.db import transaction
from ....account.models import User
from ....core.tracing import traced_atomic_transaction
from ....order import OrderStatus, models
-from ....order.actions import order_captured, order_confirmed
+from ....order.actions import order_charged, order_confirmed
from ....order.error_codes import OrderErrorCode
from ....order.fetch import fetch_order_info
from ....order.utils import update_order_display_gross_prices
@@ -78,7 +78,7 @@ class OrderConfirm(ModelMutation):
gateway.capture(payment, manager, channel_slug=order.channel.slug)
site = get_site_promise(info.context).get()
transaction.on_commit(
- lambda: order_captured(
+ lambda: order_charged(
order_info,
info.context.user,
app,
diff --git a/saleor/graphql/order/tests/mutations/test_order_confirm.py b/saleor/graphql/order/tests/mutations/test_order_confirm.py
index 8196d04446..b691051344 100644
--- a/saleor/graphql/order/tests/mutations/test_order_confirm.py
+++ b/saleor/graphql/order/tests/mutations/test_order_confirm.py
@@ -10,6 +10,7 @@ from .....order.error_codes import OrderErrorCode
from .....order.fetch import fetch_order_info
from .....order.models import OrderEvent
from .....order.notifications import get_default_order_payload
+from .....order.utils import updates_amounts_for_order
from .....product.models import ProductVariant
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -50,6 +51,7 @@ def test_order_confirm(
order_unconfirmed.total_charged = order_unconfirmed.total.gross
order_unconfirmed.save(update_fields=["total_charged_amount"])
+ updates_amounts_for_order(order_unconfirmed)
staff_api_client.user.user_permissions.add(permission_manage_orders)
assert not OrderEvent.objects.exists()
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index c1588b6ba3..1b579514d3 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -29,7 +29,9 @@ 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.events import transaction_event as order_transaction_event
+from ...order.fetch import fetch_order_info
from ...order.models import Order
from ...order.search import update_order_search_vector
from ...order.utils import updates_amounts_for_order
@@ -996,19 +998,20 @@ class TransactionCreate(BaseMutation):
@classmethod
def update_order(
- cls, order: order_models.Order, money_data: dict, *args, **kwargs
+ cls,
+ order: order_models.Order,
+ money_data: dict,
+ update_search_vector: bool = True,
) -> None:
update_fields = []
if money_data:
- update_order_search_vector(order, save=False)
updates_amounts_for_order(order, save=False)
update_fields.extend(
[
- "total_charged_amount",
- "charge_status",
"total_authorized_amount",
+ "total_charged_amount",
"authorize_status",
- "search_vector",
+ "charge_status",
]
)
if (
@@ -1017,6 +1020,13 @@ class TransactionCreate(BaseMutation):
):
order.status = OrderStatus.UNFULFILLED
update_fields.append("status")
+
+ if update_search_vector:
+ update_order_search_vector(order, save=False)
+ update_fields.append(
+ "search_vector",
+ )
+
if update_fields:
update_fields.append("updated_at")
order.save(update_fields=update_fields)
@@ -1041,6 +1051,7 @@ class TransactionCreate(BaseMutation):
transaction_data["currency"] = order_or_checkout_instance.currency
app = get_app_promise(info.context).get()
user = info.context.user
+ manager = get_plugin_manager_promise(info.context).get()
if isinstance(order_or_checkout_instance, checkout_models.Checkout):
transaction_data["checkout_id"] = order_or_checkout_instance.pk
@@ -1066,10 +1077,20 @@ class TransactionCreate(BaseMutation):
recalculate_transaction_amounts(new_transaction)
if transaction_data.get("order_id") and money_data:
order = cast(order_models.Order, new_transaction.order)
- cls.update_order(order, money_data)
+ cls.update_order(order, money_data, update_search_vector=True)
+
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=new_transaction,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=Decimal(0),
+ previous_charged_value=Decimal(0),
+ )
if transaction_data.get("checkout_id") and money_data:
discounts = load_discounts(info.context)
- manager = get_plugin_manager_promise(info.context).get()
transaction_amounts_for_checkout_updated(
new_transaction, discounts, manager
)
@@ -1183,11 +1204,10 @@ class TransactionUpdate(TransactionCreate):
cls,
instance: payment_models.TransactionItem,
transaction_data: dict,
+ money_data: dict,
user: Optional["User"],
app: Optional["App"],
- info: ResolveInfo,
):
- money_data = cls.get_money_data_from_input(transaction_data)
psp_reference = transaction_data.get(
"psp_reference", transaction_data.pop("reference", None)
)
@@ -1215,48 +1235,6 @@ class TransactionUpdate(TransactionCreate):
transaction=instance, money_data=money_data, user=user, app=app
)
recalculate_transaction_amounts(instance)
- if instance.order_id:
- order = cast(order_models.Order, instance.order)
- cls.update_order(order, money_data, psp_reference)
- if instance.checkout_id and money_data:
- discounts = load_discounts(info.context)
- manager = get_plugin_manager_promise(info.context).get()
- transaction_amounts_for_checkout_updated(instance, discounts, manager)
-
- @classmethod
- def update_order(
- cls,
- order: "Order",
- money_data: dict,
- psp_reference: Optional[str] = None,
- *args,
- **kwargs
- ) -> None:
- update_fields = []
- if money_data:
- updates_amounts_for_order(order)
- update_fields.extend(
- [
- "total_charged_amount",
- "charge_status",
- "total_authorized_amount",
- "authorize_status",
- ]
- )
- if psp_reference:
- update_order_search_vector(order, save=False)
- update_fields.append(
- "search_vector",
- )
- if (
- order.channel.automatically_confirm_all_new_orders
- and order.status == OrderStatus.UNCONFIRMED
- ):
- order.status = OrderStatus.UNFULFILLED
- update_fields.append("status")
- if update_fields:
- update_fields.append("updated_at")
- order.save(update_fields=update_fields)
@classmethod
def perform_mutation( # type: ignore[override]
@@ -1272,20 +1250,27 @@ class TransactionUpdate(TransactionCreate):
app = get_app_promise(info.context).get()
user = info.context.user
instance = get_transaction_item(id)
+ manager = get_plugin_manager_promise(info.context).get()
cls.check_can_update(
transaction=instance,
user=user if user and user.is_authenticated else None,
app=app,
)
+ money_data = {}
+ previous_transaction_psp_reference = instance.psp_reference
+ previous_authorized_value = instance.authorized_value
+ previous_charged_value = instance.charged_value
if transaction:
cls.validate_transaction_input(instance, transaction)
cls.cleanup_metadata_data(transaction)
- cls.update_transaction(instance, transaction, user, app, info)
+ money_data = cls.get_money_data_from_input(transaction)
+ cls.update_transaction(instance, transaction, money_data, user, app)
+ event = None
if transaction_event:
- cls.create_transaction_event(transaction_event, instance, user, app)
+ event = cls.create_transaction_event(transaction_event, instance, user, app)
if instance.order:
reference = transaction_event.pop("reference", None)
psp_reference = transaction_event.get("psp_reference", reference)
@@ -1297,6 +1282,30 @@ class TransactionUpdate(TransactionCreate):
status=transaction_event["status"],
message=cls.create_event_message(transaction_event),
)
+ if instance.order_id:
+ order = cast(order_models.Order, instance.order)
+ should_update_search_vector = bool(
+ (instance.psp_reference != previous_transaction_psp_reference)
+ or (event and event.psp_reference)
+ )
+ cls.update_order(
+ order, money_data, update_search_vector=should_update_search_vector
+ )
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=instance,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ )
+ if instance.checkout_id and money_data:
+ discounts = load_discounts(info.context)
+ manager = get_plugin_manager_promise(info.context).get()
+ transaction_amounts_for_checkout_updated(instance, discounts, manager)
+
return TransactionUpdate(transaction=instance)
@@ -1516,6 +1525,8 @@ class TransactionEventReport(ModelMutation):
):
user = info.context.user
app = get_app_promise(info.context).get()
+ manager = get_plugin_manager_promise(info.context).get()
+
transaction = get_transaction_item(id)
if not check_if_requestor_has_access(
@@ -1591,6 +1602,8 @@ class TransactionEventReport(ModelMutation):
create_failed_transaction_event(transaction_event, cause=error_msg)
raise ValidationError({error_field: ValidationError(error_msg, error_code)})
if not already_processed:
+ previous_authorized_value = transaction.authorized_value
+ previous_charged_value = transaction.charged_value
if available_actions is not None:
transaction.available_actions = available_actions
transaction.save(update_fields=["available_actions"])
@@ -1609,6 +1622,16 @@ class TransactionEventReport(ModelMutation):
"search_vector",
]
)
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction,
+ manager=manager,
+ user=user,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ )
if transaction.checkout_id:
discounts = load_discounts(info.context)
manager = get_plugin_manager_promise(info.context).get()
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 2094491d63..48b3e9c1db 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -7,7 +7,7 @@ from mock import patch
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....order import OrderAuthorizeStatus, OrderEvents, OrderStatus
+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents, OrderStatus
from .....order.utils import update_order_authorize_data, update_order_charge_data
from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionCreateErrorCode
@@ -1767,3 +1767,123 @@ def test_transaction_create_creates_calculation_events(
).first()
assert cancel_event
assert cancel_event.amount.amount == canceled_value
+
+
+@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,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ charged_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": [],
+ "amountCharged": {
+ "amount": charged_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 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)
+
+
+@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,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ charged_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": [],
+ "amountCharged": {
+ "amount": charged_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 order_with_lines.charge_status == OrderChargeStatus.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_fully_paid")
+def test_transaction_create_for_order_triggers_webhook_when_authorized(
+ mock_order_fully_paid,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ staff_api_client,
+):
+ # given
+ authorized_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": [],
+ "amountAuthorized": {
+ "amount": authorized_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 order_with_lines.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert not mock_order_fully_paid.called
+ mock_order_updated.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 393f75605c..c60758c296 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -1230,3 +1230,223 @@ def test_transaction_event_report_doesnt_accept_old_id_for_new_transaction(
error = transaction_report_data["errors"][0]
assert error["code"] == TransactionEventReportErrorCode.NOT_FOUND.name
assert error["field"] == "id"
+
+
+@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,
+ 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.CHARGE_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()
+
+ assert order.charge_status == OrderChargeStatusEnum.FULL.value
+ mock_order_fully_paid.assert_called_once_with(order)
+ mock_order_updated.assert_called_once_with(order)
+
+
+@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_partially_paid(
+ mock_order_fully_paid,
+ mock_order_updated,
+ 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.CHARGE_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 order.charge_status == OrderChargeStatusEnum.PARTIAL.value
+ assert not mock_order_fully_paid.called
+ mock_order_updated.assert_called_once_with(order)
+
+
+@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_partially_authorized(
+ mock_order_fully_paid,
+ mock_order_updated,
+ 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.AUTHORIZATION_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 order.authorize_status == OrderAuthorizeStatusEnum.PARTIAL.value
+ assert not mock_order_fully_paid.called
+ mock_order_updated.assert_called_once_with(order)
+
+
+@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_authorized(
+ mock_order_fully_paid,
+ mock_order_updated,
+ 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.AUTHORIZATION_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()
+
+ assert order.authorize_status == OrderAuthorizeStatusEnum.FULL.value
+ assert not mock_order_fully_paid.called
+ 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 c76282f69b..1b2d48d447 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -7,7 +7,7 @@ from mock import patch
from .....checkout import CheckoutAuthorizeStatus, CheckoutChargeStatus
from .....checkout.calculations import fetch_checkout_data
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....order import OrderEvents
+from .....order import OrderAuthorizeStatus, OrderChargeStatus, OrderEvents
from .....payment import TransactionEventStatus, TransactionEventType
from .....payment.error_codes import TransactionUpdateErrorCode
from .....payment.models import TransactionEvent, TransactionItem
@@ -2483,7 +2483,7 @@ def test_transaction_update_amounts_are_correct(
) == sum(provided_amounts.values())
-def test_transaction_create_for_checkout_updates_payment_statuses(
+def test_transaction_update_for_checkout_updates_payment_statuses(
checkout_with_items,
permission_manage_payments,
app_api_client,
@@ -2528,7 +2528,7 @@ def test_transaction_create_for_checkout_updates_payment_statuses(
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
-def test_transaction_create_for_checkout_fully_paid(
+def test_transaction_update_for_checkout_fully_paid(
mocked_checkout_fully_paid,
checkout_with_prices,
permission_manage_payments,
@@ -2631,3 +2631,141 @@ def test_transaction_update_doesnt_accept_old_id_for_new_transactions(
error = errors[0]
assert error["code"] == TransactionUpdateErrorCode.NOT_FOUND.name
assert error["field"] == "id"
+
+
+@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,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+ transaction_item_generator,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountCharged": {
+ "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)
+
+ 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)
+
+
+@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,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+ transaction_item_generator,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountCharged": {
+ "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 order_with_lines.charge_status == OrderChargeStatus.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_fully_paid")
+def test_transaction_update_for_order_triggers_webhook_when_authorized(
+ mock_order_fully_paid,
+ mock_order_updated,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+ app,
+ transaction_item_generator,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ transaction = transaction_item_generator(
+ order_id=order_with_lines.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {
+ "amountAuthorized": {
+ "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 order_with_lines.authorize_status == OrderAuthorizeStatus.PARTIAL
+ assert not mock_order_fully_paid.called
+ mock_order_updated.assert_called_once_with(order_with_lines)
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index ae4b16f71d..17d0e89a96 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -23,7 +23,7 @@ from ..payment import (
gateway,
)
from ..payment.interface import RefundData
-from ..payment.models import Payment, Transaction
+from ..payment.models import Payment, Transaction, TransactionItem
from ..payment.utils import create_payment, create_transaction_for_order
from ..warehouse.management import (
deallocate_stock,
@@ -35,6 +35,7 @@ from ..warehouse.models import Stock
from . import (
FulfillmentLineData,
FulfillmentStatus,
+ OrderChargeStatus,
OrderOrigin,
OrderStatus,
events,
@@ -96,26 +97,26 @@ def order_created(
events.order_created_event(order=order, user=user, app=app, from_draft=from_draft)
call_event(manager.order_created, order)
payment = order_info.payment
- if payment:
- if order.is_captured():
- order_captured(
- order_info=order_info,
- user=user,
- app=app,
- amount=payment.total,
- payment=payment,
- manager=manager,
- site_settings=site_settings,
- )
- elif order.is_pre_authorized():
- order_authorized(
- order=order,
- user=user,
- app=app,
- amount=payment.total,
- payment=payment,
- manager=manager,
- )
+ if payment and order.is_pre_authorized():
+ order_authorized(
+ order=order,
+ user=user,
+ app=app,
+ amount=payment.total,
+ payment=payment,
+ manager=manager,
+ )
+ if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:
+ order_charged(
+ order_info=order_info,
+ user=user,
+ app=app,
+ amount=payment.total if payment else None,
+ payment=payment,
+ manager=manager,
+ site_settings=site_settings,
+ )
+
channel = order_info.channel
if channel.automatically_confirm_all_new_orders or from_draft:
order_confirmed(order, user, app, manager)
@@ -310,22 +311,56 @@ def order_authorized(
call_event(manager.order_updated, order)
-def order_captured(
+def order_charged(
order_info: "OrderInfo",
user: Optional[User],
app: Optional["App"],
- amount: "Decimal",
- payment: "Payment",
+ amount: Optional["Decimal"],
+ payment: Optional["Payment"],
manager: "PluginsManager",
site_settings: Optional["SiteSettings"] = None,
):
order = order_info.order
- events.payment_captured_event(
- order=order, user=user, app=app, amount=amount, payment=payment
- )
- call_event(manager.order_updated, order)
- if order.is_fully_paid():
+ if payment and amount is not None:
+ events.payment_captured_event(
+ order=order, user=user, app=app, amount=amount, payment=payment
+ )
+ if order.charge_status in [OrderChargeStatus.FULL, OrderChargeStatus.OVERCHARGED]:
handle_fully_paid_order(manager, order_info, user, app, site_settings)
+ else:
+ call_event(manager.order_updated, order)
+
+
+def order_transaction_updated(
+ order_info: "OrderInfo",
+ transaction_item: "TransactionItem",
+ manager: "PluginsManager",
+ user: Optional[User],
+ app: Optional["App"],
+ previous_authorized_value: Decimal,
+ previous_charged_value: Decimal,
+ site_settings: Optional["SiteSettings"] = None,
+):
+ order_updated = False
+ if transaction_item.authorized_value != previous_authorized_value:
+ order_updated = True
+ if transaction_item.charged_value > previous_charged_value:
+ # order_updated False as order_charged triggers order_updated
+ order_updated = False
+ order_charged(
+ order_info,
+ user,
+ app,
+ amount=order_info.payment.total if order_info.payment else None,
+ payment=order_info.payment,
+ site_settings=site_settings,
+ manager=manager,
+ )
+ elif transaction_item.charged_value != previous_charged_value:
+ order_updated = True
+
+ if order_updated:
+ call_event(manager.order_updated, order_info.order)
def fulfillment_tracking_updated(
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index c69f611313..ffd93f1d9a 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -374,22 +374,27 @@ def send_fulfillment_update(order, fulfillment, manager):
def send_payment_confirmation(order_info, manager):
"""Send notification with the payment confirmation."""
payment = order_info.payment
- payment_currency = payment.currency
payload = {
"order": get_default_order_payload(order_info.order),
"recipient_email": order_info.customer_email,
- "payment": {
- "created": payment.created_at,
- "modified": payment.modified_at,
- "charge_status": payment.charge_status,
- "total": quantize_price(payment.total, payment_currency),
- "captured_amount": quantize_price(
- payment.captured_amount, payment_currency
- ),
- "currency": payment_currency,
- },
**get_site_context(),
}
+ if payment:
+ payment_currency = payment.currency
+ payload.update(
+ {
+ "payment": {
+ "created": payment.created_at,
+ "modified": payment.modified_at,
+ "charge_status": payment.charge_status,
+ "total": quantize_price(payment.total, payment_currency),
+ "captured_amount": quantize_price(
+ payment.captured_amount, payment_currency
+ ),
+ "currency": payment_currency,
+ }
+ }
+ )
manager.notify(
NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
payload,
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index f7c623b8b3..ab6fe6c289 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -32,12 +32,14 @@ from ..actions import (
mark_order_as_paid_with_payment,
mark_order_as_paid_with_transaction,
order_refunded,
+ order_transaction_updated,
)
from ..models import Fulfillment, OrderLine
from ..notifications import (
send_fulfillment_confirmation_to_customer,
send_payment_confirmation,
)
+from ..utils import updates_amounts_for_order
@pytest.fixture
@@ -678,3 +680,238 @@ def test_fulfill_digital_lines_no_allocation(
assert fulfillment_lines.count() == 1
assert line.digital_content_url
assert mock_email_fulfillment.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_order_fully_paid(
+ order_fully_paid, order_updated, 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, charged_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),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ order_fully_paid.assert_called_once_with(order_with_lines)
+ order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_order_partially_paid(
+ order_fully_paid, order_updated, 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, charged_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),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_order_partially_paid_and_multiple_transactions(
+ order_fully_paid, order_updated, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item_generator(
+ order_id=order_with_lines.pk, charged_value=Decimal("10")
+ )
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, charged_value=Decimal("5")
+ )
+ 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),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_with_the_same_transaction_charged_amount(
+ order_fully_paid, order_updated, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ charged_value = Decimal("5")
+
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, charged_value=charged_value
+ )
+ 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=charged_value,
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ assert not order_updated.called
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_order_authorized(
+ order_fully_paid, order_updated, 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,
+ authorized_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),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_order_partially_authorized_and_multiple_transactions(
+ order_fully_paid, order_updated, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ transaction_item_generator(
+ order_id=order_with_lines.pk, authorized_value=Decimal("10")
+ )
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, authorized_value=Decimal("5")
+ )
+ 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),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ order_updated.assert_called_once_with(order_with_lines)
+
+
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_order_transaction_updated_with_the_same_transaction_authorized_amount(
+ order_fully_paid, order_updated, order_with_lines, transaction_item_generator
+):
+ # given
+ order_info = fetch_order_info(order_with_lines)
+ authorized_value = Decimal("5")
+
+ transaction_item = transaction_item_generator(
+ order_id=order_with_lines.pk, authorized_value=authorized_value
+ )
+ 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=authorized_value,
+ previous_charged_value=Decimal(0),
+ )
+
+ # then
+ flush_post_commit_hooks()
+ assert not order_fully_paid.called
+ assert not order_updated.called
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 8514e11531..4bd7d44095 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -37,7 +37,7 @@ from ....graphql.core.utils import from_global_id_or_error
from ....order.actions import (
cancel_order,
order_authorized,
- order_captured,
+ order_charged,
order_refunded,
)
from ....order.events import external_notification_event
@@ -326,7 +326,7 @@ def handle_authorization(notification: Dict[str, Any], gateway_config: GatewayCo
gateway_postprocess(new_transaction, payment)
if adyen_auto_capture:
order_info = fetch_order_info(payment.order)
- order_captured(
+ order_charged(
order_info,
None,
None,
@@ -440,7 +440,7 @@ def handle_capture(notification: Dict[str, Any], _gateway_config: GatewayConfig)
if new_transaction.is_success:
gateway_postprocess(new_transaction, payment)
order_info = fetch_order_info(payment.order)
- order_captured(
+ order_charged(
order_info, None, None, new_transaction.amount, payment, manager
)
diff --git a/saleor/payment/gateways/stripe/tests/test_webhooks.py b/saleor/payment/gateways/stripe/tests/test_webhooks.py
index c09a919b79..1d9455398f 100644
--- a/saleor/payment/gateways/stripe/tests/test_webhooks.py
+++ b/saleor/payment/gateways/stripe/tests/test_webhooks.py
@@ -8,7 +8,7 @@ from django.utils import timezone
from stripe.stripe_object import StripeObject
from .....checkout.complete_checkout import complete_checkout
-from .....order.actions import order_captured, order_refunded, order_voided
+from .....order.actions import order_charged, order_refunded, order_voided
from .... import ChargeStatus, TransactionKind
from ....utils import price_to_minor_unit
from ..consts import (
@@ -349,11 +349,11 @@ def test_handle_successful_payment_intent_different_checkout_channel_slug(
@pytest.mark.parametrize("called", [True, False])
-@patch("saleor.payment.gateways.stripe.webhooks.order_captured", wraps=order_captured)
+@patch("saleor.payment.gateways.stripe.webhooks.order_charged", wraps=order_charged)
@patch("saleor.payment.gateways.stripe.webhooks.update_payment_method")
def test_handle_successful_payment_intent_different_order_channel_slug(
_wrapped_update_payment_method,
- wrapped_order_captured,
+ wrapped_order_charged,
payment_stripe_for_order,
stripe_plugin,
channel_USD,
@@ -375,7 +375,7 @@ def test_handle_successful_payment_intent_different_order_channel_slug(
handle_successful_payment_intent(payment_intent, plugin.config, channel.slug)
# then
- assert wrapped_order_captured.called == called
+ assert wrapped_order_charged.called == called
@patch(
diff --git a/saleor/payment/gateways/stripe/webhooks.py b/saleor/payment/gateways/stripe/webhooks.py
index d99676fd4b..d548315850 100644
--- a/saleor/payment/gateways/stripe/webhooks.py
+++ b/saleor/payment/gateways/stripe/webhooks.py
@@ -14,7 +14,7 @@ from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
from ....core.transactions import transaction_with_commit_on_errors
from ....discount.utils import fetch_active_discounts
-from ....order.actions import order_captured, order_refunded, order_voided
+from ....order.actions import order_charged, order_refunded, order_voided
from ....order.fetch import fetch_order_info
from ....order.models import Order
from ....plugins.manager import get_plugins_manager
@@ -442,7 +442,7 @@ def handle_successful_payment_intent(
payment_intent.currency,
)
order_info = fetch_order_info(payment.order)
- order_captured(
+ order_charged(
order_info,
None,
None,
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 4eef915c41..b83f4a0ee8 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -9,6 +9,7 @@ from freezegun import freeze_time
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ...order import OrderAuthorizeStatus, OrderChargeStatus
from ...plugins.manager import get_plugins_manager
+from ...tests.utils import flush_post_commit_hooks
from .. import TransactionEventType
from ..interface import (
PaymentLineData,
@@ -498,6 +499,138 @@ def test_create_transaction_event_from_request_updates_order_charge(
assert order.search_vector
+@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,
+ 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.CHARGE_REQUEST,
+ amount_value=order.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = order.total.gross.amount
+ event_type = TransactionEventType.CHARGE_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 order.charge_status == OrderChargeStatus.FULL
+ mock_order_fully_paid.assert_called_once_with(order)
+ mock_order_updated.assert_called_once_with(order)
+
+
+@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,
+ 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.CHARGE_REQUEST,
+ amount_value=Decimal("12.00"),
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = Decimal("12.00")
+ event_type = TransactionEventType.CHARGE_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 order_with_lines.charge_status == OrderChargeStatus.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_fully_paid")
+@freeze_time("2018-05-31 12:00:01")
+def test_create_transaction_event_from_request_triggers_webhooks_when_authorized(
+ mock_order_fully_paid,
+ mock_order_updated,
+ 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.AUTHORIZATION_REQUEST,
+ amount_value=order.total.gross.amount,
+ currency="USD",
+ transaction_id=transaction.id,
+ )
+
+ event_amount = order.total.gross.amount
+ event_type = TransactionEventType.AUTHORIZATION_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 order_with_lines.authorize_status == OrderAuthorizeStatus.FULL
+ assert not mock_order_fully_paid.called
+ mock_order_updated.assert_called_once_with(order_with_lines)
+
+
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_updates_order_authorize(
transaction_item_generator, app, order_with_lines
@@ -711,7 +844,7 @@ def test_create_transaction_event_from_request_and_webhook_response_same_event(
@freeze_time("2018-05-31 12:00:01")
-def test_create_transaction_event_from_request_and_webhook_response_differnt_amout(
+def test_create_transaction_event_from_request_and_webhook_response_different_amount(
transaction_item_generator,
app,
):
@@ -1140,3 +1273,83 @@ def test_create_transaction_event_for_transaction_session_missing_reference_with
assert transaction.charged_value == Decimal("0")
assert transaction.authorize_pending_value == Decimal("0")
assert transaction.charge_pending_value == Decimal("0")
+
+
+ "response_result",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ ],
+)
+@patch("saleor.plugins.manager.PluginsManager.order_updated")
+@patch("saleor.plugins.manager.PluginsManager.order_fully_paid")
+def test_create_transaction_event_for_transaction_session_call_webhook_order_updated(
+ mock_order_fully_paid,
+ mock_order_updated,
+ response_result,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+ order_with_lines,
+):
+ # given
+ expected_amount = Decimal("15")
+ response = transaction_session_response.copy()
+ response["result"] = response_result.upper()
+ response["amount"] = expected_amount
+ transaction = transaction_item_generator(order_id=order_with_lines.pk)
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+ # when
+ create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ flush_post_commit_hooks()
+ 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_fully_paid")
+def test_create_transaction_event_for_transaction_session_call_webhook_for_fully_paid(
+ mock_order_fully_paid,
+ mock_order_updated,
+ transaction_item_generator,
+ transaction_session_response,
+ webhook_app,
+ plugins_manager,
+ order_with_lines,
+):
+ # given
+ response = transaction_session_response.copy()
+ response["result"] = TransactionEventType.CHARGE_SUCCESS.upper()
+ response["amount"] = order_with_lines.total.gross.amount
+ transaction = transaction_item_generator(order_id=order_with_lines.pk)
+ request_event = TransactionEvent.objects.create(
+ transaction=transaction, include_in_calculations=False
+ )
+
+ # when
+ create_transaction_event_for_transaction_session(
+ request_event,
+ webhook_app,
+ manager=plugins_manager,
+ discounts=[],
+ transaction_webhook_response=response,
+ )
+
+ # then
+ order_with_lines.refresh_from_db()
+ flush_post_commit_hooks()
+ mock_order_fully_paid.assert_called_once_with(order_with_lines)
+ mock_order_updated.assert_called_once_with(order_with_lines)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index bced96c855..8fb2bc3837 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -23,6 +23,7 @@ from ..core.tracing import traced_atomic_transaction
from ..discount import DiscountInfo
from ..discount.utils import fetch_active_discounts
from ..graphql.core.utils import str_to_enum
+from ..order.fetch import fetch_order_info
from ..order.models import Order
from ..order.search import update_order_search_vector
from ..order.utils import update_order_authorize_data, updates_amounts_for_order
@@ -1127,6 +1128,9 @@ def create_transaction_event_for_transaction_session(
TransactionEventType.CHARGE_SUCCESS,
]:
transaction_item = event.transaction
+ previous_authorized_value = transaction_item.authorized_value
+ previous_charged_value = transaction_item.charged_value
+
transaction_item.psp_reference = event.psp_reference
recalculate_transaction_amounts(transaction_item, save=False)
transaction_item.save(
@@ -1143,7 +1147,21 @@ def create_transaction_event_for_transaction_session(
]
)
if transaction_item.order_id:
+ # circular import
+ from ..order.actions import order_transaction_updated
+
update_order_with_transaction_details(transaction_item)
+ order = cast(Order, transaction_item.order)
+ order_info = fetch_order_info(order)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ )
elif transaction_item.checkout_id:
transaction_amounts_for_checkout_updated(
transaction_item, discounts, manager
@@ -1178,10 +1196,27 @@ def create_transaction_event_from_request_and_webhook_response(
return create_failed_transaction_event(request_event, cause=error_msg)
transaction_item = request_event.transaction
+ previous_authorized_value = transaction_item.authorized_value
+ previous_charged_value = transaction_item.charged_value
recalculate_transaction_amounts(transaction_item)
if transaction_item.order_id:
+ # circular import
+ from ..order.actions import order_transaction_updated
+
+ manager = get_plugins_manager()
+ order = cast(Order, transaction_item.order)
+ order_info = fetch_order_info(order)
update_order_with_transaction_details(transaction_item)
+ order_transaction_updated(
+ order_info=order_info,
+ transaction_item=transaction_item,
+ manager=manager,
+ user=None,
+ app=app,
+ previous_authorized_value=previous_authorized_value,
+ previous_charged_value=previous_charged_value,
+ )
elif transaction_item.checkout_id:
discounts = fetch_active_discounts()
manager = get_plugins_manager()