2020-08-03 17:35:21 +00:00
|
|
|
# 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):
|
|
|
|
def handle(self, *args, **options):
|
|
|
|
activate('fr')
|
|
|
|
notes = NoteUser.objects.filter(
|
|
|
|
user__memberships__date_end__gte=timezone.now(),
|
2020-08-05 21:15:05 +00:00
|
|
|
user__profile__report_frequency__gt=0,
|
2020-08-03 17:35:21 +00:00
|
|
|
).distinct().all()
|
|
|
|
for note in notes:
|
|
|
|
now = timezone.now()
|
2020-08-05 21:15:05 +00:00
|
|
|
last_report = note.user.profile.last_report
|
|
|
|
delta = now.date() - last_report
|
|
|
|
if delta.days < note.user.profile.report_frequency:
|
|
|
|
continue
|
|
|
|
note.user.profile.last_report = now.date()
|
|
|
|
note.user.profile.save()
|
2020-08-03 17:35:21 +00:00
|
|
|
last_transactions = Transaction.objects.filter(
|
|
|
|
Q(source=note) | Q(destination=note),
|
2020-08-05 21:15:05 +00:00
|
|
|
created_at__gte=last_report,
|
|
|
|
).order_by("created_at").all()
|
2020-08-03 17:35:21 +00:00
|
|
|
if not last_transactions.exists():
|
|
|
|
continue
|
|
|
|
|
|
|
|
table = HistoryTable(last_transactions)
|
2020-08-03 17:37:42 +00:00
|
|
|
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)
|
2020-08-03 17:35:21 +00:00
|
|
|
context = dict(
|
|
|
|
user=note.user,
|
|
|
|
table=table,
|
|
|
|
incoming=incoming,
|
|
|
|
outcoming=outcoming,
|
|
|
|
diff=incoming - outcoming,
|
|
|
|
now=now,
|
2020-08-05 21:15:05 +00:00
|
|
|
last_report=last_report,
|
2020-08-03 17:35:21 +00:00
|
|
|
)
|
|
|
|
html = render_to_string("note/mails/weekly_report.html", context)
|
|
|
|
note.user.email_user("[Note Kfet] Rapport de la Note Kfet", html, html_message=html)
|