import logging from django.core.management.base import BaseCommand from django.utils import timezone from django.utils import translation from django.utils.translation import gettext as _ from members.models import PendingNotificationBatch, UserSettings from notifications.services import NotificationError, send_notification logger = logging.getLogger(__name__) class Command(BaseCommand): help = "Send one ntfy summary per user for each completed minute of Pending arrivals." def handle(self, *args, **options): current_minute = timezone.now().replace(second=0, microsecond=0) batches = PendingNotificationBatch.objects.filter(minute__lt=current_minute).select_related("user").order_by("minute", "pk") for batch in batches.iterator(): if not UserSettings.objects.filter(user=batch.user, ntfy_enabled=True).exclude(ntfy_url="").exists(): batch.delete() continue try: with translation.override(batch.user.notification_settings.preferred_language): parts = [] if batch.manual_count: parts.append(_("%(count)d manual") % {"count": batch.manual_count}) if batch.sensor_count: parts.append(_("%(count)d sensor") % {"count": batch.sensor_count}) total = batch.manual_count + batch.sensor_count message = _("%(count)d new Pending event(s): %(sources)s.") % {"count": total, "sources": ", ".join(parts)} send_notification(batch.user, _("Pending events"), message) except NotificationError as error: logger.warning("Could not send Pending notification for user %s: %s", batch.user_id, error) continue batch.delete()