Skip to content

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

Add possibility to add external reference to order (#6320)

Maciej Korycinski2c218aadc9b7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3944a4a81e..dbb13a4ef3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,7 +4,7 @@ All notable, unreleased changes to this project will be documented in this file.
## [Unreleased]
-- Add metadata to shipping zones and shipping methods - by @maarcingebala #6340
+- Add possibility to provide external payment ID during the conversion draft order to order - #6320 by @korycins
- Add basic rating for `Products` - #6284 by @korycins
- Add metadata to shipping zones and shipping methods - #6340 by @maarcingebala
- Drop deprecated meta mutations - #6422 by @maarcingebala
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index f5d3eed95a..0d962b36ef 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -346,6 +346,9 @@ class OrderMarkAsPaid(BaseMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of the order to mark paid.")
+ transaction_reference = graphene.String(
+ required=False, description="The external transaction reference."
+ )
class Meta:
description = "Mark order as manually paid."
@@ -364,13 +367,13 @@ class OrderMarkAsPaid(BaseMutation):
@classmethod
def perform_mutation(cls, _root, info, **data):
order = cls.get_node_or_error(info, data.get("id"), only_type=Order)
-
+ transaction_reference = data.get("transaction_reference")
cls.clean_billing_address(order)
try_payment_action(
order, info.context.user, None, clean_mark_order_as_paid, order
)
- mark_order_as_paid(order, info.context.user)
+ mark_order_as_paid(order, info.context.user, transaction_reference)
return OrderMarkAsPaid(order=order)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 0f606d78ae..0075bb212c 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -2877,28 +2877,34 @@ def test_order_capture(
}
+MUTATION_MARK_ORDER_AS_PAID = """
+ mutation markPaid($id: ID!, $transaction: String) {
+ orderMarkAsPaid(id: $id, transactionReference: $transaction) {
+ errors {
+ field
+ message
+ }
+ orderErrors {
+ field
+ message
+ code
+ }
+ order {
+ isPaid
+ events{
+ transactionReference
+ }
+ }
+ }
+ }
+"""
+
+
def test_paid_order_mark_as_paid(
staff_api_client, permission_manage_orders, payment_txn_preauth
):
order = payment_txn_preauth.order
- query = """
- mutation markPaid($id: ID!) {
- orderMarkAsPaid(id: $id) {
- errors {
- field
- message
- }
- orderErrors {
- field
- message
- code
- }
- order {
- isPaid
- }
- }
- }
- """
+ query = MUTATION_MARK_ORDER_AS_PAID
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
response = staff_api_client.post_graphql(
@@ -2914,23 +2920,42 @@ def test_paid_order_mark_as_paid(
assert order_errors[0]["code"] == OrderErrorCode.PAYMENT_ERROR.name
+def test_order_mark_as_paid_with_external_reference(
+ staff_api_client, permission_manage_orders, order_with_lines, staff_user
+):
+ transaction_reference = "searchable-id"
+ order = order_with_lines
+ query = MUTATION_MARK_ORDER_AS_PAID
+ assert not order.is_fully_paid()
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id, "transaction": transaction_reference}
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+
+ data = content["data"]["orderMarkAsPaid"]["order"]
+ order.refresh_from_db()
+ assert data["isPaid"] is True
+ assert len(data["events"]) == 1
+ assert data["events"][0]["transactionReference"] == transaction_reference
+ assert order.is_fully_paid()
+ event_order_paid = order.events.first()
+ assert event_order_paid.type == order_events.OrderEvents.ORDER_MARKED_AS_PAID
+ assert event_order_paid.user == staff_user
+ event_reference = event_order_paid.parameters.get("transaction_reference")
+ assert event_reference == transaction_reference
+ order_payments = order.payments.filter(
+ transactions__searchable_key=transaction_reference
+ )
+ assert order_payments.count() == 1
+
+
def test_order_mark_as_paid(
staff_api_client, permission_manage_orders, order_with_lines, staff_user
):
order = order_with_lines
- query = """
- mutation markPaid($id: ID!) {
- orderMarkAsPaid(id: $id) {
- errors {
- field
- message
- }
- order {
- isPaid
- }
- }
- }
- """
+ query = MUTATION_MARK_ORDER_AS_PAID
assert not order.is_fully_paid()
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
@@ -2954,15 +2979,7 @@ def test_order_mark_as_paid_no_billing_address(
order_with_lines.billing_address = None
order_with_lines.save()
- query = """
- mutation markPaid($id: ID!) {
- orderMarkAsPaid(id: $id) {
- orderErrors {
- code
- }
- }
- }
- """
+ query = MUTATION_MARK_ORDER_AS_PAID
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
response = staff_api_client.post_graphql(
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 0108c92300..a73a739261 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -73,6 +73,9 @@ class OrderEvent(CountableDjangoObjectType):
warehouse = graphene.Field(
Warehouse, description="The warehouse were items were restocked."
)
+ transaction_reference = graphene.String(
+ description="The transaction reference of captured payment."
+ )
class Meta:
description = "History log of the order."
@@ -176,6 +179,10 @@ class OrderEvent(CountableDjangoObjectType):
warehouse = root.parameters.get("warehouse")
return warehouse_models.Warehouse.objects.filter(pk=warehouse).first()
+ @staticmethod
+ def resolve_transaction_reference(root: models.OrderEvent, _info):
+ return root.parameters.get("transaction_reference")
+
class FulfillmentLine(CountableDjangoObjectType):
order_line = graphene.Field(lambda: OrderLine)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 5843bbf39f..8de6b6d4d5 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2646,7 +2646,7 @@ type Mutation {
orderFulfill(input: OrderFulfillInput!, order: ID): OrderFulfill
orderFulfillmentCancel(id: ID!, input: FulfillmentCancelInput!): FulfillmentCancel
orderFulfillmentUpdateTracking(id: ID!, input: FulfillmentUpdateTrackingInput!): FulfillmentUpdateTracking
- orderMarkAsPaid(id: ID!): OrderMarkAsPaid
+ orderMarkAsPaid(id: ID!, transactionReference: String): OrderMarkAsPaid
orderRefund(amount: PositiveDecimal!, id: ID!): OrderRefund
orderUpdate(id: ID!, input: OrderUpdateInput!): OrderUpdate
orderUpdateShipping(order: ID!, input: OrderUpdateShippingInput): OrderUpdateShipping
@@ -2962,6 +2962,7 @@ type OrderEvent implements Node {
lines: [OrderEventOrderLineObject]
fulfilledItems: [FulfillmentLine]
warehouse: Warehouse
+ transactionReference: String
}
type OrderEventCountableConnection {
@@ -5051,6 +5052,7 @@ enum TransactionError {
}
enum TransactionKind {
+ EXTERNAL
AUTH
PENDING
ACTION_TO_CONFIRM
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 1cad9b6232..5832b5394c 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -6,7 +6,9 @@ from django.db import transaction
from ..core import analytics
from ..core.exceptions import InsufficientStock
-from ..payment import ChargeStatus, CustomPaymentChoices, PaymentError
+from ..payment import ChargeStatus, CustomPaymentChoices, PaymentError, TransactionKind
+from ..payment.models import Payment, Transaction
+from ..payment.utils import create_payment
from ..plugins.manager import get_plugins_manager
from ..warehouse.management import deallocate_stock_for_order, decrease_stock
from . import FulfillmentStatus, OrderStatus, emails, events, utils
@@ -26,7 +28,6 @@ from .utils import (
if TYPE_CHECKING:
from ..account.models import User
- from ..payment.models import Payment
from ..warehouse.models import Warehouse
from .models import Order
@@ -195,14 +196,14 @@ def cancel_fulfillment(
@transaction.atomic
-def mark_order_as_paid(order: "Order", request_user: "User"):
+def mark_order_as_paid(
+ order: "Order", request_user: "User", external_reference: Optional[str] = None
+):
"""Mark order as paid.
Allows to create a payment for an order without actually performing any
payment by the gateway.
"""
- # pylint: disable=cyclic-import
- from ..payment.utils import create_payment
payment = create_payment(
gateway=CustomPaymentChoices.MANUAL,
@@ -216,7 +217,20 @@ def mark_order_as_paid(order: "Order", request_user: "User"):
payment.captured_amount = order.total.gross.amount
payment.save(update_fields=["captured_amount", "charge_status", "modified"])
- events.order_manually_marked_as_paid_event(order=order, user=request_user)
+ Transaction.objects.create(
+ payment=payment,
+ action_required=False,
+ kind=TransactionKind.EXTERNAL,
+ token=external_reference or "",
+ is_success=True,
+ amount=order.total.gross.amount,
+ currency=order.total.gross.currency,
+ searchable_key=external_reference or "",
+ gateway_response={},
+ )
+ events.order_manually_marked_as_paid_event(
+ order=order, user=request_user, transaction_reference=external_reference
+ )
manager = get_plugins_manager()
manager.order_fully_paid(order)
manager.order_updated(order)
diff --git a/saleor/order/events.py b/saleor/order/events.py
index b588ad4f2a..7a680881da 100644
--- a/saleor/order/events.py
+++ b/saleor/order/events.py
@@ -176,11 +176,19 @@ def order_canceled_event(*, order: Order, user: UserType) -> OrderEvent:
return OrderEvent.objects.create(order=order, type=OrderEvents.CANCELED, user=user)
-def order_manually_marked_as_paid_event(*, order: Order, user: UserType) -> OrderEvent:
+def order_manually_marked_as_paid_event(
+ *, order: Order, user: UserType, transaction_reference: Optional[str] = None
+) -> OrderEvent:
if not _user_is_valid(user):
user = None
+ parameters = {} # type: ignore
+ if transaction_reference:
+ parameters = {"transaction_reference": transaction_reference}
return OrderEvent.objects.create(
- order=order, type=OrderEvents.ORDER_MARKED_AS_PAID, user=user
+ order=order,
+ type=OrderEvents.ORDER_MARKED_AS_PAID,
+ user=user,
+ parameters=parameters,
)
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index 276ff4a0e8..e94125baca 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -4,7 +4,7 @@ from unittest.mock import patch
import pytest
from prices import Money, TaxedMoney
-from ...payment import ChargeStatus, PaymentError
+from ...payment import ChargeStatus, PaymentError, TransactionKind
from ...payment.models import Payment
from ...product.models import DigitalContent
from ...product.tests.utils import create_image
@@ -131,6 +131,23 @@ def test_mark_as_paid(admin_user, draft_order):
assert payment.charge_status == ChargeStatus.FULLY_CHARGED
assert payment.captured_amount == draft_order.total.gross.amount
assert draft_order.events.last().type == (OrderEvents.ORDER_MARKED_AS_PAID)
+ transactions = payment.transactions.all()
+ assert transactions.count() == 1
+ assert transactions[0].kind == TransactionKind.EXTERNAL
+
+
+def test_mark_as_paid_with_external_reference(admin_user, draft_order):
+ external_reference = "transaction_id"
+ mark_order_as_paid(draft_order, admin_user, external_reference=external_reference)
+ payment = draft_order.payments.last()
+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED
+ assert payment.captured_amount == draft_order.total.gross.amount
+ assert draft_order.events.last().type == (OrderEvents.ORDER_MARKED_AS_PAID)
+ transactions = payment.transactions.all()
+ assert transactions.count() == 1
+ assert transactions[0].kind == TransactionKind.EXTERNAL
+ assert transactions[0].searchable_key == external_reference
+ assert transactions[0].token == external_reference
def test_mark_as_paid_no_billing_address(admin_user, draft_order):
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index faf1733352..88b0e329ec 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -57,6 +57,7 @@ class TransactionKind:
- REFUND - full or partial return of captured funds to the customer.
"""
+ EXTERNAL = "external"
AUTH = "auth"
CAPTURE = "capture"
CAPTURE_FAILED = "capture_failed"
@@ -73,6 +74,7 @@ class TransactionKind:
# Which were authorized, but needs to be confirmed manually by staff
# eg. Braintree with "submit_for_settlement" enabled
CHOICES = [
+ (EXTERNAL, "External reference"),
(AUTH, "Authorization"),
(PENDING, "Pending"),
(ACTION_TO_CONFIRM, "Action to confirm"),
diff --git a/saleor/payment/migrations/0023_auto_20201110_0834.py b/saleor/payment/migrations/0023_auto_20201110_0834.py
new file mode 100644
index 0000000000..82a8f30d64
--- /dev/null
+++ b/saleor/payment/migrations/0023_auto_20201110_0834.py
@@ -0,0 +1,32 @@
+# Generated by Django 3.1.2 on 2020-11-10 08:34
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payment", "0022_auto_20201104_1458"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="transaction",
+ name="kind",
+ field=models.CharField(
+ choices=[
+ ("external", "External reference"),
+ ("auth", "Authorization"),
+ ("pending", "Pending"),
+ ("action_to_confirm", "Action to confirm"),
+ ("refund", "Refund"),
+ ("refund_ongoing", "Refund in progress"),
+ ("capture", "Capture"),
+ ("void", "Void"),
+ ("confirm", "Confirm"),
+ ("cancel", "Cancel"),
+ ],
+ max_length=25,
+ ),
+ ),
+ ]