schon/payments/signals.py
Egor fureunoir Gorbunov 220e50c01b Features: 1) Restructure transaction processing to handle unsaved instances using pk check; 2) Instantiate AbstractGateway to prevent potential shared reference issues;
Fixes: 1) Correct logic to properly detect new transactions for processing;

Extra: 1) Minor code tidy-up with consistent case handling;
2025-07-06 23:17:23 +03:00

37 lines
1.3 KiB
Python

from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from payments.gateways import AbstractGateway
from payments.models import Balance, Transaction
from payments.utils.emailing import balance_deposit_email
from vibes_auth.models import User
@receiver(post_save, sender=User)
def create_balance_on_user_creation_signal(instance, created, **_kwargs):
if created:
Balance.objects.create(user=instance)
@receiver(pre_save, sender=Transaction)
def process_transaction_changes(instance, **_kwargs):
is_new = instance.pk is None
if is_new:
try:
match instance.process.get("gateway", "default"):
case "gateway":
gateway = AbstractGateway()
case "default":
gateway = AbstractGateway()
case _:
gateway = AbstractGateway()
gateway.process_transaction(instance)
except Exception as e:
instance.process = {"status": "ERRORED", "error": str(e)}
else:
status = str(instance.process.get("status", "")).lower()
success = instance.process.get("success", False)
if ("success" in status or success) and (instance.process.get("notify", False)):
balance_deposit_email.delay(instance.uuid)