Skip to content

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

Fix amount precision in transaction API (#16430)

Iga Karbowiak63b7e9f095ec
diff --git a/saleor/graphql/order/bulk_mutations/order_bulk_create.py b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
index 04af6ae247..727554f466 100644
--- a/saleor/graphql/order/bulk_mutations/order_bulk_create.py
+++ b/saleor/graphql/order/bulk_mutations/order_bulk_create.py
@@ -1470,7 +1470,9 @@ class OrderBulkCreate(BaseMutation, I18nMixin):
new_transaction = TransactionCreate.create_transaction(
transaction_data, None, None, save=False
)
- money_data = TransactionCreate.get_money_data_from_input(transaction_data)
+ money_data = TransactionCreate.get_money_data_from_input(
+ transaction_data, order.currency
+ )
events: list[TransactionEvent] = []
if money_data:
amountfield_eventtype_map = {
diff --git a/saleor/graphql/payment/mutations/base.py b/saleor/graphql/payment/mutations/base.py
index c2a525bcb1..1e0ad87c8d 100644
--- a/saleor/graphql/payment/mutations/base.py
+++ b/saleor/graphql/payment/mutations/base.py
@@ -8,6 +8,7 @@ from graphql import GraphQLError
from ....checkout import models as checkout_models
from ....checkout.calculations import fetch_checkout_data
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from ....core.prices import quantize_price
from ....order import models as order_models
from ...core.enums import TransactionInitializeErrorCode
from ...core.mutations import BaseMutation
@@ -99,8 +100,9 @@ class TransactionSessionBase(BaseMutation):
source_object: Union[checkout_models.Checkout, order_models.Order],
input_amount: Optional[Decimal],
) -> Decimal:
+ currency = source_object.currency
if input_amount is not None:
- return input_amount
+ return quantize_price(input_amount, currency)
amount: Decimal = source_object.total_gross_amount
transactions = source_object.payment_transactions.all()
for transaction_item in transactions:
@@ -111,4 +113,4 @@ class TransactionSessionBase(BaseMutation):
amount -= transaction_item.authorize_pending_value
amount -= transaction_item.charge_pending_value
- return amount if amount >= Decimal(0) else Decimal(0)
+ return quantize_price(amount, currency) if amount >= Decimal(0) else Decimal(0)
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_create.py b/saleor/graphql/payment/mutations/transaction/transaction_create.py
index 45cb453ba4..6e6642e1e5 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_create.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_create.py
@@ -9,6 +9,7 @@ from django.db.models import Model
from .....checkout import models as checkout_models
from .....checkout.actions import transaction_amounts_for_checkout_updated
+from .....core.prices import quantize_price
from .....order import OrderStatus
from .....order import models as order_models
from .....order.actions import order_transaction_updated
@@ -151,17 +152,27 @@ class TransactionCreate(BaseMutation):
)
@classmethod
- def get_money_data_from_input(cls, cleaned_data: dict) -> dict[str, Decimal]:
+ def get_money_data_from_input(
+ cls, cleaned_data: dict, currency: str
+ ) -> dict[str, Decimal]:
money_data = {}
if amount_authorized := cleaned_data.pop("amount_authorized", None):
- money_data["authorized_value"] = amount_authorized["amount"]
+ money_data["authorized_value"] = quantize_price(
+ amount_authorized["amount"], currency
+ )
if amount_charged := cleaned_data.pop("amount_charged", None):
- money_data["charged_value"] = amount_charged["amount"]
+ money_data["charged_value"] = quantize_price(
+ amount_charged["amount"], currency
+ )
if amount_refunded := cleaned_data.pop("amount_refunded", None):
- money_data["refunded_value"] = amount_refunded["amount"]
+ money_data["refunded_value"] = quantize_price(
+ amount_refunded["amount"], currency
+ )
if amount_canceled := cleaned_data.pop("amount_canceled", None):
- money_data["canceled_value"] = amount_canceled["amount"]
+ money_data["canceled_value"] = quantize_price(
+ amount_canceled["amount"], currency
+ )
return money_data
@classmethod
@@ -342,7 +353,8 @@ class TransactionCreate(BaseMutation):
order_or_checkout_instance, transaction=transaction
)
transaction_data = {**transaction}
- transaction_data["currency"] = order_or_checkout_instance.currency
+ currency = order_or_checkout_instance.currency
+ transaction_data["currency"] = currency
app = get_app_promise(info.context).get()
user = info.context.user
manager = get_plugin_manager_promise(info.context).get()
@@ -359,7 +371,7 @@ class TransactionCreate(BaseMutation):
reference=transaction_event.get("psp_reference"),
message=transaction_event.get("message", ""),
)
- money_data = cls.get_money_data_from_input(transaction_data)
+ money_data = cls.get_money_data_from_input(transaction_data, currency)
new_transaction = cls.create_transaction(transaction_data, user=user, app=app)
if money_data:
create_manual_adjustment_events(
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
index 5eef6103ec..7f58cafe86 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_event_report.py
@@ -7,6 +7,7 @@ from django.utils import timezone
from .....app.models import App
from .....checkout.actions import transaction_amounts_for_checkout_updated
from .....core.exceptions import PermissionDenied
+from .....core.prices import quantize_price
from .....core.tracing import traced_atomic_transaction
from .....order import models as order_models
from .....order.actions import order_transaction_updated
@@ -216,6 +217,7 @@ class TransactionEventReport(ModelMutation):
]
)
+ amount = quantize_price(amount, transaction.currency)
app_identifier = None
if app and app.identifier:
app_identifier = app.identifier
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
index 6a1dfd89d6..aea7de2a9e 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_request_action.py
@@ -6,6 +6,7 @@ import graphene
from django.core.exceptions import ValidationError
from .....app.models import App
+from .....core.prices import quantize_price
from .....order.models import Order
from .....payment import PaymentError, TransactionAction, TransactionEventType
from .....payment.error_codes import TransactionRequestActionErrorCode
@@ -154,11 +155,17 @@ class TransactionRequestAction(BaseMutation):
else:
checkout = cast(Checkout, transaction.checkout)
channel = checkout.channel
+
cls.check_channel_permissions(info, [channel.id])
+
channel_slug = channel.slug
user = info.context.user
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
+
+ if action_value is not None:
+ action_value = quantize_price(action_value, transaction.currency)
+
action_kwargs = {
"channel_slug": channel_slug,
"user": user,
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_update.py b/saleor/graphql/payment/mutations/transaction/transaction_update.py
index 3f3b2e6b06..50d4bdfcd8 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_update.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_update.py
@@ -217,7 +217,7 @@ class TransactionUpdate(TransactionCreate):
cls.validate_transaction_input(instance, transaction)
cls.assign_app_to_transaction_data_if_missing(instance, transaction, app)
cls.cleanup_metadata_data(transaction)
- money_data = cls.get_money_data_from_input(transaction)
+ money_data = cls.get_money_data_from_input(transaction, instance.currency)
cls.update_transaction(instance, transaction, money_data, user, app)
event = None
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
index 6e12bab11a..94fe749b6a 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -808,3 +808,55 @@ def test_for_order_with_multiple_payment_gateways(
],
order,
)
+
+
[email protected]("saleor.plugins.manager.PluginsManager.payment_gateway_initialize_session")
+def test_with_payment_gateways_and_amount_with_lot_of_decimal_places(
+ mocked_initialize,
+ user_api_client,
+ order_with_lines,
+):
+ # given
+ order = order_with_lines
+ expected_app_identifier = "app.id"
+ expected_data = {"json": "data"}
+ expected_response = {"data": expected_data}
+ expected_input_data = {"input": "json"}
+ excpected_amount = Decimal("28.1256977854")
+ mocked_initialize.return_value = [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_response
+ )
+ ]
+ variables = {
+ "id": to_global_id_or_none(order),
+ "amount": excpected_amount,
+ "paymentGateways": [
+ {"id": expected_app_identifier, "data": expected_input_data}
+ ],
+ }
+
+ # when
+ response = user_api_client.post_graphql(PAYMENT_GATEWAY_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["paymentGatewayInitialize"]["errors"]
+ assert content["data"]
+ assert len(content["data"]["paymentGatewayInitialize"]["gatewayConfigs"]) == 1
+ gateway_config = content["data"]["paymentGatewayInitialize"]["gatewayConfigs"][0]
+ assert gateway_config == {
+ "id": expected_app_identifier,
+ "data": expected_data,
+ "errors": [],
+ }
+
+ mocked_initialize.assert_called_once_with(
+ round(excpected_amount, 2),
+ [
+ PaymentGatewayData(
+ app_identifier=expected_app_identifier, data=expected_input_data
+ )
+ ],
+ order,
+ )
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
index 47eeb332cb..dad77b8f2b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py
@@ -2112,3 +2112,70 @@ def test_transaction_create_null_available_actions(
# then
assert checkout_with_items.payment_transactions.first().available_actions == []
+
+
+ ("amount_field_name", "transaction_field_name", "amount_db_field"),
+ [
+ ("amountAuthorized", "authorizedAmount", "authorized_value"),
+ ("amountCharged", "chargedAmount", "charged_value"),
+ ("amountCanceled", "canceledAmount", "canceled_value"),
+ ("amountRefunded", "refundedAmount", "refunded_value"),
+ ],
+)
+def test_transaction_create_amount_with_lot_of_decimal_places(
+ amount_field_name,
+ transaction_field_name,
+ amount_db_field,
+ order_with_lines,
+ permission_manage_payments,
+ app_api_client,
+):
+ # given
+ psp_reference = "PSP reference - 123"
+ available_actions = [
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.CANCEL.name,
+ TransactionActionEnum.CHARGE.name,
+ ]
+ value = Decimal("9.88789999")
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+
+ variables = {
+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),
+ "transaction": {
+ "name": "Credit Card",
+ "pspReference": psp_reference,
+ "availableActions": available_actions,
+ amount_field_name: {
+ "amount": value,
+ "currency": "USD",
+ },
+ "externalUrl": external_url,
+ },
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ available_actions = set(available_actions)
+
+ transaction = order_with_lines.payment_transactions.first()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionCreate"]["transaction"]
+ assert set(data["actions"]) == available_actions
+ assert data["pspReference"] == psp_reference
+ assert str(data[transaction_field_name]["amount"]) == str(round(value, 2))
+ assert data["externalUrl"] == external_url
+ assert data["createdBy"]["id"] == to_global_id_or_none(app_api_client.app)
+
+ assert available_actions == set(map(str.upper, transaction.available_actions))
+ assert psp_reference == transaction.psp_reference
+ assert round(value, 2) == getattr(transaction, amount_db_field)
+ assert transaction.app_identifier == app_api_client.app.identifier
+ assert transaction.app == app_api_client.app
+ assert transaction.user is None
+ assert transaction.external_url == external_url
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 a5b37c4378..facf6a6476 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_event_report.py
@@ -377,6 +377,85 @@ def test_transaction_event_report_by_another_user(
assert transaction.available_actions == [TransactionActionEnum.CANCEL.value]
+def test_transaction_event_report_amount_with_lot_of_decimal_places(
+ transaction_item_generator,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ transaction = transaction_item_generator(
+ app=app_api_client.app, authorized_value=Decimal("10")
+ )
+ event_time = timezone.now()
+ external_url = f"http://{TEST_SERVER_DOMAIN}/external-url"
+ message = "Sucesfull charge"
+ psp_reference = "111-abc"
+ amount = Decimal("10.454657657")
+ transaction_id = graphene.Node.to_global_id("TransactionItem", transaction.token)
+ variables = {
+ "id": transaction_id,
+ "type": TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ "amount": amount,
+ "pspReference": psp_reference,
+ "time": event_time.isoformat(),
+ "externalUrl": external_url,
+ "message": message,
+ "availableActions": [TransactionActionEnum.REFUND.name],
+ }
+ query = (
+ MUTATION_DATA_FRAGMENT
+ + """
+ mutation TransactionEventReport(
+ $id: ID
+ $type: TransactionEventTypeEnum!
+ $amount: PositiveDecimal!
+ $pspReference: String!
+ $time: DateTime
+ $externalUrl: String
+ $message: String
+ $availableActions: [TransactionActionEnum!]!
+ ) {
+ transactionEventReport(
+ id: $id
+ type: $type
+ amount: $amount
+ pspReference: $pspReference
+ time: $time
+ externalUrl: $externalUrl
+ message: $message
+ availableActions: $availableActions
+ ) {
+ ...TransactionEventData
+ }
+ }
+ """
+ )
+ # when
+ response = app_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ response = get_graphql_content(response)
+ transaction_report_data = response["data"]["transactionEventReport"]
+ assert transaction_report_data["alreadyProcessed"] is False
+
+ event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_SUCCESS
+ ).first()
+ assert event
+ assert event.psp_reference == psp_reference
+ assert event.type == TransactionEventTypeEnum.CHARGE_SUCCESS.value
+ assert event.amount_value == round(amount, 2)
+ assert event.currency == transaction.currency
+ assert event.created_at == event_time
+ assert event.external_url == external_url
+ assert event.transaction == transaction
+ assert event.app_identifier == app_api_client.app.identifier
+ assert event.app == app_api_client.app
+ assert event.user is None
+
+
def test_transaction_event_report_no_permission(
transaction_item_created_by_app,
app_api_client,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
index 0efb71c131..a4b3e03400 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_initialize.py
@@ -328,6 +328,71 @@ def test_for_checkout_with_idempotency_key(
assert transaction.events.first().idempotency_key == idempotency_key
[email protected]("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
+def test_for_checkout_amount_with_lot_of_decimal_places(
+ mocked_initialize,
+ user_api_client,
+ checkout_with_prices,
+ webhook_app,
+ transaction_session_response,
+):
+ # given
+ checkout = checkout_with_prices
+ expected_app_identifier = "webhook.app.identifier"
+ webhook_app.identifier = expected_app_identifier
+ webhook_app.save()
+
+ expected_amount = Decimal("9.8888888889")
+ expected_psp_reference = "ppp-123"
+ expected_response = transaction_session_response.copy()
+ expected_response["result"] = "CHARGE_SUCCESS"
+ expected_response["pspReference"] = expected_psp_reference
+ expected_response["amount"] = round(expected_amount, 2)
+ mocked_initialize.return_value = TransactionSessionResult(
+ app_identifier=expected_app_identifier, response=expected_response
+ )
+
+ variables = {
+ "action": None,
+ "amount": expected_amount,
+ "id": to_global_id_or_none(checkout),
+ "paymentGateway": {"id": expected_app_identifier, "data": None},
+ }
+
+ # when
+ response = user_api_client.post_graphql(TRANSACTION_INITIALIZE, variables)
+
+ # then
+ content = get_graphql_content(response)
+ transaction_item = checkout.payment_transactions.last()
+ mocked_initialize.assert_called_once_with(
+ TransactionSessionData(
+ transaction=transaction_item,
+ source_object=checkout,
+ payment_gateway_data=mock.ANY,
+ action=TransactionProcessActionData(
+ action_type=TransactionFlowStrategy.CHARGE,
+ currency=checkout.currency,
+ amount=round(expected_amount, 2),
+ ),
+ idempotency_key=mock.ANY,
+ customer_ip_address=mock.ANY,
+ )
+ )
+ checkout.refresh_from_db()
+ _assert_fields(
+ content=content,
+ source_object=checkout,
+ expected_amount=round(expected_amount, 2),
+ expected_psp_reference=expected_psp_reference,
+ response_event_type=TransactionEventType.CHARGE_SUCCESS,
+ app_identifier=webhook_app.identifier,
+ mocked_initialize=mocked_initialize,
+ charged_value=round(expected_amount, 2),
+ returned_data=expected_response["data"],
+ )
+
+
@mock.patch("saleor.plugins.manager.PluginsManager.transaction_initialize_session")
def test_for_checkout_with_multiple_calls_and_idempotency_key(
mocked_initialize,
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
index 9939fc4ee9..2cb647b38b 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_request_action.py
@@ -172,6 +172,73 @@ def test_transaction_request_action_missing_event(
assert mocked_is_active.called
+@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
+@patch("saleor.plugins.manager.PluginsManager.transaction_charge_requested")
+def test_transaction_request_action_amount_with_lot_of_decimal_places(
+ mocked_payment_action_request,
+ mocked_is_active,
+ order_with_lines,
+ app_api_client,
+ permission_manage_payments,
+):
+ # given
+ mocked_is_active.side_effect = [True, False]
+
+ transaction = TransactionItem.objects.create(
+ name="Credit card",
+ psp_reference="PSP ref",
+ available_actions=[],
+ currency="USD",
+ order_id=order_with_lines.pk,
+ authorized_value=Decimal("10"),
+ )
+
+ charge_amount = Decimal("9.12345678")
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "action_type": TransactionActionEnum.CHARGE.name,
+ "amount": charge_amount,
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_REQUEST_ACTION,
+ variables,
+ permissions=[permission_manage_payments],
+ )
+
+ # then
+ get_graphql_content(response)
+
+ request_event = TransactionEvent.objects.filter(
+ type=TransactionEventType.CHARGE_REQUEST
+ ).first()
+
+ assert mocked_is_active.called
+ assert request_event
+ mocked_payment_action_request.assert_called_once_with(
+ TransactionActionData(
+ transaction=transaction,
+ action_type=TransactionAction.CHARGE,
+ action_value=round(charge_amount, 2),
+ event=request_event,
+ transaction_app_owner=None,
+ ),
+ order_with_lines.channel.slug,
+ )
+
+ event = order_with_lines.events.first()
+ assert event.type == OrderEvents.TRANSACTION_CHARGE_REQUESTED
+ assert Decimal(event.parameters["amount"]) == round(charge_amount, 2)
+ assert event.parameters["reference"] == transaction.psp_reference
+
+ assert TransactionEvent.objects.get(
+ transaction=transaction,
+ type=TransactionEventType.CHARGE_REQUEST,
+ amount_value=round(charge_amount, 2),
+ )
+
+
@pytest.fixture
def transaction_request_webhook(permission_manage_payments):
app = App.objects.create(
diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
index 006a1d9621..ed9ebfd438 100644
--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py
+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py
@@ -3073,3 +3073,56 @@ def test_transaction_update_for_checkout_updates_last_transaction_modified_at(
assert checkout_with_items.last_transaction_modified_at != previous_modified_at
assert checkout_with_items.last_transaction_modified_at == transaction.modified_at
+
+
+ ("field_name", "response_field", "db_field_name"),
+ [
+ ("amountAuthorized", "authorizedAmount", "authorized_value"),
+ ("amountCharged", "chargedAmount", "charged_value"),
+ ("amountCanceled", "canceledAmount", "canceled_value"),
+ ("amountRefunded", "refundedAmount", "refunded_value"),
+ ],
+)
+def test_transaction_update_amounts_with_lot_of_decimal_places(
+ field_name,
+ response_field,
+ db_field_name,
+ permission_manage_payments,
+ app_api_client,
+ transaction_item_generator,
+ order,
+ app,
+):
+ # given
+ current_authorized_value = Decimal("1")
+ current_charged_value = Decimal("2")
+ current_refunded_value = Decimal("3")
+ current_canceled_value = Decimal("4")
+
+ transaction = transaction_item_generator(
+ order_id=order.pk,
+ app=app,
+ authorized_value=current_authorized_value,
+ charged_value=current_charged_value,
+ canceled_value=current_canceled_value,
+ refunded_value=current_refunded_value,
+ )
+ value = Decimal("9.88888888889")
+
+ variables = {
+ "id": graphene.Node.to_global_id("TransactionItem", transaction.token),
+ "transaction": {field_name: {"amount": value, "currency": "USD"}},
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]
+ )
+
+ # then
+ transaction.refresh_from_db()
+ content = get_graphql_content(response)
+ data = content["data"]["transactionUpdate"]["transaction"]
+ assert str(data[response_field]["amount"]) == str(round(value, 2))
+ assert getattr(transaction, db_field_name) == round(value, 2)