first commit

This commit is contained in:
Joren de Graaf
2026-09-30 17:25:25 +02:00
commit 6baa19f11b
4271 changed files with 716371 additions and 0 deletions
View File
+48
View File
@@ -0,0 +1,48 @@
"""Display and streak helpers for private daily symptom check-ins."""
from dataclasses import dataclass
from datetime import timedelta
# Keeping this policy value here makes it straightforward to tune later.
LOW_PAIN_STREAK_THRESHOLD = 2
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE = 12
@dataclass(frozen=True)
class CheckInStreaks:
current: int
longest: int
def is_low_pain(check_in, threshold=LOW_PAIN_STREAK_THRESHOLD):
return (
check_in.neck_pain_severity <= threshold
and check_in.headache_severity <= threshold
)
def calculate_check_in_streaks(check_ins, as_of_date, threshold=LOW_PAIN_STREAK_THRESHOLD):
"""Return consecutive confirmed low-pain runs; absent dates always break a run."""
by_date = {check_in.check_in_date: check_in for check_in in check_ins}
if not by_date:
return CheckInStreaks(current=0, longest=0)
first_date = min(by_date)
longest = run = 0
day = first_date
while day <= as_of_date:
check_in = by_date.get(day)
if check_in is not None and is_low_pain(check_in, threshold):
run += 1
longest = max(longest, run)
else:
run = 0
day += timedelta(days=1)
current = 0
day = as_of_date
while (check_in := by_date.get(day)) is not None and is_low_pain(check_in, threshold):
current += 1
day -= timedelta(days=1)
return CheckInStreaks(current=current, longest=longest)
+132
View File
@@ -0,0 +1,132 @@
"""Deferral policies, deliberately separate from HTTP views and model saves."""
from datetime import date, timedelta
from typing import Iterable
from planner.models import SickDaySettings, Task
from planner.services.scheduling import is_task_scheduled_on_date
DEFERRAL_SOURCES = frozenset(Task.DeferralSource.values)
def extend_task_deferral(task: Task, deferred_until: date, source: str) -> bool:
"""Set a deferral only when it does not shorten an existing one.
The caller chooses the source when it extends a deferral. This is suitable
for an intentional manual deferral; automatic policies use their narrower
source-owning helpers below.
"""
if source not in DEFERRAL_SOURCES:
raise ValueError(f'Unsupported deferral source: {source}')
if not isinstance(deferred_until, date):
raise ValueError('deferred_until must be a date')
if task.deferred_until is not None and deferred_until <= task.deferred_until:
return False
task.deferred_until = deferred_until
task.deferral_source = source
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
return True
def defer_task_manually(task: Task, deferred_until: date) -> bool:
"""Apply a user-requested manual deferral without shortening an existing one."""
return extend_task_deferral(task, deferred_until, Task.DeferralSource.MANUAL)
def apply_missed_task_deferrals(tasks: Iterable[Task], selected_date: date) -> list[Task]:
"""Create or extend missed deferrals for overdue one-time tasks.
Existing manual or Sick Day deferrals are left untouched. A missed deferral
can only move later as the user views later dates.
"""
changed = []
for task in tasks:
if task.is_recurring or not task.defer_days or task.scheduled_for >= selected_date:
continue
if task.deferral_source not in ('', Task.DeferralSource.MISSED):
continue
target_date = selected_date + timedelta(days=task.defer_days)
if task.deferred_until is not None and target_date <= task.deferred_until:
continue
task.deferred_until = target_date
task.deferral_source = Task.DeferralSource.MISSED
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
changed.append(task)
return changed
def sick_day_applies(settings: SickDaySettings | None, selected_date: date) -> bool:
"""Whether a user's Sick Day Mode applies to the selected calendar date."""
return bool(
settings
and settings.enabled
and (settings.recovery_date is None or selected_date <= settings.recovery_date)
)
def sick_day_target_date(settings: SickDaySettings, selected_date: date) -> date:
"""Return the date to which Sick Day work should be deferred."""
base_date = settings.recovery_date or selected_date
return base_date + timedelta(days=1)
def is_sick_day_suppressed(
task: Task, settings: SickDaySettings | None, selected_date: date
) -> bool:
"""Hide normally scheduled non-essential work without touching other sources."""
return (
sick_day_applies(settings, selected_date)
and not task.required_on_sick_day
and task.deferral_source != Task.DeferralSource.SICK_DAY
and is_task_scheduled_on_date(task, selected_date)
)
def sync_sick_day_deferrals(
tasks: Iterable[Task], settings: SickDaySettings | None, selected_date: date
) -> list[Task]:
"""Synchronize only deferrals owned by Sick Day Mode.
Recovery-date changes can move Sick Day deferrals in either direction. When
disabled, only Sick Day deferrals are removed; manual and missed deferrals
are deliberately never changed by this function.
"""
changed = []
task_list = list(tasks)
if settings is None or not settings.enabled:
for task in task_list:
if task.deferral_source == Task.DeferralSource.SICK_DAY:
task.deferred_until = None
task.deferral_source = ''
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
changed.append(task)
return changed
target_date = sick_day_target_date(settings, selected_date)
applies = sick_day_applies(settings, selected_date)
for task in task_list:
if task.required_on_sick_day:
if task.deferral_source == Task.DeferralSource.SICK_DAY:
task.deferred_until = None
task.deferral_source = ''
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
changed.append(task)
continue
if task.deferral_source == Task.DeferralSource.SICK_DAY:
if task.deferred_until != target_date:
task.deferred_until = target_date
task.save(update_fields=['deferred_until', 'updated_at'])
changed.append(task)
continue
if applies and task.deferral_source == '' and is_task_scheduled_on_date(task, selected_date):
task.deferred_until = target_date
task.deferral_source = Task.DeferralSource.SICK_DAY
task.save(update_fields=['deferred_until', 'deferral_source', 'updated_at'])
changed.append(task)
return changed
+193
View File
@@ -0,0 +1,193 @@
"""Intermittent-fasting schedule and history synchronization policies."""
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from django.db import IntegrityError, transaction
from django.utils import timezone
from planner.models import FastingPause, FastingPeriod, FastingSettings
from planner.timezones import timezone_for_user
@dataclass(frozen=True)
class ScheduledFastingPeriod:
scheduled_start: datetime
scheduled_end: datetime
@dataclass(frozen=True)
class FastingPhase:
name: str
scheduled_start: datetime
scheduled_end: datetime
cycle_start: datetime
cycle_end: datetime
@property
def is_fasting(self) -> bool:
return self.name == 'fasting'
def current_timezone(user=None):
"""Use the saved timezone when a user is known, otherwise Django's active zone."""
return timezone_for_user(user) if user is not None else timezone.get_current_timezone()
def scheduled_fasting_period(
settings: FastingSettings, start_date: date, tz=None
) -> ScheduledFastingPeriod:
"""Build one scheduled daily fasting period in the active Django timezone."""
tz = tz or current_timezone(settings.user)
start = timezone.make_aware(
datetime.combine(start_date, settings.fasting_start_time), timezone=tz
)
end = start + timedelta(minutes=settings.fasting_duration_minutes)
return ScheduledFastingPeriod(start, end)
def current_fasting_phase(
settings: FastingSettings, now: datetime | None = None
) -> FastingPhase:
"""Return the current fasting/eating phase from the repeating daily schedule."""
now = now or timezone.now()
tz = current_timezone(settings.user)
local_now = timezone.localtime(now, tz)
local_time = local_now.timetz().replace(tzinfo=None)
start_date = local_now.date()
if local_time < settings.fasting_start_time:
start_date -= timedelta(days=1)
period = scheduled_fasting_period(settings, start_date, tz)
if period.scheduled_start <= now < period.scheduled_end:
return FastingPhase(
'fasting',
period.scheduled_start,
period.scheduled_end,
period.scheduled_start,
period.scheduled_end,
)
# The eating cycle starts as the fast ends and resets at the next daily fast.
next_fasting_start = period.scheduled_start + timedelta(days=1)
return FastingPhase(
'eating',
period.scheduled_start,
period.scheduled_end,
period.scheduled_end,
next_fasting_start,
)
def _period_overlaps_pause(
user, period: ScheduledFastingPeriod, now: datetime
) -> bool:
pauses = FastingPause.objects.filter(user=user, paused_at__lt=period.scheduled_end)
for pause in pauses:
pause_end = pause.resumed_at or now
if pause_end > period.scheduled_start:
return True
return False
def validate_fasting_duration(value: int) -> None:
if isinstance(value, bool) or not isinstance(value, int) or not 1 <= value < 24 * 60:
raise ValueError('Fasting duration must be between 1 and 1439 minutes.')
def configure_fasting(
user,
*,
enabled: bool,
fasting_start_time,
fasting_duration_minutes: int,
now: datetime | None = None,
) -> FastingSettings:
"""Create or update configuration and record any transition into a pause."""
validate_fasting_duration(fasting_duration_minutes)
now = now or timezone.now()
settings, created = FastingSettings.objects.get_or_create(
user=user,
defaults={
'enabled': enabled,
'fasting_start_time': fasting_start_time,
'fasting_duration_minutes': fasting_duration_minutes,
'tracking_started_at': now if enabled else None,
},
)
if created:
if not enabled:
FastingPause.objects.create(user=user, paused_at=now)
return settings
was_enabled = settings.enabled
settings.fasting_start_time = fasting_start_time
settings.fasting_duration_minutes = fasting_duration_minutes
settings.enabled = enabled
if enabled and settings.tracking_started_at is None:
settings.tracking_started_at = now
settings.save()
if was_enabled and not enabled:
FastingPause.objects.get_or_create(user=user, resumed_at__isnull=True, defaults={'paused_at': now})
elif not was_enabled and enabled:
FastingPause.objects.filter(user=user, resumed_at__isnull=True).update(resumed_at=now)
return settings
def set_fasting_tracking_enabled(
settings: FastingSettings, enabled: bool, now: datetime | None = None
) -> FastingSettings:
"""Pause or resume tracking while preserving the configured daily schedule."""
return configure_fasting(
settings.user,
enabled=enabled,
fasting_start_time=settings.fasting_start_time,
fasting_duration_minutes=settings.fasting_duration_minutes,
now=now,
)
def synchronize_fasting_periods(
settings: FastingSettings | None, now: datetime | None = None
) -> list[FastingPeriod]:
"""Idempotently record completed scheduled periods that were fully tracked.
This function can be called from a request today and a background job later.
It never creates records while paused or for any schedule period overlapping
a recorded pause interval.
"""
if settings is None or not settings.enabled or settings.tracking_started_at is None:
return []
now = now or timezone.now()
tz = current_timezone(settings.user)
started_local = timezone.localtime(settings.tracking_started_at, tz)
current_local = timezone.localtime(now, tz)
created_periods = []
candidate_date = started_local.date()
while candidate_date <= current_local.date():
period = scheduled_fasting_period(settings, candidate_date, tz)
candidate_date += timedelta(days=1)
if period.scheduled_start < settings.tracking_started_at:
continue
if period.scheduled_end > now or _period_overlaps_pause(settings.user, period, now):
continue
try:
with transaction.atomic():
history, created = FastingPeriod.objects.get_or_create(
user=settings.user,
scheduled_start=period.scheduled_start,
defaults={
'scheduled_end': period.scheduled_end,
'completed_at': now,
'status': FastingPeriod.Status.COMPLETED,
},
)
except IntegrityError:
# The uniqueness constraint makes concurrent synchronization safe.
continue
if created:
created_periods.append(history)
return created_periods
+193
View File
@@ -0,0 +1,193 @@
"""Reusable scheduling and recommendation decisions for the task planner."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date, timedelta
from typing import TYPE_CHECKING, Iterable
from planner.models import Task, TaskWeatherShift
if TYPE_CHECKING:
from planner.models import SickDaySettings
ENERGY_BUDGETS = {1: 15, 2: 30, 3: 60, 4: 90, 5: 180}
DEFAULT_ENERGY_LEVEL = 3
@dataclass(frozen=True)
class RecommendedTaskGroup:
"""One independently recommended top-level task and its eligible subtasks."""
task: Task
subtasks: tuple[Task, ...]
def normalize_energy_level(value: object) -> int:
try:
level = int(value)
except (TypeError, ValueError):
return DEFAULT_ENERGY_LEVEL
return max(min(level, max(ENERGY_BUDGETS)), min(ENERGY_BUDGETS))
def duration_budget_for_energy(value: object) -> int:
return ENERGY_BUDGETS[normalize_energy_level(value)]
def is_task_scheduled_on_date(task: Task, selected_date: date) -> bool:
anchor = task.scheduled_for
if not isinstance(anchor, date) or not isinstance(selected_date, date):
return False
if not task.is_recurring:
return selected_date == anchor
interval = task.recurrence_interval
if not isinstance(interval, int) or isinstance(interval, bool) or interval <= 0 or selected_date < anchor:
return False
if task.recurrence_unit == Task.RecurrenceUnit.DAY:
return (selected_date - anchor).days % interval == 0
if task.recurrence_unit == Task.RecurrenceUnit.WEEK:
return (selected_date - anchor).days % (interval * 7) == 0
if task.recurrence_unit == Task.RecurrenceUnit.MONTH:
if selected_date.day != anchor.day:
return False
distance = (selected_date.year - anchor.year) * 12 + selected_date.month - anchor.month
return distance >= 0 and distance % interval == 0
return False
def is_task_eligible(task: Task, selected_date: date) -> bool:
if not isinstance(selected_date, date):
return False
if task.deferred_until is not None:
if selected_date < task.deferred_until:
return False
if selected_date == task.deferred_until:
return True
return is_task_scheduled_on_date(task, selected_date)
def task_recommendation_key(task: Task, energy_level: object) -> tuple:
budget = duration_budget_for_energy(energy_level)
duration = task.estimated_duration_minutes
has_duration = duration is not None
exceeds_budget = has_duration and duration > budget
if not has_duration:
preference = float('inf')
elif normalize_energy_level(energy_level) <= 2:
preference = duration
elif duration <= budget:
preference = budget - duration
else:
preference = duration - budget
return (not task.is_active, not task.is_recurring, not has_duration,
exceeds_budget if has_duration else True, preference, task.title.casefold())
def _weather_shift_for_date(task: Task, selected_date: date):
return task.weather_shifts.filter(shifted_to=selected_date).first()
def _find_weather_target(task: Task, owner, original_date: date):
"""Find the first forecast-supported vacancy for one weather-blocked occurrence."""
from planner.services.weather import (
FORECAST_SEARCH_HORIZON_DAYS, evaluate_weather_suitability, forecast_for_user_on_date,
)
for offset in range(1, FORECAST_SEARCH_HORIZON_DAYS + 1):
candidate = original_date + timedelta(days=offset)
# An occurrence may not be moved onto another natural or already moved occurrence.
if is_task_scheduled_on_date(task, candidate):
continue
if task.weather_shifts.filter(shifted_to=candidate).exclude(original_date=original_date).exists():
continue
outcome = evaluate_weather_suitability(task, forecast_for_user_on_date(owner, candidate))
if outcome.status == 'suitable':
return candidate, outcome.reason
return None, 'Waiting for a suitable weather forecast.'
def is_weather_eligible(task: Task, selected_date: date, owner) -> bool:
"""Apply weather-owned occurrence moves without changing recurrence anchors.
Manual, missed, and Sick Day deferrals are intentionally evaluated first and
are never replaced by weather state. Unknown weather remains visible.
"""
if owner is None or task.weather_profile == Task.WeatherProfile.ANY:
return is_task_eligible(task, selected_date)
moved = _weather_shift_for_date(task, selected_date)
if moved is not None:
task.weather_shift_reason = moved.reason
task.weather_shifted_from = moved.original_date
return True
if not is_task_eligible(task, selected_date):
return False
if task.deferred_until is not None and task.deferral_source != Task.DeferralSource.WEATHER:
return True
if not is_task_scheduled_on_date(task, selected_date):
return True
existing = task.weather_shifts.filter(original_date=selected_date).first()
if existing is not None:
# The source is weather-owned, so it can be recalculated without touching other deferrals.
target, reason = _find_weather_target(task, owner, selected_date)
if existing.shifted_to != target or existing.reason != reason:
existing.shifted_to, existing.reason = target, reason
existing.save(update_fields=['shifted_to', 'reason', 'updated_at'])
return False
from planner.services.weather import evaluate_weather_suitability, forecast_for_user_on_date
outcome = evaluate_weather_suitability(task, forecast_for_user_on_date(owner, selected_date))
if outcome.status != 'unsuitable':
if outcome.status == 'unknown':
task.weather_shift_reason = outcome.reason
return True
target, reason = _find_weather_target(task, owner, selected_date)
TaskWeatherShift.objects.create(
task=task, owner=owner, original_date=selected_date, shifted_to=target,
reason=f'{outcome.reason} {reason}',
)
return False
def recommend_tasks(top_level_tasks: Iterable[Task], selected_date: date, energy_level: object,
sick_day_settings: 'SickDaySettings | None' = None, *, user=None) -> list[RecommendedTaskGroup]:
"""Recommend parent tasks first; completed parents unlock their subtasks."""
from planner.services.deferrals import is_sick_day_suppressed
candidates = []
for parent in top_level_tasks:
if parent.is_completed:
candidates.extend(
subtask for subtask in parent.subtasks.all()
if is_weather_eligible(subtask, selected_date, user)
and not is_sick_day_suppressed(subtask, sick_day_settings, selected_date)
)
elif (
is_weather_eligible(parent, selected_date, user)
and not is_sick_day_suppressed(parent, sick_day_settings, selected_date)
):
candidates.append(parent)
candidates.sort(key=lambda task: task_recommendation_key(task, energy_level))
return [RecommendedTaskGroup(task, ()) for task in candidates]
def daily_recommendations(user, selected_date: date | object = None, energy_level: object = None,
sick_day_settings: 'SickDaySettings | None' = None) -> list[RecommendedTaskGroup]:
"""Load one user's tasks and apply deferral and weather policies.
The legacy three-argument shape remains temporarily supported for existing
service callers; normal application code always passes the authenticated user.
"""
if isinstance(user, date):
user, selected_date, energy_level, sick_day_settings = None, user, selected_date, energy_level
from planner.services.deferrals import apply_missed_task_deferrals, sync_sick_day_deferrals
queryset = Task.objects.filter(parent_task__isnull=True)
if user is not None:
queryset = queryset.filter(owner=user)
top_level_tasks = list(queryset.prefetch_related('subtasks', 'weather_shifts'))
all_tasks = [task for parent in top_level_tasks for task in (parent, *parent.subtasks.all())]
apply_missed_task_deferrals(all_tasks, selected_date)
sync_sick_day_deferrals(all_tasks, sick_day_settings, selected_date)
return recommend_tasks(top_level_tasks, selected_date, energy_level, sick_day_settings, user=user)
+197
View File
@@ -0,0 +1,197 @@
"""Open-Meteo integration and weather suitability policy.
The rest of the planner only consumes DailyForecast instances, never Open-Meteo JSON.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
import json
from typing import Iterable
from urllib.parse import urlencode
from urllib.request import urlopen
from django.core.cache import cache
from planner.models import Task, UserSettings
OPEN_METEO_URL = 'https://api.open-meteo.com/v1/forecast'
FORECAST_SEARCH_HORIZON_DAYS = 16
FORECAST_CACHE_SECONDS = 12 * 60 * 60
MEANINGFUL_PRECIPITATION_PROBABILITY = 40
MEANINGFUL_PRECIPITATION_MM = 0.5
SUNNY_MINIMUM_SECONDS = 4 * 60 * 60
WARM_MINIMUM_TEMPERATURE_C = 15.0
@dataclass(frozen=True)
class DailyForecast:
forecast_date: date
condition: str
precipitation_probability: float | None
precipitation_mm: float | None
temperature_min_c: float | None
temperature_max_c: float | None
wind_speed_max_kmh: float | None
sunshine_seconds: float | None
@dataclass(frozen=True)
class WeatherSuitability:
status: str # suitable, unsuitable, unknown
reason: str
@property
def is_suitable(self) -> bool:
return self.status == 'suitable'
class WeatherServiceError(Exception):
"""Open-Meteo could not provide a usable forecast."""
def wmo_condition(code: int | None) -> str:
"""Map Open-Meteo WMO codes into stable application-level conditions."""
if code == 0:
return 'clear'
if code in (1, 2):
return 'partly_cloudy'
if code == 3:
return 'cloudy'
if code in (45, 48):
return 'fog'
if code in (51, 53, 55, 56, 57, 80, 81):
return 'rain'
if code in (61, 63, 66, 80):
return 'rain'
if code in (65, 67, 82):
return 'heavy_rain'
if code in (71, 73, 75, 77, 85, 86):
return 'snow'
if code in (95, 96, 99):
return 'thunderstorm'
return 'unknown'
WEATHER_ICON_NAMES = {
'clear': '☀', 'partly_cloudy': '⛅', 'cloudy': '☁', 'fog': '🌫',
'rain': '🌦', 'heavy_rain': '🌧', 'thunderstorm': '⛈', 'snow': '❄', 'unknown': '◌',
}
WEATHER_LABELS = {
'clear': 'Clear', 'partly_cloudy': 'Partly cloudy', 'cloudy': 'Cloudy', 'fog': 'Foggy',
'rain': 'Rain', 'heavy_rain': 'Heavy rain', 'thunderstorm': 'Thunderstorms',
'snow': 'Snow', 'unknown': 'Unknown conditions',
}
def _as_number(values: list, index: int) -> float | None:
try:
value = values[index]
except (IndexError, TypeError):
return None
return float(value) if value is not None else None
def normalize_open_meteo_response(payload: dict) -> list[DailyForecast]:
"""Convert Open-Meteo's daily arrays into application forecast records."""
daily = payload.get('daily') or {}
dates = daily.get('time') or []
forecasts = []
for index, value in enumerate(dates):
try:
forecast_date = date.fromisoformat(value)
except (TypeError, ValueError):
continue
code = _as_number(daily.get('weather_code', []), index)
forecasts.append(DailyForecast(
forecast_date=forecast_date,
condition=wmo_condition(int(code) if code is not None else None),
precipitation_probability=_as_number(daily.get('precipitation_probability_max', []), index),
precipitation_mm=_as_number(daily.get('precipitation_sum', []), index),
temperature_min_c=_as_number(daily.get('temperature_2m_min', []), index),
temperature_max_c=_as_number(daily.get('temperature_2m_max', []), index),
wind_speed_max_kmh=_as_number(daily.get('wind_speed_10m_max', []), index),
sunshine_seconds=_as_number(daily.get('sunshine_duration', []), index),
))
return forecasts
def fetch_open_meteo_forecasts(latitude: Decimal | float, longitude: Decimal | float) -> list[DailyForecast]:
"""Fetch one normalized finite daily forecast from Open-Meteo."""
params = urlencode({
'latitude': str(latitude), 'longitude': str(longitude),
'daily': 'weather_code,precipitation_probability_max,precipitation_sum,temperature_2m_min,temperature_2m_max,wind_speed_10m_max,sunshine_duration',
'forecast_days': FORECAST_SEARCH_HORIZON_DAYS, 'timezone': 'auto',
})
try:
with urlopen(f'{OPEN_METEO_URL}?{params}', timeout=5) as response: # nosec B310 - fixed HTTPS endpoint
payload = json.loads(response.read().decode('utf-8'))
except (OSError, ValueError, json.JSONDecodeError) as error:
raise WeatherServiceError('Weather forecast is unavailable.') from error
return normalize_open_meteo_response(payload)
def _forecast_cache_key(user_id: int, latitude: Decimal, longitude: Decimal) -> str:
return f'planner:weather:{user_id}:{latitude}:{longitude}'
def forecasts_for_user(user) -> list[DailyForecast] | None:
"""Return cached normalized forecasts, or None when location/API is unavailable."""
settings = UserSettings.objects.filter(user=user).first()
if settings is None or settings.latitude is None or settings.longitude is None:
return None
key = _forecast_cache_key(user.pk, settings.latitude, settings.longitude)
cached = cache.get(key)
if cached is not None:
return cached
try:
forecasts = fetch_open_meteo_forecasts(settings.latitude, settings.longitude)
except WeatherServiceError:
return None
cache.set(key, forecasts, FORECAST_CACHE_SECONDS)
return forecasts
def forecast_for_user_on_date(user, selected_date: date) -> DailyForecast | None:
forecasts = forecasts_for_user(user)
if forecasts is None:
return None
return next((forecast for forecast in forecasts if forecast.forecast_date == selected_date), None)
def evaluate_weather_suitability(task: Task, forecast: DailyForecast | None) -> WeatherSuitability:
"""Evaluate a task profile with centralized, explainable weather thresholds."""
profile = task.weather_profile
if profile == Task.WeatherProfile.ANY:
return WeatherSuitability('suitable', 'Any weather is suitable.')
if forecast is None:
return WeatherSuitability('unknown', 'Weather forecast unavailable.')
rainy = (
(forecast.precipitation_probability is not None and forecast.precipitation_probability >= MEANINGFUL_PRECIPITATION_PROBABILITY)
or (forecast.precipitation_mm is not None and forecast.precipitation_mm >= MEANINGFUL_PRECIPITATION_MM)
)
dry = not rainy
sunny = dry and forecast.condition in {'clear', 'partly_cloudy'} and (
forecast.sunshine_seconds is not None and forecast.sunshine_seconds >= SUNNY_MINIMUM_SECONDS
)
warm = forecast.temperature_max_c is not None and forecast.temperature_max_c >= WARM_MINIMUM_TEMPERATURE_C
if profile == Task.WeatherProfile.DRY:
return WeatherSuitability('suitable', f'Dry forecast.') if dry else WeatherSuitability('unsuitable', 'Rain expected.')
if profile == Task.WeatherProfile.SUNNY:
return WeatherSuitability('suitable', 'Sunny and dry forecast.') if sunny else WeatherSuitability('unsuitable', 'Not sunny and dry enough.')
if profile == Task.WeatherProfile.WARM:
return WeatherSuitability('suitable', f'Warm, up to {forecast.temperature_max_c:g} °C.') if warm else WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
if profile == Task.WeatherProfile.DRY_AND_WARM:
if not dry:
return WeatherSuitability('unsuitable', 'Rain expected.')
if not warm:
return WeatherSuitability('unsuitable', f'Below {WARM_MINIMUM_TEMPERATURE_C:g} °C.')
return WeatherSuitability('suitable', f'Dry and warm, up to {forecast.temperature_max_c:g} °C.')
return WeatherSuitability('unknown', 'Unknown weather preference.')
def weather_profile_label(task: Task) -> str:
return task.get_weather_profile_display()
+54
View File
@@ -0,0 +1,54 @@
"""Workout daily-occurrence policy, separate from task scheduling."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from django.db.models import Q
from planner.models import Workout, WorkoutCompletion
@dataclass(frozen=True)
class DailyWorkoutSummary:
workouts: tuple[Workout, ...]
calories_total: int | None
completed_without_calories: int
def workouts_for_day(user, selected_date: date) -> DailyWorkoutSummary:
"""Return this user's one-time and repeating workout occurrences for a day."""
workouts = list(
Workout.objects.filter(owner=user)
.filter(Q(is_daily_recurring=True, scheduled_for__lte=selected_date) | Q(is_daily_recurring=False, scheduled_for=selected_date))
.prefetch_related('completions')
)
total = 0
completed_with_calories = 0
completed_without_calories = 0
for workout in workouts:
completed = workout.completions.filter(completed_on=selected_date).exists() if workout.is_daily_recurring else workout.is_completed
workout.completed_for_day = completed
workout.occurrence_date = selected_date
if completed:
if workout.calories_burned is None:
completed_without_calories += 1
else:
total += workout.calories_burned
completed_with_calories += 1
workouts.sort(key=lambda item: (item.completed_for_day, item.name.casefold()))
return DailyWorkoutSummary(tuple(workouts), total if completed_with_calories else None, completed_without_calories)
def toggle_workout_completion(workout: Workout, selected_date: date) -> bool:
"""Toggle one displayed occurrence and return its new completion status."""
if workout.is_daily_recurring:
completion = WorkoutCompletion.objects.filter(workout=workout, completed_on=selected_date).first()
if completion is not None:
completion.delete()
return False
WorkoutCompletion.objects.create(workout=workout, completed_on=selected_date)
return True
workout.is_completed = not workout.is_completed
workout.save(update_fields=['is_completed', 'updated_at'])
return workout.is_completed