Add task occurrence scheduling and card completion workflow

This commit is contained in:
Joren de Graaf
2026-10-28 21:05:32 +01:00
parent 22d9757ddd
commit 2f84a9f359
15 changed files with 526 additions and 9 deletions
+107
View File
@@ -0,0 +1,107 @@
"""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
+12 -2
View File
@@ -5,7 +5,7 @@ from dataclasses import dataclass
from datetime import date, timedelta
from typing import TYPE_CHECKING, Iterable
from planner.models import Task, TaskWeatherShift
from planner.models import Task, TaskOccurrence, TaskWeatherShift
if TYPE_CHECKING:
from planner.models import SickDaySettings
@@ -62,6 +62,12 @@ def is_task_eligible(task: Task, selected_date: date) -> bool:
return False
if selected_date == task.deferred_until:
return True
if task.occurrences.filter(status=TaskOccurrence.Status.SNOOZED, snoozed_until=selected_date).exists():
return True
if task.occurrences.filter(scheduled_date=selected_date, status__in=(
TaskOccurrence.Status.COMPLETED, TaskOccurrence.Status.SKIPPED, TaskOccurrence.Status.SNOOZED,
)).exists():
return False
return is_task_scheduled_on_date(task, selected_date)
@@ -156,14 +162,18 @@ def recommend_tasks(top_level_tasks: Iterable[Task], selected_date: date, energy
candidates = []
for parent in top_level_tasks:
if parent.is_completed:
occurrence = parent.occurrences.filter(scheduled_date=selected_date).first() if parent.is_recurring else None
completed_today = occurrence and occurrence.status == TaskOccurrence.Status.COMPLETED
if parent.is_completed or completed_today:
candidates.extend(
subtask for subtask in parent.subtasks.all()
if is_weather_eligible(subtask, selected_date, user)
and not subtask.occurrences.filter(scheduled_date=selected_date, status=TaskOccurrence.Status.COMPLETED).exists()
and not is_sick_day_suppressed(subtask, sick_day_settings, selected_date)
)
elif (
is_weather_eligible(parent, selected_date, user)
and not completed_today
and not is_sick_day_suppressed(parent, sick_day_settings, selected_date)
):
candidates.append(parent)