from datetime import time from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.urls import reverse class Task(models.Model): class Priority(models.TextChoices): LOW = 'low', 'Low' MEDIUM = 'medium', 'Medium' HIGH = 'high', 'High' class RecurrenceUnit(models.TextChoices): DAY = 'day', 'Day' WEEK = 'week', 'Week' MONTH = 'month', 'Month' class DeferralSource(models.TextChoices): MANUAL = 'manual', 'Manual' MISSED = 'missed', 'Missed' SICK_DAY = 'sick_day', 'Sick day' WEATHER = 'weather', 'Weather' class WeatherProfile(models.TextChoices): ANY = 'none', 'Any weather' DRY = 'dry', 'Dry' SUNNY = 'sunny', 'Sunny / mostly sunny' WARM = 'warm', 'Warm' DRY_AND_WARM = 'dry_warm', 'Dry and warm' owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tasks', null=True, blank=True ) title = models.CharField(max_length=255) description = models.TextField(blank=True) estimated_duration_minutes = models.PositiveIntegerField(blank=True, null=True) priority = models.CharField(max_length=6, choices=Priority.choices, default=Priority.MEDIUM) category = models.CharField(max_length=100, blank=True) is_recurring = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_completed = models.BooleanField(default=False) scheduled_for = models.DateField() recurrence_interval = models.PositiveIntegerField(default=1, blank=True, null=True) recurrence_unit = models.CharField(max_length=5, choices=RecurrenceUnit.choices, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_outdoor = models.BooleanField(default=False) weather_profile = models.CharField( max_length=50, choices=WeatherProfile.choices, default=WeatherProfile.ANY ) required_on_sick_day = models.BooleanField(default=False) defer_days = models.PositiveIntegerField(blank=True, null=True) deferred_until = models.DateField(blank=True, null=True) deferral_source = models.CharField(max_length=20, choices=DeferralSource.choices, blank=True) parent_task = models.ForeignKey( 'self', blank=True, null=True, on_delete=models.SET_NULL, related_name='subtasks' ) class Meta: ordering = ('scheduled_for', 'title') def __str__(self): return self.title def get_absolute_url(self): return reverse('planner:task-detail', kwargs={'pk': self.pk}) def clean(self): super().clean() if not self.parent_task_id: return if self.owner_id and self.parent_task.owner_id and self.owner_id != self.parent_task.owner_id: raise ValidationError({'parent_task': 'A parent task must belong to the same user.'}) if self.pk and self.parent_task_id == self.pk: raise ValidationError({'parent_task': 'A task cannot be its own parent.'}) # Follow the proposed parent's ancestors. Finding this task means the # assignment would create a circular hierarchy. ancestor = self.parent_task visited_ids = set() while ancestor is not None: if ancestor.pk in visited_ids: break visited_ids.add(ancestor.pk) if self.pk and ancestor.pk == self.pk: raise ValidationError( {'parent_task': 'A task cannot have one of its descendants as its parent.'} ) ancestor = ancestor.parent_task class UserSettings(models.Model): """Private, per-user preferences that do not belong on Django's User model.""" user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='planner_settings' ) latitude = models.DecimalField( max_digits=9, decimal_places=6, blank=True, null=True, validators=[MinValueValidator(-90), MaxValueValidator(90)], ) longitude = models.DecimalField( max_digits=10, decimal_places=6, blank=True, null=True, validators=[MinValueValidator(-180), MaxValueValidator(180)], ) time_zone = models.CharField(max_length=64, default='Europe/Amsterdam') onboarding_enabled = models.BooleanField(default=True) onboarding_step = models.PositiveSmallIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def clean(self): super().clean() if (self.latitude is None) != (self.longitude is None): raise ValidationError('Enter both latitude and longitude, or leave both empty.') def __str__(self): return f'Planner settings for {self.user}' class TaskWeatherShift(models.Model): """A weather-owned move of a single scheduled task occurrence.""" task = models.ForeignKey(Task, on_delete=models.CASCADE, related_name='weather_shifts') owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='task_weather_shifts' ) original_date = models.DateField() shifted_to = models.DateField(blank=True, null=True) reason = models.CharField(max_length=255, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [ models.UniqueConstraint( fields=('task', 'original_date'), name='unique_weather_shift_per_task_occurrence' ) ] ordering = ('original_date',) def clean(self): super().clean() if self.task_id and self.owner_id and self.task.owner_id != self.owner_id: raise ValidationError({'owner': 'A weather shift must belong to the task owner.'}) def __str__(self): return f'{self.task} from {self.original_date}' class Workout(models.Model): """A personal, non-task workout entry or repeating daily workout intention.""" owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='workouts' ) name = models.CharField(max_length=255) scheduled_for = models.DateField() is_completed = models.BooleanField(default=False) duration_minutes = models.PositiveIntegerField(blank=True, null=True) calories_burned = models.PositiveIntegerField(blank=True, null=True) is_daily_recurring = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ('scheduled_for', 'name') def __str__(self): return self.name class WorkoutCompletion(models.Model): """Completion state for one date of a repeating daily workout.""" workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='completions') completed_on = models.DateField() completed_at = models.DateTimeField(auto_now_add=True) class Meta: constraints = [ models.UniqueConstraint( fields=('workout', 'completed_on'), name='unique_workout_completion_per_day', ) ] ordering = ('-completed_on',) def __str__(self): return f'{self.workout} completed on {self.completed_on}' class NeckHeadacheCheckIn(models.Model): """A private, once-per-local-day symptom check-in.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='neck_headache_check_ins', ) check_in_date = models.DateField() neck_pain_severity = models.PositiveSmallIntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], ) headache_severity = models.PositiveSmallIntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], ) note = models.CharField(max_length=500, blank=True) had_physiotherapy = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'check_in_date'), name='unique_neck_headache_check_in_per_day' ) ] ordering = ('-check_in_date',) def __str__(self): return f'Neck and headache check-in for {self.user} on {self.check_in_date}' class SleepCheckIn(models.Model): """A private, once-per-wake-up-date sleep check-in.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sleep_check_ins', ) wake_up_date = models.DateField() rested_score = models.PositiveSmallIntegerField( validators=[MinValueValidator(0), MaxValueValidator(10)], ) watch_sleep_score = models.PositiveSmallIntegerField( blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(100)], ) note = models.CharField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'wake_up_date'), name='unique_sleep_check_in_per_wake_up_date' ) ] ordering = ('-wake_up_date',) def __str__(self): return f'Sleep check-in for {self.user} on {self.wake_up_date}' class SickDaySettings(models.Model): """Per-user preferences used by the Sick Day deferral policy.""" user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='sick_day_settings', ) enabled = models.BooleanField(default=False) recovery_date = models.DateField(blank=True, null=True) def __str__(self): return f'Sick Day settings for {self.user}' class FastingSettings(models.Model): """A user's repeating daily intermittent-fasting configuration.""" user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fasting_settings', ) enabled = models.BooleanField(default=False) fasting_start_time = models.TimeField(default=time(20, 0)) fasting_duration_minutes = models.PositiveIntegerField( default=16 * 60, validators=[MinValueValidator(1), MaxValueValidator((24 * 60) - 1)], ) tracking_started_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'Fasting settings for {self.user}' class FastingPause(models.Model): """An interval during which a user's automatic fasting tracking was paused.""" user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fasting_pauses', ) paused_at = models.DateTimeField() resumed_at = models.DateTimeField(blank=True, null=True) class Meta: ordering = ('-paused_at',) def __str__(self): return f'Fasting pause for {self.user} at {self.paused_at}' class FastingPeriod(models.Model): class Status(models.TextChoices): COMPLETED = 'completed', 'Completed' user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='fasting_periods', ) scheduled_start = models.DateTimeField() scheduled_end = models.DateTimeField() completed_at = models.DateTimeField() status = models.CharField(max_length=16, choices=Status.choices, default=Status.COMPLETED) class Meta: constraints = [ models.UniqueConstraint( fields=('user', 'scheduled_start'), name='unique_user_fasting_scheduled_start', ) ] ordering = ('-scheduled_start',) def __str__(self): return f'Fasting period for {self.user}: {self.scheduled_start}'