"""Deliver the latest fasting phase transition once per tracked schedule.""" import logging from django.db import transaction from django.utils import timezone from planner.models import FastingSettings from planner.services.fasting import current_fasting_phase from planner.services.notifications import NotificationError, send_notification logger = logging.getLogger(__name__) def notify_fasting_phase_changes(now=None): now = now or timezone.now() delivered = 0 for settings_id in FastingSettings.objects.filter(enabled=True).values_list('pk', flat=True): with transaction.atomic(): settings = FastingSettings.objects.select_for_update().select_related('user').get(pk=settings_id) if not settings.enabled: continue phase = current_fasting_phase(settings, now) boundary = phase.cycle_start cursor = settings.last_phase_notification_at if cursor is None: # Existing configurations start at the current phase without a catch-up alert. settings.last_phase_notification_at = now settings.save(update_fields=['last_phase_notification_at']) continue if boundary <= cursor or boundary > now: continue title = 'Fasting started' if phase.is_fasting else 'Eating window started' message = 'Your fasting window has started.' if phase.is_fasting else 'Your eating window is open.' try: sent = send_notification(settings.user, title, message) except NotificationError: logger.warning('Could not deliver fasting phase notification for user %s.', settings.user_id) continue settings.last_phase_notification_at = boundary settings.save(update_fields=['last_phase_notification_at']) delivered += int(sent) return delivered