feat: improved order payment lifecycle
This commit is contained in:
+29
-6
@@ -7,6 +7,7 @@ from decimal import Decimal
|
||||
import pyDes
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import transaction
|
||||
from django.db.models import Sum
|
||||
from django.utils import timezone
|
||||
from django.utils.text import gettext_lazy as _
|
||||
|
||||
@@ -20,8 +21,10 @@ from shop.models import (
|
||||
ProductBatch,
|
||||
ProductPrice,
|
||||
ShippingMethod,
|
||||
CartItem,
|
||||
)
|
||||
from shop.settings import ERROR_CODES
|
||||
from shop.signals import clear_cart
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
@@ -114,6 +117,7 @@ def create_order_from_cart(
|
||||
shipping_method=shipping_method,
|
||||
user=cart.user,
|
||||
email=email,
|
||||
from_cart=cart,
|
||||
)
|
||||
|
||||
for item in cart.items.all():
|
||||
@@ -261,15 +265,34 @@ def validate_expiry_date(expiry_date: str):
|
||||
return True
|
||||
|
||||
|
||||
def pay_order(order: Order, amount_paid: Decimal):
|
||||
with transaction.atomic() as tx:
|
||||
def update_order_payment_status(order: Order):
|
||||
if order.amount_paid >= order.total:
|
||||
order.status = Order.Statuses.STATUS_PAID
|
||||
elif order.status == Order.Statuses.STATUS_PAID and order.amount_paid == Decimal(
|
||||
"0.00"
|
||||
):
|
||||
order.status = Order.Statuses.STATUS_RETURNED
|
||||
else:
|
||||
order.status = Order.Statuses.STATUS_PENDING
|
||||
|
||||
order.save()
|
||||
|
||||
|
||||
def delete_cart_items_from_order(order):
|
||||
if order.status == Order.Statuses.STATUS_PAID and order.from_cart:
|
||||
CartItem.objects.filter(cart=order.from_cart).delete()
|
||||
|
||||
|
||||
def add_payment_to_order(order: Order, amount):
|
||||
with transaction.atomic():
|
||||
payment = Payment.objects.create(
|
||||
amount=amount_paid,
|
||||
amount=amount,
|
||||
order=order,
|
||||
user=order.user,
|
||||
method=Payment.MethodChoices.REDSYS,
|
||||
)
|
||||
order.amount_paid += payment.amount
|
||||
|
||||
if amount_paid >= order.total:
|
||||
order.status = Order.Statuses.STATUS_PAID
|
||||
order.save()
|
||||
update_order_payment_status(order)
|
||||
|
||||
delete_cart_items_from_order(order)
|
||||
|
||||
Reference in New Issue
Block a user