Skip to content

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

Add total_paid field on order (#7283)

Tomasz Szymańskia79a8b7d370d
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index e0fa77591b..d91f2106a1 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -405,6 +405,7 @@ def _create_order(
order.metadata = checkout.metadata
order.redirect_url = checkout.redirect_url
order.private_metadata = checkout.private_metadata
+ order.update_total_paid()
order.save()
transaction.on_commit(
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index d3a7433046..64eb886380 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -141,7 +141,10 @@ def clean_refund_payment(payment):
def try_payment_action(order, user, payment, func, *args, **kwargs):
try:
- return func(*args, **kwargs)
+ result = func(*args, **kwargs)
+ # provided order might alter it's total_paid.
+ order.refresh_from_db()
+ return result
except (PaymentError, ValueError) as e:
message = str(e)
events.payment_failed_event(
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 53d33712c3..43a508eec3 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -27,7 +27,6 @@ from ...payment.model_helpers import (
get_last_payment,
get_subtotal,
get_total_authorized,
- get_total_captured,
)
from ...product import ProductMediaTypes
from ...product.product_images import get_product_image_thumbnail
@@ -867,14 +866,7 @@ class Order(CountableDjangoObjectType):
@staticmethod
def resolve_total_captured(root: models.Order, info):
- def _resolve_total_captured(payments):
- return get_total_captured(payments, root.currency)
-
- return (
- PaymentsByOrderIdLoader(info.context)
- .load(root.id)
- .then(_resolve_total_captured)
- )
+ return root.total_paid
@staticmethod
def resolve_total_balance(root: models.Order, _info):
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 3c9d04e588..08469e11db 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -326,6 +326,7 @@ def mark_order_as_paid(
)
manager.order_fully_paid(order)
manager.order_updated(order)
+ order.update_total_paid()
def clean_mark_order_as_paid(order: "Order"):
diff --git a/saleor/order/migrations/0105_order_total_paid_amount.py b/saleor/order/migrations/0105_order_total_paid_amount.py
new file mode 100644
index 0000000000..5f14ac094e
--- /dev/null
+++ b/saleor/order/migrations/0105_order_total_paid_amount.py
@@ -0,0 +1,33 @@
+# Generated by Django 3.1.8 on 2021-04-29 07:02
+
+from django.db import migrations, models
+from django.db.models.functions import Coalesce
+
+
+def update_orders_total_paid_in_db(apps, schema_editor):
+ Order = apps.get_model("order", "Order")
+ Order.objects.update(
+ total_paid_amount=models.Subquery(
+ Order.objects.filter(id=models.OuterRef("id"))
+ .annotate(
+ _total_paid_amount=Coalesce(models.Sum("payments__captured_amount"), 0)
+ )
+ .values("_total_paid_amount")[:1]
+ )
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("order", "0104_auto_20210506_0835"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="total_paid_amount",
+ field=models.DecimalField(decimal_places=3, default=0, max_digits=12),
+ ),
+ migrations.RunPython(update_orders_total_paid_in_db, migrations.RunPython.noop),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index ff013d15fd..074b556f48 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -21,7 +21,6 @@ from ..account.models import Address
from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.permissions import OrderPermissions
-from ..core.taxes import zero_taxed_money
from ..core.units import WeightUnits
from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.weight import zero_weight
@@ -29,11 +28,7 @@ from ..discount import DiscountValueType
from ..discount.models import Voucher
from ..giftcard.models import GiftCard
from ..payment import ChargeStatus, TransactionKind
-from ..payment.model_helpers import (
- get_subtotal,
- get_total_authorized,
- get_total_captured,
-)
+from ..payment.model_helpers import get_subtotal, get_total_authorized
from ..payment.models import Payment
from ..shipping.models import ShippingMethod
from . import FulfillmentStatus, OrderEvents, OrderStatus
@@ -210,6 +205,13 @@ class Order(ModelWithMetadata):
currency_field="currency",
)
+ total_paid_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")
+
voucher = models.ForeignKey(
Voucher, blank=True, null=True, related_name="+", on_delete=models.SET_NULL
)
@@ -236,29 +238,19 @@ class Order(ModelWithMetadata):
return super().save(*args, **kwargs)
def is_fully_paid(self):
- total_paid = self._total_paid()
- return total_paid.gross >= self.total.gross
+ return self.total_paid >= self.total.gross
def is_partly_paid(self):
- total_paid = self._total_paid()
- return total_paid.gross.amount > 0
+ return self.total_paid_amount > 0
def get_customer_email(self):
return self.user.email if self.user else self.user_email
- def _total_paid(self):
- # Get total paid amount from partially charged,
- # fully charged and partially refunded payments
- payments = self.payments.filter(
- charge_status__in=[
- ChargeStatus.PARTIALLY_CHARGED,
- ChargeStatus.FULLY_CHARGED,
- ChargeStatus.PARTIALLY_REFUNDED,
- ]
+ def update_total_paid(self):
+ self.total_paid_amount = (
+ sum(self.payments.values_list("captured_amount", flat=True)) or 0
)
- total_captured = [payment.get_captured_amount() for payment in payments]
- total_paid = sum(total_captured, zero_taxed_money(currency=self.currency))
- return total_paid
+ self.save(update_fields=["total_paid_amount"])
def _index_billing_phone(self):
return self.billing_address.phone
@@ -363,7 +355,7 @@ class Order(ModelWithMetadata):
@property
def total_captured(self):
- return get_total_captured(self.payments.all(), self.currency)
+ return self.total_paid
@property
def total_balance(self):
diff --git a/saleor/payment/model_helpers.py b/saleor/payment/model_helpers.py
index d69e268be3..49fd920151 100644
--- a/saleor/payment/model_helpers.py
+++ b/saleor/payment/model_helpers.py
@@ -1,10 +1,7 @@
from operator import attrgetter
from typing import TYPE_CHECKING, List
-from prices import Money
-
from ..core.taxes import zero_money, zero_taxed_money
-from . import ChargeStatus
from .models import Payment
if TYPE_CHECKING:
@@ -15,22 +12,6 @@ def get_last_payment(payments: List[Payment]):
return max(payments, default=None, key=attrgetter("pk"))
-def get_total_captured(payments: List[Payment], fallback_currency: str):
- # FIXME adjust to multiple payments in the future
- if last_payment := get_last_payment(payments):
- if (
- last_payment.charge_status
- in (
- ChargeStatus.PARTIALLY_CHARGED,
- ChargeStatus.FULLY_CHARGED,
- ChargeStatus.PARTIALLY_REFUNDED,
- )
- and last_payment.is_active
- ):
- return Money(last_payment.captured_amount, last_payment.currency)
- return zero_money(fallback_currency)
-
-
def get_total_authorized(payments: List[Payment], fallback_currency: str):
# FIXME adjust to multiple payments in the future
if last_payment := get_last_payment(payments):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 4fab2a88cc..ca0ed6053c 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -308,6 +308,8 @@ def gateway_postprocess(transaction, payment):
payment.save(update_fields=changed_fields)
transaction.already_processed = True
transaction.save(update_fields=["already_processed"])
+ if "captured_amount" in changed_fields and payment.order:
+ payment.order.update_total_paid()
def fetch_customer_id(user: User, gateway: str):