202 lines
7.0 KiB
Python
202 lines
7.0 KiB
Python
"""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,
|
|
'last_phase_notification_at': now,
|
|
},
|
|
)
|
|
if created:
|
|
if not enabled:
|
|
FastingPause.objects.create(user=user, paused_at=now)
|
|
return settings
|
|
|
|
was_enabled = settings.enabled
|
|
schedule_changed = (
|
|
settings.fasting_start_time != fasting_start_time
|
|
or settings.fasting_duration_minutes != fasting_duration_minutes
|
|
or was_enabled != enabled
|
|
)
|
|
settings.fasting_start_time = fasting_start_time
|
|
settings.fasting_duration_minutes = fasting_duration_minutes
|
|
settings.enabled = enabled
|
|
if schedule_changed:
|
|
settings.last_phase_notification_at = now
|
|
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
|