Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add new fields to Order type to show authorize/charge statuses (#9795)
Maciej Korycinski094b1ec0f610
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a92e94d45a..fef390a0c7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,15 @@ All notable, unreleased changes to this project will be documented in this file.- Fix invalid `ADDED_PRODUCTS` event parameter for `OrderLinesCreate` mutation - #9653 by @IKarbowiak- Fix sorting by publication date with pagination - #9741 by @IKarbowiak- Fix max_length for voucher_code in Checkout model - #9791 by @SzymJ+- Add new fields to `Order` type to show authorize/charge status #9795+ - Add new fields to Order type:+ - `totalAuthorized`+ - `totalCharged`+ - `authorizeStatus`+ - `chargeStatus`+ - Add filters to `Order`:+ - `authorizeStatus`+ - `chargeStatus`- Fix sorting by publication date with pagination - #9741 by IKarbowiak- Migrate order discount id from int to UUID - #9729 by @IKarbowiak- Changed the order discount `id` from `int` to `UUID`, the old ids still can be useddiff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex ffbf9d7770..4ee0ce6921 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -44,6 +44,7 @@ from ..order.fetch import OrderInfo, OrderLineInfofrom ..order.models import Order, OrderLinefrom ..order.notifications import send_order_confirmationfrom ..order.search import prepare_order_search_document_value+from ..order.utils import update_order_authorize_data, update_order_charge_datafrom ..payment import PaymentError, TransactionKind, gatewayfrom ..payment.models import Payment, Transactionfrom ..payment.utils import fetch_customer_id, store_customer_id@@ -536,7 +537,8 @@ def _create_order(order.metadata = checkout.metadataorder.redirect_url = checkout.redirect_urlorder.private_metadata = checkout.private_metadata- order.update_total_paid()+ update_order_charge_data(order, with_save=False)+ update_order_authorize_data(order, with_save=False)order.search_document = prepare_order_search_document_value(order)order.save()@@ -1062,6 +1064,8 @@ def _create_order_from_checkout(# paymentscheckout_info.checkout.payments.update(order=order, checkout_id=None)checkout_info.checkout.payment_transactions.update(order=order, checkout_id=None)+ update_order_charge_data(order, with_save=False)+ update_order_authorize_data(order, with_save=False)# order searchorder.search_document = prepare_order_search_document_value(order)diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.pyindex d77c1d3fee..c526603cb0 100644--- a/saleor/checkout/tests/test_order_from_checkout.py+++ b/saleor/checkout/tests/test_order_from_checkout.py@@ -1,3 +1,4 @@+from decimal import Decimalfrom unittest import mockimport pytest@@ -478,3 +479,77 @@ def test_create_order_use_translations(assert order_line.translated_product_name == translated_product_nameassert order_line.translated_variant_name == translated_variant_name+++def test_create_order_from_checkout_updates_total_authorized_amount(+ checkout_with_item, address, customer_user, shipping_method, app+):+ # given+ checkout_with_item.shipping_address = address+ checkout_with_item.billing_address = address+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.redirect_url = "https://www.example.com"+ checkout_with_item.save()++ authorized_value = Decimal(10)+ checkout_with_item.payment_transactions.create(+ authorized_value=authorized_value,+ currency=checkout_with_item.currency,+ )+ manager = get_plugins_manager()++ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, [], manager)++ # when+ order = create_order_from_checkout(+ checkout_info=checkout_info,+ checkout_lines=checkout_lines,+ discounts=[],+ manager=manager,+ user=AnonymousUser(),+ app=app,+ tracking_code="tracking_code",+ )++ # then+ assert order.total_authorized_amount == authorized_value+++def test_create_order_from_checkout_updates_total_charged_amount(+ checkout_with_item, address, customer_user, shipping_method, app+):+ # given+ checkout_with_item.shipping_address = address+ checkout_with_item.billing_address = address+ checkout_with_item.shipping_method = shipping_method+ checkout_with_item.redirect_url = "https://www.example.com"+ checkout_with_item.save()++ charged_value = Decimal(10)+ checkout_with_item.payment_transactions.create(+ charged_value=charged_value,+ currency=checkout_with_item.currency,+ )+ checkout_with_item.payment_transactions.create(+ authorized_value=Decimal(2),+ currency=checkout_with_item.currency,+ )+ manager = get_plugins_manager()++ checkout_lines, unavailable_variant_pks = fetch_checkout_lines(checkout_with_item)+ checkout_info = fetch_checkout_info(checkout_with_item, checkout_lines, [], manager)++ # when+ order = create_order_from_checkout(+ checkout_info=checkout_info,+ checkout_lines=checkout_lines,+ discounts=[],+ manager=manager,+ user=AnonymousUser(),+ app=app,+ tracking_code="tracking_code",+ )++ # then+ assert order.total_charged_amount == charged_valuediff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.pyindex 718bd06958..659c647218 100644--- a/saleor/graphql/checkout/tests/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py@@ -272,6 +272,8 @@ def test_checkout_complete(assert order.total.gross == total.grossassert order.metadata == checkout.metadataassert order.private_metadata == checkout.private_metadata+ assert order.total_charged_amount == payment.total+ assert order.total_authorized == zero_money(order.currency)order_line = order.lines.first()assert checkout_line_quantity == order_line.quantitydiff --git a/saleor/graphql/order/enums.py b/saleor/graphql/order/enums.pyindex 1ea168c671..e12c53fbb5 100644--- a/saleor/graphql/order/enums.py+++ b/saleor/graphql/order/enums.py@@ -3,6 +3,8 @@ import graphenefrom ...graphql.core.enums import to_enumfrom ...order import (FulfillmentStatus,+ OrderAuthorizeStatus,+ OrderChargeStatus,OrderEvents,OrderEventsEmails,OrderOrigin,@@ -14,6 +16,12 @@ OrderEventsEnum = to_enum(OrderEvents)OrderEventsEmailsEnum = to_enum(OrderEventsEmails)OrderOriginEnum = to_enum(OrderOrigin)OrderStatusEnum = to_enum(OrderStatus, type_name="OrderStatus")+OrderAuthorizeStatusEnum = to_enum(+ OrderAuthorizeStatus, description=OrderAuthorizeStatus.__doc__+)+OrderChargeStatusEnum = to_enum(+ OrderChargeStatus, description=OrderChargeStatus.__doc__+)class OrderStatusFilter(graphene.Enum):diff --git a/saleor/graphql/order/filters.py b/saleor/graphql/order/filters.pyindex d4a3881d87..421c227542 100644--- a/saleor/graphql/order/filters.py+++ b/saleor/graphql/order/filters.py@@ -20,7 +20,7 @@ from ..core.utils import from_global_id_or_errorfrom ..payment.enums import PaymentChargeStatusEnumfrom ..utils import resolve_global_ids_to_primary_keysfrom ..utils.filters import filter_range_field-from .enums import OrderStatusFilter+from .enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnum, OrderStatusFilterdef filter_payment_status(qs, _, value):@@ -29,6 +29,18 @@ def filter_payment_status(qs, _, value):return qs+def filter_authorize_status(qs, _, value):+ if value:+ qs = qs.filter(authorize_status__in=value)+ return qs+++def filter_charge_status(qs, _, value):+ if value:+ qs = qs.filter(charge_status__in=value)+ return qs++def get_payment_id_from_query(value):try:return from_global_id_or_error(value, only_type="Payment")[1]@@ -157,6 +169,12 @@ class OrderFilter(DraftOrderFilter):payment_status = ListObjectTypeFilter(input_class=PaymentChargeStatusEnum, method=filter_payment_status)+ authorize_status = ListObjectTypeFilter(+ input_class=OrderAuthorizeStatusEnum, method=filter_authorize_status+ )+ charge_status = ListObjectTypeFilter(+ input_class=OrderChargeStatusEnum, method=filter_charge_status+ )status = ListObjectTypeFilter(input_class=OrderStatusFilter, method=filter_status)customer = django_filters.CharFilter(method=filter_customer)created = ObjectTypeFilter(input_class=DateRangeInput, method=filter_created_range)diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 3d35c18d56..07acd798f9 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -35,6 +35,7 @@ from ....order.search import (prepare_order_search_document_value,update_order_search_document,)+from ....order.utils import update_order_authorize_data, update_order_charge_datafrom ....payment import ChargeStatus, PaymentError, TransactionAction, TransactionStatusfrom ....payment.interface import TransactionActionDatafrom ....payment.models import Payment, TransactionEvent, TransactionItem@@ -52,6 +53,7 @@ from ...tests.utils import (get_graphql_content,get_graphql_content_from_response,)+from ..enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnumfrom ..mutations.order_cancel import clean_order_cancelfrom ..mutations.order_capture import clean_order_capturefrom ..mutations.order_refund import clean_refund_payment@@ -372,6 +374,8 @@ query OrdersQuery {createdAt}}+ authorizeStatus+ chargeStatussubtotal {net {amount@@ -574,6 +578,106 @@ def test_order_query(assert order_data["deliveryMethod"]["id"] == order_data["shippingMethod"]["id"]+ "total_authorized, total_charged, expected_status",+ [+ (Decimal("98.40"), Decimal("0"), OrderAuthorizeStatusEnum.FULL.name),+ (Decimal("0"), Decimal("98.40"), OrderAuthorizeStatusEnum.FULL.name),+ (Decimal("10"), Decimal("88.40"), OrderAuthorizeStatusEnum.FULL.name),+ (Decimal("0"), Decimal("0"), OrderAuthorizeStatusEnum.NONE.name),+ (Decimal("11"), Decimal("0"), OrderAuthorizeStatusEnum.PARTIAL.name),+ (Decimal("0"), Decimal("50.00"), OrderAuthorizeStatusEnum.PARTIAL.name),+ (Decimal("10"), Decimal("40.40"), OrderAuthorizeStatusEnum.PARTIAL.name),+ ],+)+def test_order_query_authorize_status(+ total_authorized,+ total_charged,+ expected_status,+ staff_api_client,+ permission_manage_orders,+ permission_manage_shipping,+ fulfilled_order,+):+ # given+ assert fulfilled_order.total.gross.amount == Decimal("98.40")+ fulfilled_order.total_authorized_amount = total_authorized+ fulfilled_order.total_charged_amount = total_charged+ fulfilled_order.save()++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.user.user_permissions.add(permission_manage_shipping)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ assert order_data["authorizeStatus"] == expected_status+++ "total_authorized, total_charged, expected_status",+ [+ (Decimal("10.40"), Decimal("0"), OrderChargeStatusEnum.NONE.name),+ (Decimal("98.40"), Decimal("0"), OrderChargeStatusEnum.NONE.name),+ (Decimal("0"), Decimal("0"), OrderChargeStatusEnum.NONE.name),+ (Decimal("0"), Decimal("11.00"), OrderChargeStatusEnum.PARTIAL.name),+ (Decimal("88.40"), Decimal("10.00"), OrderChargeStatusEnum.PARTIAL.name),+ (Decimal("0"), Decimal("98.40"), OrderChargeStatusEnum.FULL.name),+ ],+)+def test_order_query_charge_status(+ total_authorized,+ total_charged,+ expected_status,+ staff_api_client,+ permission_manage_orders,+ permission_manage_shipping,+ fulfilled_order,+):+ # given+ assert fulfilled_order.total.gross.amount == Decimal("98.40")+ fulfilled_order.total_authorized_amount = total_authorized+ fulfilled_order.total_charged_amount = total_charged+ fulfilled_order.save()++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.user.user_permissions.add(permission_manage_shipping)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ assert order_data["chargeStatus"] == expected_status+++def test_order_query_payment_status_with_total_fulfillment_refund_equal_to_order_total(+ staff_api_client,+ permission_manage_orders,+ permission_manage_shipping,+ fulfilled_order,+):+ # given+ fulfilled_order.fulfillments.create(+ tracking_number="123", total_refund_amount=fulfilled_order.total.gross.amount+ )++ staff_api_client.user.user_permissions.add(permission_manage_orders)+ staff_api_client.user.user_permissions.add(permission_manage_shipping)++ # when+ response = staff_api_client.post_graphql(ORDERS_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ assert order_data["paymentStatus"] == PaymentChargeStatusEnum.FULLY_REFUNDED.name++def test_order_query_with_transactions_details(staff_api_client,permission_manage_orders,@@ -626,7 +730,8 @@ def test_order_query_with_transactions_details(),])-+ update_order_authorize_data(order)+ update_order_charge_data(order)event_status = TransactionStatus.FAILUREevent_reference = "PSP-ref"event_name = "Failed authorization"@@ -5834,7 +5939,7 @@ def test_order_capture(@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")-def test_order_capture_with_transaction_action_request(+def test_order_charge_with_transaction_action_request(mocked_transaction_action_request,mocked_is_active,staff_api_client,@@ -5846,16 +5951,16 @@ def test_order_capture_with_transaction_action_request(status="Authorized",type="Credit card",reference="PSP ref",- available_actions=["capture", "void"],+ available_actions=["charge", "void"],currency="USD",order_id=order.pk,authorized_value=Decimal("10"),)- capture_value = Decimal(5.0)+ charge_value = Decimal(5.0)mocked_is_active.return_value = Trueorder_id = to_global_id_or_none(order)- variables = {"id": order_id, "amount": capture_value}+ variables = {"id": order_id, "amount": charge_value}# whenresponse = staff_api_client.post_graphql(@@ -5872,14 +5977,14 @@ def test_order_capture_with_transaction_action_request(TransactionActionData(transaction=transaction,action_type=TransactionAction.CHARGE,- action_value=capture_value,+ action_value=charge_value,),channel_slug=order.channel.slug,)event = order.events.first()assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED- assert Decimal(event.parameters["amount"]) == capture_value+ assert Decimal(event.parameters["amount"]) == charge_valueassert event.parameters["reference"] == transaction.reference@@ -8894,6 +8999,166 @@ def test_draft_orders_query_with_filter_search_by_number_with_hash(assert content["data"]["draftOrders"]["totalCount"] == 1+ "transaction_data, statuses, expected_count",+ [+ (+ {"authorized_value": Decimal("10")},+ [OrderAuthorizeStatusEnum.PARTIAL.name],+ 1,+ ),+ (+ {"authorized_value": Decimal("00")},+ [OrderAuthorizeStatusEnum.PARTIAL.name],+ 0,+ ),+ (+ {"authorized_value": Decimal("100")},+ [OrderAuthorizeStatusEnum.FULL.name],+ 2,+ ),+ (+ {"authorized_value": Decimal("10")},+ [OrderAuthorizeStatusEnum.FULL.name, OrderAuthorizeStatusEnum.PARTIAL.name],+ 2,+ ),+ (+ {"authorized_value": Decimal("0")},+ [OrderAuthorizeStatusEnum.FULL.name, OrderAuthorizeStatusEnum.NONE.name],+ 2,+ ),+ (+ {"authorized_value": Decimal("10"), "charged_value": Decimal("90")},+ [OrderAuthorizeStatusEnum.FULL.name],+ 2,+ ),+ ],+)+def test_orders_query_with_filter_authorize_status(+ transaction_data,+ statuses,+ expected_count,+ orders_query_with_filter,+ order_with_lines,+ order,+ staff_api_client,+ permission_manage_orders,+ customer_user,+ channel_USD,+):+ # given+ address = customer_user.default_billing_address.get_copy()+ order = Order.objects.create(+ billing_address=address,+ channel=channel_USD,+ currency=channel_USD.currency_code,+ shipping_address=address,+ user_email=customer_user.email,+ user=customer_user,+ origin=OrderOrigin.CHECKOUT,+ )+ order.payment_transactions.create(+ currency=order.currency, authorized_value=Decimal("10")+ )+ update_order_charge_data(order)+ update_order_authorize_data(order)++ order_with_lines.payment_transactions.create(+ currency=order.currency, **transaction_data+ )+ update_order_charge_data(order_with_lines)+ update_order_authorize_data(order_with_lines)++ variables = {"filter": {"authorizeStatus": statuses}}+ staff_api_client.user.user_permissions.add(permission_manage_orders)++ # when+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["orders"]["totalCount"] == expected_count+++ "transaction_data, statuses, expected_count",+ [+ (+ {"charged_value": Decimal("10")},+ [OrderChargeStatusEnum.PARTIAL.name],+ 1,+ ),+ (+ {"charged_value": Decimal("00")},+ [OrderChargeStatusEnum.PARTIAL.name],+ 0,+ ),+ (+ {"charged_value": Decimal("98.40")},+ [OrderChargeStatusEnum.FULL.name],+ 1,+ ),+ (+ {"charged_value": Decimal("10")},+ [OrderChargeStatusEnum.FULL.name, OrderChargeStatusEnum.PARTIAL.name],+ 1,+ ),+ (+ {"charged_value": Decimal("0")},+ [OrderChargeStatusEnum.FULL.name, OrderChargeStatusEnum.NONE.name],+ 1,+ ),+ (+ {"charged_value": Decimal("98.40")},+ [OrderChargeStatusEnum.FULL.name, OrderChargeStatusEnum.OVERCHARGED.name],+ 2,+ ),+ ],+)+def test_orders_query_with_filter_charge_status(+ transaction_data,+ statuses,+ expected_count,+ orders_query_with_filter,+ order_with_lines,+ order,+ staff_api_client,+ permission_manage_orders,+ customer_user,+ channel_USD,+):+ # given+ address = customer_user.default_billing_address.get_copy()+ order = Order.objects.create(+ billing_address=address,+ channel=channel_USD,+ currency=channel_USD.currency_code,+ shipping_address=address,+ user_email=customer_user.email,+ user=customer_user,+ origin=OrderOrigin.CHECKOUT,+ )+ order.payment_transactions.create(+ currency=order.currency, charged_value=Decimal("10")+ )+ update_order_charge_data(order)++ order_with_lines.payment_transactions.create(+ currency=order.currency, **transaction_data+ )+ update_order_charge_data(order_with_lines)++ variables = {"filter": {"chargeStatus": statuses}}+ staff_api_client.user.user_permissions.add(permission_manage_orders)++ # when+ response = staff_api_client.post_graphql(orders_query_with_filter, variables)++ # then+ content = get_graphql_content(response)+ assert content["data"]["orders"]["totalCount"] == expected_count++QUERY_GET_VARIANTS_FROM_ORDER = """{me{diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.pyindex 18fbb6f53b..d40ae1ce53 100644--- a/saleor/graphql/order/types.py+++ b/saleor/graphql/order/types.py@@ -118,6 +118,8 @@ from .dataloaders import ()from .enums import (FulfillmentStatusEnum,+ OrderAuthorizeStatusEnum,+ OrderChargeStatusEnum,OrderEventsEmailsEnum,OrderEventsEnum,OrderOriginEnum,@@ -149,22 +151,14 @@ def get_order_discount_event(discount_obj: dict):)-def get_payment_status_for_order(order, transactions):+def get_payment_status_for_order(order):status = ChargeStatus.NOT_CHARGED- charged_money = prices.Money(Decimal(0), order.currency)- refunded_money = prices.Money(Decimal(0), order.currency)- for transaction in transactions:- charged_money += transaction.amount_charged- refunded_money += transaction.amount_refunded+ charged_money = order.total_chargedif charged_money >= order.total.gross:status = ChargeStatus.FULLY_CHARGEDelif charged_money and charged_money < order.total.gross:status = ChargeStatus.PARTIALLY_CHARGED- if refunded_money >= order.total.gross:- status = ChargeStatus.FULLY_REFUNDED- elif refunded_money and refunded_money < order.total.gross:- status = ChargeStatus.PARTIALLY_REFUNDEDreturn status@@ -809,6 +803,16 @@ class Order(ModelObjectType):payment_status_display = graphene.String(description="User-friendly payment status.", required=True)+ authorize_status = OrderAuthorizeStatusEnum(+ description=(+ "The authorize status of the order." + ADDED_IN_34 + PREVIEW_FEATURE+ ),+ required=True,+ )+ charge_status = OrderChargeStatusEnum(+ description=("The charge status of the order." + ADDED_IN_34 + PREVIEW_FEATURE),+ required=True,+ )transactions = NonNullList(TransactionItem,description=(@@ -1145,7 +1149,7 @@ class Order(ModelObjectType):for transaction in transactions:charged_money += transaction.amount_chargedreturn quantize_price(charged_money, root.currency)- return root.total_paid+ return root.total_chargedreturn (TransactionItemsByOrderIDLoader(info.context)@@ -1218,9 +1222,20 @@ class Order(ModelObjectType):@traced_resolverdef resolve_payment_status(root: models.Order, info):def _resolve_payment_status(data):- transactions, payments = data+ transactions, payments, fulfillments = data++ total_fulfillment_refund = sum(+ [+ fulfillment.total_refund_amount+ for fulfillment in fulfillments+ if fulfillment.total_refund_amount+ ]+ )+ if total_fulfillment_refund == root.total.gross.amount:+ return ChargeStatus.FULLY_REFUNDED+if transactions:- return get_payment_status_for_order(root, transactions)+ return get_payment_status_for_order(root)last_payment = get_last_payment(payments)if not last_payment:return ChargeStatus.NOT_CHARGED@@ -1228,14 +1243,41 @@ class Order(ModelObjectType):transactions = TransactionItemsByOrderIDLoader(info.context).load(root.id)payments = PaymentsByOrderIdLoader(info.context).load(root.id)- return Promise.all([transactions, payments]).then(_resolve_payment_status)+ fulfillments = FulfillmentsByOrderIdLoader(info.context).load(root.id)+ return Promise.all([transactions, payments, fulfillments]).then(+ _resolve_payment_status+ )++ @staticmethod+ def resolve_authorize_status(root: models.Order, info):+ total_covered = quantize_price(+ root.total_authorized_amount + root.total_charged_amount, root.currency+ )+ total_gross = quantize_price(root.total_gross_amount, root.currency)+ if total_covered == 0:+ return OrderAuthorizeStatusEnum.NONE+ if total_covered >= total_gross:+ return OrderAuthorizeStatusEnum.FULL+ return OrderAuthorizeStatusEnum.PARTIAL++ @staticmethod+ def resolve_charge_status(root: models.Order, info):+ total_charged = quantize_price(root.total_charged_amount, root.currency)+ total_gross = quantize_price(root.total_gross_amount, root.currency)+ if total_charged <= 0:+ return OrderChargeStatusEnum.NONE+ if total_charged < total_gross:+ return OrderChargeStatusEnum.PARTIAL+ if total_charged == total_gross:+ return OrderChargeStatusEnum.FULL+ return OrderChargeStatusEnum.OVERCHARGED@staticmethoddef resolve_payment_status_display(root: models.Order, info):def _resolve_payment_status(data):transactions, payments = dataif transactions:- status = get_payment_status_for_order(root, transactions)+ status = get_payment_status_for_order(root)return dict(ChargeStatus.CHOICES).get(status)last_payment = get_last_payment(payments)if not last_payment:diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.pyindex f12b28ca20..0a27118bb8 100644--- a/saleor/graphql/payment/mutations.py+++ b/saleor/graphql/payment/mutations.py@@ -1,8 +1,10 @@+import uuidfrom decimal import Decimalfrom typing import List, Optional, Unionimport graphenefrom django.core.exceptions import ValidationError+from django.db.models import Ffrom ...channel.models import Channelfrom ...checkout import models as checkout_models@@ -16,6 +18,7 @@ from ...core.utils import get_client_ipfrom ...core.utils.url import validate_storefront_urlfrom ...order import models as order_modelsfrom ...order.events import transaction_event+from ...order.models import Orderfrom ...payment import PaymentError, StorePaymentMethod, TransactionAction, gatewayfrom ...payment import models as payment_modelsfrom ...payment.error_codes import (@@ -53,6 +56,17 @@ from .types import Payment, PaymentInitialized, TransactionItemfrom .utils import metadata_contains_empty_key+def add_to_order_total_authorized_and_total_charged(+ order_id: uuid.UUID,+ authorized_amount_to_add: Decimal,+ charged_amount_to_add: Decimal,+):+ Order.objects.filter(id=order_id).update(+ total_authorized_amount=F("total_authorized_amount") + authorized_amount_to_add,+ total_charged_amount=F("total_charged_amount") + charged_amount_to_add,+ )++def description(enum):if enum is None:return "Enum representing the type of a payment storage in a gateway."@@ -788,6 +802,18 @@ class TransactionCreate(BaseMutation):transaction=transaction,)+ @classmethod+ def add_amounts_to_order(cls, order_id: uuid.UUID, transaction_data: dict):+ authorized_amount = transaction_data.get("authorized_value", 0)+ charged_amount = transaction_data.get("charged_value", 0)+ if not authorized_amount and not charged_amount:+ return+ add_to_order_total_authorized_and_total_charged(+ order_id=order_id,+ authorized_amount_to_add=authorized_amount,+ charged_amount_to_add=charged_amount,+ )+@classmethoddef perform_mutation(cls, root, info, **data):instance_id = data.get("id")@@ -811,6 +837,9 @@ class TransactionCreate(BaseMutation):name=transaction_event_data.get("name", ""),)transaction = cls.create_transaction(transaction_data)+ if order_id := transaction_data.get("order_id"):+ cls.add_amounts_to_order(order_id, transaction_data)+if transaction_event_data:cls.create_transaction_event(transaction_event_data, transaction)return TransactionCreate(transaction=transaction)@@ -864,6 +893,33 @@ class TransactionUpdate(TransactionCreate):error_code=TransactionUpdateErrorCode.METADATA_KEY_REQUIRED.value,)+ @classmethod+ def update_amounts_for_order(+ cls,+ transaction: payment_models.TransactionItem,+ order_id: uuid.UUID,+ transaction_data: dict,+ ):+ current_authorized_amount = transaction.authorized_value+ updated_authorized_amount = transaction_data.get(+ "authorized_value", current_authorized_amount+ )+ authorized_amount_to_add = updated_authorized_amount - current_authorized_amount++ current_charged_amount = transaction.charged_value+ updated_charged_amount = transaction_data.get(+ "charged_value", current_charged_amount+ )+ charged_amount_to_add = updated_charged_amount - current_charged_amount++ if not authorized_amount_to_add and not charged_amount_to_add:+ return+ add_to_order_total_authorized_and_total_charged(+ order_id=order_id,+ authorized_amount_to_add=authorized_amount_to_add,+ charged_amount_to_add=charged_amount_to_add,+ )+@classmethoddef perform_mutation(cls, root, info, **data):instance_id = data.get("id")@@ -873,6 +929,10 @@ class TransactionUpdate(TransactionCreate):cls.validate_transaction_input(instance, transaction_data)cls.cleanup_money_data(transaction_data)cls.cleanup_metadata_data(transaction_data)+ if instance.order_id:+ cls.update_amounts_for_order(+ instance, instance.order_id, transaction_data+ )instance = cls.construct_instance(instance, transaction_data)instance.save()diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_create.py b/saleor/graphql/payment/tests/mutations/test_transaction_create.pyindex 20892f3568..023338e11d 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_create.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_create.py@@ -4,6 +4,7 @@ import grapheneimport pytestfrom .....order import OrderEvents+from .....order.utils import update_order_authorize_data, update_order_charge_datafrom .....payment import TransactionStatusfrom .....payment.error_codes import TransactionCreateErrorCodefrom .....payment.models import TransactionItem@@ -117,6 +118,99 @@ def test_transaction_create_for_order(}+def test_transaction_create_for_order_updates_order_total_authorized(+ order_with_lines, permission_manage_payments, app_api_client+):+ # given+ previously_authorized_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ authorized_value=previously_authorized_value, currency=order_with_lines.currency+ )++ update_order_authorize_data(order_with_lines)++ authorized_value = Decimal("10")++ variables = {+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),+ "transaction": {+ "status": "Authorized for 10$",+ "type": "Credit Card",+ "reference": "PSP reference - 123",+ "availableActions": [],+ "amountAuthorized": {+ "amount": authorized_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)+ data = content["data"]["transactionCreate"]["transaction"]+ assert data["authorizedAmount"]["amount"] == authorized_value+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + authorized_value+ )+ assert authorized_value == transaction.authorized_value+++def test_transaction_create_for_order_updates_order_total_charged(+ order_with_lines, permission_manage_payments, app_api_client+):+ # given+ previously_charged_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ charged_value=previously_charged_value, currency=order_with_lines.currency+ )+ update_order_charge_data(order_with_lines)++ charged_value = Decimal("10")++ variables = {+ "id": graphene.Node.to_global_id("Order", order_with_lines.pk),+ "transaction": {+ "status": "Charged 10$",+ "type": "Credit Card",+ "reference": "PSP reference - 123",+ "availableActions": [],+ "amountCharged": {+ "amount": charged_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_CREATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)+ data = content["data"]["transactionCreate"]["transaction"]+ assert data["chargedAmount"]["amount"] == charged_value+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + charged_value+ )+ assert charged_value == transaction.charged_value++def test_transaction_create_for_checkout(checkout_with_items, permission_manage_payments, app_api_client):diff --git a/saleor/graphql/payment/tests/mutations/test_transaction_update.py b/saleor/graphql/payment/tests/mutations/test_transaction_update.pyindex 8582692c3c..27e69d0360 100644--- a/saleor/graphql/payment/tests/mutations/test_transaction_update.py+++ b/saleor/graphql/payment/tests/mutations/test_transaction_update.py@@ -4,6 +4,7 @@ import grapheneimport pytestfrom .....order import OrderEvents+from .....order.utils import update_order_authorize_data, update_order_charge_datafrom .....payment import TransactionStatusfrom .....payment.error_codes import TransactionUpdateErrorCodefrom .....payment.models import TransactionItem@@ -217,6 +218,297 @@ def test_transaction_update_amounts(assert getattr(transaction, db_field_name) == value+def test_transaction_update_for_order_increases_order_total_authorized(+ order_with_lines,+ permission_manage_payments,+ app_api_client,+ transaction,+):+ # given+ previously_authorized_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ authorized_value=previously_authorized_value, currency=order_with_lines.currency+ )+ update_order_authorize_data(+ order_with_lines,+ )+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + transaction.authorized_value+ )++ authorized_value = transaction.authorized_value + Decimal("10")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountAuthorized": {+ "amount": authorized_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)++ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["authorizedAmount"]["amount"] == authorized_value+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + authorized_value+ )+ assert authorized_value == transaction.authorized_value+++def test_transaction_update_for_order_reduces_order_total_authorized(+ order_with_lines,+ permission_manage_payments,+ app_api_client,+ transaction,+):+ # given+ previously_authorized_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ authorized_value=previously_authorized_value, currency=order_with_lines.currency+ )+ update_order_authorize_data(order_with_lines)+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + transaction.authorized_value+ )++ authorized_value = transaction.authorized_value - Decimal("5")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountAuthorized": {+ "amount": authorized_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)++ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["authorizedAmount"]["amount"] == authorized_value+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + authorized_value+ )+ assert authorized_value == transaction.authorized_value+++def test_transaction_update_for_order_reduces_transaction_authorized_amount_to_zero(+ order_with_lines,+ permission_manage_payments,+ app_api_client,+ transaction,+):+ # given+ previously_authorized_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ authorized_value=previously_authorized_value, currency=order_with_lines.currency+ )+ update_order_authorize_data(order_with_lines)+ assert (+ order_with_lines.total_authorized_amount+ == previously_authorized_value + transaction.authorized_value+ )++ authorized_value = Decimal("0")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountAuthorized": {+ "amount": authorized_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)++ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["authorizedAmount"]["amount"] == authorized_value+ assert order_with_lines.total_authorized_amount == previously_authorized_value+ assert authorized_value == transaction.authorized_value+++def test_transaction_update_for_order_increases_order_total_charged(+ order_with_lines, permission_manage_payments, app_api_client, transaction+):+ # given+ previously_charged_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ charged_value=previously_charged_value, currency=order_with_lines.currency+ )++ update_order_charge_data(order_with_lines)+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + transaction.charged_value+ )++ charged_value = transaction.charged_value + Decimal("10")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountCharged": {+ "amount": charged_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)+ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["chargedAmount"]["amount"] == charged_value+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + charged_value+ )+ assert charged_value == transaction.charged_value+++def test_transaction_update_for_order_reduces_order_total_charged(+ order_with_lines, permission_manage_payments, app_api_client, transaction+):+ # given+ previously_charged_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ charged_value=previously_charged_value, currency=order_with_lines.currency+ )+ transaction.charged_value = Decimal("30")+ transaction.save()++ update_order_charge_data(order_with_lines)+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + transaction.charged_value+ )++ charged_value = transaction.charged_value - Decimal("5")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountCharged": {+ "amount": charged_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)+ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["chargedAmount"]["amount"] == charged_value+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + charged_value+ )+ assert charged_value == transaction.charged_value+++def test_transaction_update_for_order_reduces_transaction_charged_amount_to_zero(+ order_with_lines, permission_manage_payments, app_api_client, transaction+):+ # given+ previously_charged_value = Decimal("90")+ old_transaction = order_with_lines.payment_transactions.create(+ charged_value=previously_charged_value, currency=order_with_lines.currency+ )+ transaction.charged_value = Decimal("30")+ transaction.save()++ update_order_charge_data(order_with_lines)+ assert (+ order_with_lines.total_charged_amount+ == previously_charged_value + transaction.charged_value+ )++ charged_value = Decimal("0")++ variables = {+ "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),+ "transaction": {+ "amountCharged": {+ "amount": charged_value,+ "currency": "USD",+ },+ },+ }++ # when+ response = app_api_client.post_graphql(+ MUTATION_TRANSACTION_UPDATE, variables, permissions=[permission_manage_payments]+ )++ # then+ order_with_lines.refresh_from_db()+ transaction = order_with_lines.payment_transactions.exclude(+ id=old_transaction.id+ ).last()+ content = get_graphql_content(response)+ data = content["data"]["transactionUpdate"]["transaction"]+ assert data["chargedAmount"]["amount"] == charged_value+ assert order_with_lines.total_charged_amount == previously_charged_value+ assert charged_value == transaction.charged_value++def test_transaction_update_multiple_amounts_provided(transaction, permission_manage_payments, app_api_client):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex fb9772cc9a..28ce27726b 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -7997,6 +7997,24 @@ type Order implements Node & ObjectWithMetadata {"""User-friendly payment status."""paymentStatusDisplay: String!+ """+ The authorize status of the order.++ Added in Saleor 3.4.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ authorizeStatus: OrderAuthorizeStatusEnum!++ """+ The charge status of the order.++ Added in Saleor 3.4.++ Note: this API is currently in Feature Preview and can be subject to changes at later point.+ """+ chargeStatus: OrderChargeStatusEnum!+"""List of transactions for the order. Requires one of the following permissions: MANAGE_ORDERS, HANDLE_PAYMENTS.@@ -8399,6 +8417,47 @@ enum PaymentChargeStatusEnum {CANCELLED}+"""+Determine a current authorize status for order.++ We treat the order as fully authorized when the sum of authorized and charged funds+ cover the order.total.+ We treat the order as partially authorized when the sum of authorized and charged+ funds covers only part of the order.total+ We treat the order as not authorized when the sum of authorized and charged funds is+ 0.++ NONE - the funds are not authorized+ PARTIAL - the funds that are authorized or charged don't cover fully the order's+ total+ FULL - the funds that are authorized or charged fully cover the order's total+"""+enum OrderAuthorizeStatusEnum {+ NONE+ PARTIAL+ FULL+}++"""+Determine the current charge status for the order.++ We treat the order as overcharged when the charged amount is bigger that order.total+ We treat the order as fully charged when the charged amount is equal to order.total.+ We treat the order as partially charged when the charged amount covers only part of+ the order.total++ NONE - the funds are not charged.+ PARTIAL - the funds that are charged don't cover the order's total+ FULL - the funds that are charged fully cover the order's total+ OVERCHARGED - the charged funds are bigger than order's total+"""+enum OrderChargeStatusEnum {+ NONE+ PARTIAL+ FULL+ OVERCHARGED+}+"""Represents a payment of a given type."""type Payment implements Node & ObjectWithMetadata {id: ID!@@ -9342,6 +9401,8 @@ input OrderFilterInput {search: Stringmetadata: [MetadataFilter!]channels: [ID!]+ authorizeStatus: [OrderAuthorizeStatusEnum!]+ chargeStatus: [OrderChargeStatusEnum!]updatedAt: DateTimeRangeInputisClickAndCollect: BooleanisPreorder: Booleandiff --git a/saleor/order/__init__.py b/saleor/order/__init__.pyindex 28530c37c5..b3d1d7ee39 100644--- a/saleor/order/__init__.py+++ b/saleor/order/__init__.py@@ -214,6 +214,67 @@ class OrderEventsEmails:]+class OrderAuthorizeStatus:+ """Determine a current authorize status for order.++ We treat the order as fully authorized when the sum of authorized and charged funds+ cover the order.total.+ We treat the order as partially authorized when the sum of authorized and charged+ funds covers only part of the order.total+ We treat the order as not authorized when the sum of authorized and charged funds is+ 0.++ NONE - the funds are not authorized+ PARTIAL - the funds that are authorized or charged don't cover fully the order's+ total+ FULL - the funds that are authorized or charged fully cover the order's total+ """++ NONE = "none"+ PARTIAL = "partial"+ FULL = "full"++ CHOICES = [+ (NONE, "The funds are not authorized"),+ (+ PARTIAL,+ "The funds that are authorized or charged don't cover fully the order's "+ "total",+ ),+ (+ FULL,+ "The funds that are authorized or charged fully cover the order's total",+ ),+ ]+++class OrderChargeStatus:+ """Determine the current charge status for the order.++ We treat the order as overcharged when the charged amount is bigger that order.total+ We treat the order as fully charged when the charged amount is equal to order.total.+ We treat the order as partially charged when the charged amount covers only part of+ the order.total++ NONE - the funds are not charged.+ PARTIAL - the funds that are charged don't cover the order's total+ FULL - the funds that are charged fully cover the order's total+ OVERCHARGED - the charged funds are bigger than order's total+ """++ NONE = "none"+ PARTIAL = "partial"+ FULL = "full"+ OVERCHARGED = "overcharged"++ CHOICES = [+ (NONE, "The funds are not charged."),+ (PARTIAL, "The funds that are charged, don't cover the order's total"),+ (FULL, "The funds that are charged fully cover the order's total"),+ (OVERCHARGED, "The charged funds are bigger than order's total"),+ ]++@dataclassclass FulfillmentLineData:line: "FulfillmentLine"diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex a3a1250ea0..42ff72c510 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -60,6 +60,8 @@ from .utils import (order_line_needs_automatic_fulfillment,recalculate_order,restock_fulfillment_lines,+ update_order_authorize_data,+ update_order_charge_data,update_order_status,)@@ -519,7 +521,12 @@ def mark_order_as_paid(transaction.on_commit(lambda: manager.order_fully_paid(order))transaction.on_commit(lambda: manager.order_updated(order))- order.update_total_paid()+ update_order_charge_data(+ order,+ )+ update_order_authorize_data(+ order,+ )def clean_mark_order_as_paid(order: "Order"):diff --git a/saleor/order/migrations/0148_auto_20220519_1118.py b/saleor/order/migrations/0148_auto_20220519_1118.pynew file mode 100644index 0000000000..3e4b641c86--- /dev/null+++ b/saleor/order/migrations/0148_auto_20220519_1118.py@@ -0,0 +1,69 @@+# Generated by Django 3.2.13 on 2022-05-17 10:08+from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0147_alter_orderline_options"),+ ]++ operations = [+ migrations.RenameField(+ model_name="order",+ old_name="total_paid_amount",+ new_name="total_charged_amount",+ ),+ migrations.AddField(+ model_name="order",+ name="total_authorized_amount",+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),+ ),+ migrations.AddField(+ model_name="order",+ name="authorize_status",+ field=models.CharField(+ choices=[+ ("none", "The funds are not authorized"),+ (+ "partial",+ (+ "The funds that are authorized or charged don't cover "+ "fully the order's total"+ ),+ ),+ (+ "full",+ (+ "The funds that are authorized or charged fully cover the "+ "order's total"+ ),+ ),+ ],+ db_index=True,+ default="none",+ max_length=32,+ ),+ ),+ migrations.AddField(+ model_name="order",+ name="charge_status",+ field=models.CharField(+ choices=[+ ("none", "The funds are not charged."),+ (+ "partial",+ "The funds that are charged, don't cover the order's total",+ ),+ (+ "full",+ "The funds that are charged fully cover the order's total",+ ),+ ("overcharged", "The charged funds are bigger than order's total"),+ ],+ default="none",+ db_index=True,+ max_length=32,+ ),+ ),+ ]diff --git a/saleor/order/migrations/0149_add_fields_for_authorize_and_charge.py b/saleor/order/migrations/0149_add_fields_for_authorize_and_charge.pynew file mode 100644index 0000000000..b74d8491c6--- /dev/null+++ b/saleor/order/migrations/0149_add_fields_for_authorize_and_charge.py@@ -0,0 +1,65 @@+# Generated by Django 3.2.13 on 2022-05-17 10:17++from django.db import migrations, models+++def set_total_authorized_amount(apps, _schema_editor):+ Transaction = apps.get_model("payment", "Transaction")+ TransactionItem = apps.get_model("payment", "TransactionItem")+ Order = apps.get_model("order", "Order")++ # We don't store authorized amount directly in payment model. We need to find+ # all auth transactions, that are success and doesn't require any action, then+ # annotate the sum of them and assign to order as a `total_authorized_amount`.+ # The payment status `not-charged` exists only in case when payment is not paid yet.+ transaction_amounts = Transaction.objects.filter(+ payment__order_id=models.OuterRef("id"),+ payment__is_active=True,+ payment__charge_status="not-charged",+ is_success=True,+ action_required=False,+ kind="auth",+ ).values("payment__order_id")++ transactions_total_authorized_amounts = transaction_amounts.annotate(+ total_amount=models.Sum("amount", output_field=models.DecimalField())+ ).values("total_amount")++ Order.objects.filter(models.Exists(transactions_total_authorized_amounts)).update(+ total_authorized_amount=models.Subquery(transactions_total_authorized_amounts)+ )++ transaction_items = TransactionItem.objects.filter(+ order_id=models.OuterRef("id")+ ).values("order_id")+ transaction_items_total_authorized_amount = transaction_items.annotate(+ total_authorized=models.Sum(+ "authorized_value", output_field=models.DecimalField()+ )+ ).values("total_authorized")++ transaction_items_total_charged_amount = transaction_items.annotate(+ total_charged=models.Sum("charged_value", output_field=models.DecimalField())+ ).values("total_charged")+ order_ids = TransactionItem.objects.all().values_list("order_id", flat=True)++ Order.objects.filter(id__in=order_ids).update(+ total_authorized_amount=models.F("total_authorized_amount")+ + models.Subquery(transaction_items_total_authorized_amount),+ total_charged_amount=models.F("total_charged_amount")+ + models.Subquery(transaction_items_total_charged_amount),+ )+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0148_auto_20220519_1118"),+ ("payment", "0036_auto_20220518_0732"),+ ]++ operations = [+ migrations.RunPython(+ set_total_authorized_amount, reverse_code=migrations.RunPython.noop+ ),+ ]diff --git a/saleor/order/migrations/0150_update_authorize_and_charge_status.py b/saleor/order/migrations/0150_update_authorize_and_charge_status.pynew file mode 100644index 0000000000..1c07c61081--- /dev/null+++ b/saleor/order/migrations/0150_update_authorize_and_charge_status.py@@ -0,0 +1,48 @@+# Generated by Django 3.2.13 on 2022-05-19 11:21++from django.db import migrations, models+++def update_authorize_status(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ order_query = Order.objects.annotate(+ sum_authorized=models.F("total_authorized_amount")+ + models.F("total_charged_amount")+ )+ order_query.filter(+ sum_authorized__gt=0, sum_authorized__lt=models.F("total_gross_amount")+ ).update(authorize_status="partial")+ order_query.filter(sum_authorized__gte=models.F("total_gross_amount")).update(+ authorize_status="full"+ )+++def update_charge_status(apps, _schema_editor):+ Order = apps.get_model("order", "Order")+ Order.objects.filter(+ total_charged_amount__gt=0,+ total_charged_amount__lt=models.F("total_gross_amount"),+ ).update(charge_status="partial")++ Order.objects.filter(total_charged_amount=models.F("total_gross_amount")).update(+ charge_status="full"+ )+ Order.objects.filter(+ total_charged_amount__gt=models.F("total_gross_amount")+ ).update(charge_status="overcharged")+++class Migration(migrations.Migration):++ dependencies = [+ ("order", "0149_add_fields_for_authorize_and_charge"),+ ]++ operations = [+ migrations.RunPython(+ update_authorize_status, reverse_code=migrations.RunPython.noop+ ),+ migrations.RunPython(+ update_charge_status, reverse_code=migrations.RunPython.noop+ ),+ ]diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 6569cb1250..2cfc3a77e1 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -27,10 +27,17 @@ from ..discount import DiscountValueTypefrom ..discount.models import Voucherfrom ..giftcard.models import GiftCardfrom ..payment import ChargeStatus, TransactionKind-from ..payment.model_helpers import get_subtotal, get_total_authorized+from ..payment.model_helpers import get_subtotalfrom ..payment.models import Paymentfrom ..shipping.models import ShippingMethod-from . import FulfillmentStatus, OrderEvents, OrderOrigin, OrderStatus+from . import (+ FulfillmentStatus,+ OrderAuthorizeStatus,+ OrderChargeStatus,+ OrderEvents,+ OrderOrigin,+ OrderStatus,+)class OrderQueryset(models.QuerySet):@@ -61,7 +68,7 @@ class OrderQueryset(models.QuerySet):return self.filter(Exists(payments.filter(order_id=OuterRef("id"))),status__in=statuses,- total_gross_amount__lte=F("total_paid_amount"),+ total_gross_amount__lte=F("total_charged_amount"),)def ready_to_capture(self):@@ -99,6 +106,18 @@ class Order(ModelWithMetadata):status = models.CharField(max_length=32, default=OrderStatus.UNFULFILLED, choices=OrderStatus.CHOICES)+ authorize_status = models.CharField(+ max_length=32,+ default=OrderAuthorizeStatus.NONE,+ choices=OrderAuthorizeStatus.CHOICES,+ db_index=True,+ )+ charge_status = models.CharField(+ max_length=32,+ default=OrderChargeStatus.NONE,+ choices=OrderChargeStatus.CHOICES,+ db_index=True,+ )user = models.ForeignKey(settings.AUTH_USER_MODEL,blank=True,@@ -237,12 +256,22 @@ class Order(ModelWithMetadata):currency_field="currency",)- total_paid_amount = models.DecimalField(+ total_charged_amount = models.DecimalField(+ max_digits=settings.DEFAULT_MAX_DIGITS,+ decimal_places=settings.DEFAULT_DECIMAL_PLACES,+ default=0,+ )+ total_authorized_amount = models.DecimalField(max_digits=settings.DEFAULT_MAX_DIGITS,decimal_places=settings.DEFAULT_DECIMAL_PLACES,default=0,)- total_paid = MoneyField(amount_field="total_paid_amount", currency_field="currency")+ total_authorized = MoneyField(+ amount_field="total_authorized_amount", currency_field="currency"+ )+ total_charged = MoneyField(+ amount_field="total_charged_amount", currency_field="currency"+ )voucher = models.ForeignKey(Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULL@@ -281,20 +310,14 @@ class Order(ModelWithMetadata):]def is_fully_paid(self):- return self.total_paid >= self.total.gross+ return self.total_charged >= self.total.grossdef is_partly_paid(self):- return self.total_paid_amount > 0+ return self.total_charged_amount > 0def get_customer_email(self):return self.user.email if self.user_id else self.user_email- def update_total_paid(self):- self.total_paid_amount = (- sum(self.payments.values_list("captured_amount", flat=True)) or 0- )- self.save(update_fields=["total_paid_amount", "updated_at"])-def _index_billing_phone(self):return self.billing_address.phone@@ -396,17 +419,9 @@ class Order(ModelWithMetadata):payments = self.payments.all()return len(payments) == 0- @property- def total_authorized(self):- return get_total_authorized(self.payments.all(), self.currency)-- @property- def total_captured(self):- return self.total_paid-@propertydef total_balance(self):- return self.total_captured - self.total.gross+ return self.total_charged - self.total.grossdef get_total_weight(self, _lines=None):return self.weightdiff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex ab7c7d8afb..8ca7f14925 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -47,6 +47,8 @@ from ..utils import (get_voucher_discount_for_order,recalculate_order,restock_fulfillment_lines,+ update_order_authorize_data,+ update_order_charge_data,update_order_prices,update_order_status,)@@ -492,13 +494,13 @@ def test_order_queryset_to_ship(settings, channel_USD):Order.objects.create(status=OrderStatus.UNFULFILLED,total=total,- total_paid_amount=total.gross.amount,+ total_charged_amount=total.gross.amount,channel=channel_USD,),Order.objects.create(status=OrderStatus.PARTIALLY_FULFILLED,total=total,- total_paid_amount=total.gross.amount,+ total_charged_amount=total.gross.amount,channel=channel_USD,),]@@ -1324,3 +1326,128 @@ def test_available_collection_points_for_preorders_and_regular_variants_in_orderexpected_collection_points== response_content["data"]["order"]["availableCollectionPoints"])+++def test_order_update_total_authorize_data_with_payment(+ order_with_lines, payment_txn_preauth+):+ # given+ authorized_amount = payment_txn_preauth.transactions.first().amount++ # when+ update_order_authorize_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_authorized == Money(+ authorized_amount, order_with_lines.currency+ )+++def test_order_update_total_authorize_data_with_transaction_item(order_with_lines):+ # given+ first_authorized_amount = Decimal(10)+ order_with_lines.payment_transactions.create(+ authorized_value=first_authorized_amount,+ charged_value=Decimal(12),+ currency=order_with_lines.currency,+ )+ second_authorized_amount = Decimal(3)+ order_with_lines.payment_transactions.create(+ authorized_value=second_authorized_amount,+ charged_value=Decimal(12),+ currency=order_with_lines.currency,+ )++ # when+ update_order_authorize_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_authorized == Money(+ first_authorized_amount + second_authorized_amount, order_with_lines.currency+ )+++def test_order_update_total_authorize_data_with_transaction_item_and_payment(+ order_with_lines, payment_txn_preauth+):+ # given+ first_authorized_amount = payment_txn_preauth.transactions.first().amount++ second_authorized_amount = Decimal(3)+ order_with_lines.payment_transactions.create(+ authorized_value=second_authorized_amount,+ charged_value=Decimal(12),+ currency=order_with_lines.currency,+ )++ # when+ update_order_authorize_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_authorized == Money(+ first_authorized_amount + second_authorized_amount, order_with_lines.currency+ )+++def test_order_update_charge_data_with_payment(order_with_lines, payment_txn_captured):+ # given+ charged_amount = payment_txn_captured.transactions.first().amount++ # when+ update_order_charge_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_charged == Money(+ charged_amount, order_with_lines.currency+ )+++def test_order_update_charge_data_with_transaction_item(order_with_lines):+ # given+ first_charged_amount = Decimal(10)+ order_with_lines.payment_transactions.create(+ charged_value=first_charged_amount,+ authorized_value=Decimal(12),+ currency=order_with_lines.currency,+ )+ second_charged_amount = Decimal(3)+ order_with_lines.payment_transactions.create(+ authorized_value=Decimal(11),+ charged_value=second_charged_amount,+ currency=order_with_lines.currency,+ )++ # when+ update_order_charge_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_charged == Money(+ first_charged_amount + second_charged_amount, order_with_lines.currency+ )+++def test_order_update_charge_data_with_transaction_item_and_payment(+ order_with_lines, payment_txn_captured+):+ # given+ first_charged_amount = payment_txn_captured.transactions.first().amount+ second_charged_amount = Decimal(3)+ order_with_lines.payment_transactions.create(+ authorized_value=Decimal(11),+ charged_value=second_charged_amount,+ currency=order_with_lines.currency,+ )++ # when+ update_order_charge_data(order_with_lines)++ # then+ order_with_lines.refresh_from_db()+ assert order_with_lines.total_charged == Money(+ first_charged_amount + second_charged_amount, order_with_lines.currency+ )diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex f316ffce99..f5e9b41ff4 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom prices import Money, TaxedMoney, fixed_discount, percentage_discountfrom ..account.models import User+from ..core.prices import quantize_pricefrom ..core.taxes import zero_moneyfrom ..core.tracing import traced_atomic_transactionfrom ..core.weight import zero_weight@@ -21,9 +22,9 @@ from ..discount.utils import ()from ..giftcard import events as gift_card_eventsfrom ..giftcard.models import GiftCard-from ..order import FulfillmentStatus, OrderStatusfrom ..order.fetch import OrderLineInfofrom ..order.models import Order, OrderLine+from ..payment.model_helpers import get_total_authorizedfrom ..product.utils.digital_products import get_default_digital_content_settingsfrom ..shipping.interface import ShippingMethodDatafrom ..shipping.models import ShippingMethod, ShippingMethodChannelListing@@ -38,7 +39,13 @@ from ..warehouse.management import (increase_stock,)from ..warehouse.models import Warehouse-from . import events+from . import (+ FulfillmentStatus,+ OrderAuthorizeStatus,+ OrderChargeStatus,+ OrderStatus,+ events,+)if TYPE_CHECKING:from ..app.models import App@@ -1010,3 +1017,97 @@ def remove_discount_from_order_line("tax_rate",])+++def update_order_charge_status(order: Order):+ """Update the current charge status for the order.++ We treat the order as overcharged when the charged amount is bigger that order.total+ We treat the order as fully charged when the charged amount is equal to order.total.+ We treat the order as partially charged when the charged amount covers only part of+ the order.total+ We treat the order as not charged when the charged amount is 0.+ """+ total_charged = order.total_charged_amount or Decimal("0")+ total_charged = quantize_price(total_charged, order.currency)++ total_gross = order.total_gross_amount or Decimal(0)+ total_gross = quantize_price(total_gross, order.currency)++ if total_charged <= 0:+ order.charge_status = OrderChargeStatus.NONE+ elif total_charged < total_gross:+ order.charge_status = OrderChargeStatus.PARTIAL+ elif total_charged == total_gross:+ order.charge_status = OrderChargeStatus.FULL+ else:+ order.charge_status = OrderChargeStatus.OVERCHARGED+++def _update_order_total_charged(order: Order):+ order.total_charged_amount = (+ sum(order.payments.values_list("captured_amount", flat=True)) # type: ignore+ or 0+ )+ order.total_charged_amount += sum(+ order.payment_transactions.values_list( # type: ignore+ "charged_value", flat=True+ )+ )+++def update_order_charge_data(order: Order, with_save=True):+ _update_order_total_charged(order)+ update_order_charge_status(order)+ if with_save:+ order.save(+ update_fields=["total_charged_amount", "charge_status", "updated_at"]+ )+++def _update_order_total_authorized(order: Order):+ order.total_authorized_amount = get_total_authorized(+ order.payments.all(), order.currency # type: ignore+ ).amount+ order.total_authorized_amount += (+ sum(+ order.payment_transactions.values_list( # type: ignore+ "authorized_value", flat=True+ )+ )+ or 0+ )+++def update_order_authorize_status(order: Order):+ """Update the current authorize status for the order.++ We treat the order as fully authorized when the sum of authorized and charged funds+ cover the order.total.+ We treat the order as partially authorized when the sum of authorized and charged+ funds covers only part of the order.total+ We treat the order as not authorized when the sum of authorized and charged funds is+ 0.+ """+ total_covered = (+ order.total_authorized_amount + order.total_charged_amount or Decimal("0")+ )+ total_covered = quantize_price(total_covered, order.currency)+ total_gross = order.total_gross_amount or Decimal("0")+ total_gross = quantize_price(total_gross, order.currency)++ if total_covered == 0:+ order.authorize_status = OrderAuthorizeStatus.NONE+ elif total_covered >= total_gross:+ order.authorize_status = OrderAuthorizeStatus.FULL+ else:+ order.authorize_status = OrderAuthorizeStatus.PARTIAL+++def update_order_authorize_data(order: Order, with_save=True):+ _update_order_total_authorized(order)+ update_order_authorize_status(order)+ if with_save:+ order.save(+ update_fields=["total_authorized_amount", "authorize_status", "updated_at"]+ )diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.pyindex ee397c0283..411e7865fe 100644--- a/saleor/payment/tests/test_payment.py+++ b/saleor/payment/tests/test_payment.py@@ -619,7 +619,6 @@ def test_payment_get_authorized_amount(payment_txn_preauth):authorized_amount = payment.transactions.first().amountassert payment.get_authorized_amount().amount == authorized_amount- assert payment.order.total_authorized.amount == authorized_amountpayment.transactions.create(amount=payment.total,diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex ef544d1f67..d262f21209 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -15,6 +15,7 @@ from ..core.prices import quantize_pricefrom ..core.tracing import traced_atomic_transactionfrom ..discount.utils import fetch_active_discountsfrom ..order.models import Order+from ..order.utils import update_order_authorize_data, update_order_charge_datafrom ..plugins.manager import PluginsManager, get_plugins_managerfrom . import (ChargeStatus,@@ -445,7 +446,6 @@ def update_payment_charge_status(payment, transaction, changed_fields=None):changed_fields = changed_fields or []transaction_kind = transaction.kind-if transaction_kind in {TransactionKind.CAPTURE,TransactionKind.REFUND_REVERSED,@@ -493,8 +493,10 @@ def update_payment_charge_status(payment, transaction, changed_fields=None):payment.save(update_fields=changed_fields)transaction.already_processed = Truetransaction.save(update_fields=["already_processed"])- if "captured_amount" in changed_fields and payment.order:- payment.order.update_total_paid()+ if "captured_amount" in changed_fields and payment.order_id:+ update_order_charge_data(payment.order)+ if transaction_kind == TransactionKind.AUTH and payment.order_id:+ update_order_authorize_data(payment.order)def fetch_customer_id(user: User, gateway: str):