From c3b4100f3b6c136c49eee36b74ccadf5a7e3da3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= <cuu508@gmail.com> Date: Thu, 9 Nov 2023 14:00:22 +0200 Subject: [PATCH] Add a management command to notify admins about new log records --- hc/logs/management/__init__.py | 0 hc/logs/management/commands/__init__.py | 0 hc/logs/management/commands/sendlogs.py | 34 +++++++++++++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 hc/logs/management/__init__.py create mode 100644 hc/logs/management/commands/__init__.py create mode 100644 hc/logs/management/commands/sendlogs.py diff --git a/hc/logs/management/__init__.py b/hc/logs/management/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/hc/logs/management/commands/__init__.py b/hc/logs/management/commands/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/hc/logs/management/commands/sendlogs.py b/hc/logs/management/commands/sendlogs.py new file mode 100644 index 00000000..14ae72d9 --- /dev/null +++ b/hc/logs/management/commands/sendlogs.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from datetime import timedelta as td +from typing import Any + +from django.conf import settings +from django.core.mail import mail_admins +from django.core.management.base import BaseCommand +from django.urls import reverse +from django.utils.timezone import now + +from hc.logs.models import Record + +YEAR_AGO = now() - td(days=365) + + +class Command(BaseCommand): + help = """Send notification to admins about new log events.""" + + def handle(self, **options: Any) -> str: + threshold = now() - td(hours=24) + count = Record.objects.filter(created__gt=threshold).count() + if count > 0: + url = settings.SITE_ROOT + reverse("admin:logs_record_changelist") + s_maybe = "" if count == 1 else "s" + message = f"{count} new log record{s_maybe} in the last 24 hours" + html_message = f""" + {count} new log record{s_maybe} in the last 24 hours.<br /> + <a href="{url}">Show log records</a>. + """ + mail_admins(message, message, html_message=html_message) + return f"Done, {count} new log record{s_maybe}." + + return "Done, no new log records."