kpsul/kfet/management/commands/sendrappelsnegatifs.py

58 lines
1.9 KiB
Python

"""
Gestion en ligne de commande des mails de rappel K-Fet.
"""
import smtplib
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from kfet.models import AccountNegative
def send_mail(neg: AccountNegative, stdout) -> None:
try:
neg.send_rappel()
stdout.write(f"Mail de rappel pour {neg.account} envoyé avec succès.")
except smtplib.SMTPException:
stdout.write(f"Erreur lors de l'envoi du mail de rappel pour {neg.account}.")
class Command(BaseCommand):
help = (
"Envoie un mail de rappel aux personnes en négatif.\n"
"Envoie un mail au bout de 24h, puis un mail par semaine."
)
leave_locale_alone = True
def handle(self, *args, **options):
now = timezone.now()
# Le premier mail est envoyé après 24h de négatif, puis toutes les semaines
first_delay = timedelta(days=1)
periodic_delay = timedelta(weeks=1)
# On n'envoie des mails qu'aux comptes qui ont un négatif vraiment actif
# et dont la balance est négative
# On ignore les comptes gelés qui signinfient une adresse mail plus valide
account_negatives = AccountNegative.objects.filter(
account__balance__lt=0, account__is_frozen=False
).exclude(end__lte=now)
accounts_first_mail = account_negatives.filter(
start__lt=now - first_delay, last_rappel__isnull=True
)
accounts_periodic_mail = account_negatives.filter(
last_rappel__lt=now - periodic_delay
)
for neg in accounts_first_mail:
send_mail(neg, self.stdout)
for neg in accounts_periodic_mail:
send_mail(neg, self.stdout)
if not (accounts_first_mail.exists() or accounts_periodic_mail.exists()):
self.stdout.write("Aucun mail à envoyer.")