"""Shared, user-scoped task occurrence operations.""" from datetime import datetime, timedelta from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from django.core.exceptions import ValidationError from django.db import transaction from planner.models import Task, TaskOccurrence, TaskOccurrenceEvent from planner.services.scheduling import is_task_scheduled_on_date def validate_local_time(day, clock, zone_name): if clock is None: return try: zone = ZoneInfo(zone_name) except ZoneInfoNotFoundError as exc: raise ValidationError('Choose a valid IANA time zone.') from exc local = datetime.combine(day, clock) # Round trips detect clock times lost in a spring DST transition. aware = local.replace(tzinfo=zone, fold=0) round_trip = aware.astimezone(ZoneInfo('UTC')).astimezone(zone).replace(tzinfo=None) if round_trip != local: raise ValidationError('This local time does not exist on the selected date.') # Ambiguous autumn times consistently use the first occurrence (fold=0). def occurrence_for_date(task, day): if not is_task_scheduled_on_date(task, day): raise ValidationError('This date is not part of the task schedule.') clock = task.scheduled_time if task.is_recurring and clock is not None: # Spring gaps move only this occurrence to the first valid wall time. for _ in range(24 * 60): try: validate_local_time(day, clock, task.time_zone) break except ValidationError as exc: if 'does not exist' not in str(exc): raise clock = (datetime.combine(day, clock) + timedelta(minutes=1)).time() else: raise ValidationError('No valid local time exists on this date.') else: validate_local_time(day, clock, task.time_zone) occurrence, _ = TaskOccurrence.objects.get_or_create( task=task, scheduled_date=day, defaults={'scheduled_time': clock, 'time_zone': task.time_zone}, ) if occurrence.status == TaskOccurrence.Status.PENDING and not occurrence.is_time_override and ( occurrence.scheduled_time != clock or occurrence.time_zone != task.time_zone ): occurrence.scheduled_time = clock occurrence.time_zone = task.time_zone occurrence.save(update_fields=['scheduled_time', 'time_zone', 'updated_at']) return occurrence def occurrence_for_user(user, task_id, day): task = Task.objects.get(pk=task_id, owner=user) return occurrence_for_date(task, day) @transaction.atomic def override_occurrence_time(user, task_id, day, clock): task = Task.objects.select_for_update().get(pk=task_id, owner=user) validate_local_time(day, clock, task.time_zone) occurrence = occurrence_for_date(task, day) occurrence.scheduled_time = clock occurrence.is_time_override = True occurrence.save(update_fields=['scheduled_time', 'is_time_override', 'updated_at']) return occurrence @transaction.atomic def set_occurrence_status(user, task_id, day, status, *, snoozed_until=None): if status not in TaskOccurrence.Status.values: raise ValidationError('Invalid occurrence status.') if status == TaskOccurrence.Status.SNOOZED and (snoozed_until is None or snoozed_until <= day): raise ValidationError('Choose a snooze date after the scheduled date.') task = Task.objects.select_for_update().get(pk=task_id, owner=user) occurrence = occurrence_for_date(task, day) previous = occurrence.status previous_snooze = occurrence.snoozed_until if previous != status or occurrence.snoozed_until != snoozed_until: occurrence.status = status occurrence.snoozed_until = snoozed_until if status == TaskOccurrence.Status.SNOOZED else None occurrence.save(update_fields=['status', 'snoozed_until', 'updated_at']) TaskOccurrenceEvent.objects.create( occurrence=occurrence, from_status=previous, to_status=status, from_snoozed_until=previous_snooze, to_snoozed_until=occurrence.snoozed_until, ) if not task.is_recurring and task.is_completed != (status == TaskOccurrence.Status.COMPLETED): task.is_completed = status == TaskOccurrence.Status.COMPLETED task.save(update_fields=['is_completed', 'updated_at']) return occurrence def upcoming_occurrences(task, start, count=8, horizon_days=3660): results = [] day = max(start, task.scheduled_for) end = day + timedelta(days=horizon_days) while day <= end and len(results) < count: if is_task_scheduled_on_date(task, day): results.append(occurrence_for_date(task, day)) day += timedelta(days=1) return results