nk20-scripts/management/commands/send_reports.py

65 lines
2.6 KiB
Python
Raw Normal View History

# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
# SPDX-License-Identifier: GPL-3.0-or-later
from datetime import timedelta
from django.core.management import BaseCommand
from django.db.models import Q
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import activate
from note.models import NoteUser, Transaction
from note.tables import HistoryTable
class Command(BaseCommand):
2020-09-07 09:02:10 +00:00
def add_arguments(self, parser):
parser.add_argument('--notes', '-n', type=int, nargs='+', help='Select note ids')
parser.add_argument('--debug', '-d', action='store_true', help='Debug mode, print mails in stdout')
def handle(self, *args, **options):
activate('fr')
if 'notes' in options and options['notes']:
notes = NoteUser.objects.filter(pk__in=options['notes']).all()
2020-09-07 09:02:10 +00:00
else:
notes = NoteUser.objects.filter(
user__memberships__date_end__gte=timezone.now(),
user__profile__report_frequency__gt=0,
).distinct().all()
for note in notes:
now = timezone.now()
last_report = note.user.profile.last_report
delta = now.date() - last_report.date()
if delta.days < note.user.profile.report_frequency:
continue
if not options["debug"]:
note.user.profile.last_report = now
note.user.profile.save()
last_transactions = Transaction.objects.filter(
Q(source=note) | Q(destination=note),
created_at__gte=last_report,
).order_by("created_at").all()
if not last_transactions.exists():
continue
table = HistoryTable(last_transactions)
incoming = sum(tr.total for tr in last_transactions if tr.destination.pk == note.pk if tr.valid)
outcoming = sum(tr.total for tr in last_transactions if tr.source.pk == note.pk if tr.valid)
context = dict(
user=note.user,
table=table,
2020-09-07 09:02:10 +00:00
last_transactions=last_transactions,
incoming=incoming,
outcoming=outcoming,
diff=incoming - outcoming,
now=now,
last_report=last_report,
)
2020-09-07 09:02:10 +00:00
plain = render_to_string("note/mails/weekly_report.txt", context)
html = render_to_string("note/mails/weekly_report.html", context)
2020-09-07 09:02:10 +00:00
if options["debug"]:
self.stdout.write(plain)
else:
note.user.email_user("[Note Kfet] Rapport de la Note Kfet", plain, html_message=html)