Files
Django_TasksApp/main/planner/models.py
T

417 lines
16 KiB
Python

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
from django.utils import timezone
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."""
class Appearance(models.TextChoices):
LIGHT = 'light', 'Light'
DARK = 'dark', 'Dark'
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')
appearance = models.CharField(
max_length=5, choices=Appearance.choices, default=Appearance.LIGHT,
)
onboarding_enabled = models.BooleanField(default=True)
onboarding_step = models.PositiveSmallIntegerField(default=0)
daily_water_goal_ml = models.PositiveIntegerField(
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)],
)
daily_calorie_goal = models.PositiveIntegerField(null=True, blank=True)
carbohydrate_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)])
protein_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)])
fat_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)])
fibre_goal_g = models.DecimalField(max_digits=7, decimal_places=1, default=40, validators=[MinValueValidator(0)])
ntfy_url = models.URLField(blank=True)
ntfy_enabled = models.BooleanField(default=False)
ntfy_last_tested_at = models.DateTimeField(null=True, blank=True)
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()
PERIODS = (
('morning', 'Morning', 'M'),
('afternoon', 'Afternoon', 'A'),
('evening', 'Evening', 'E'),
)
morning_neck_pain_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
morning_headache_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
morning_note = models.TextField(max_length=500, blank=True)
afternoon_neck_pain_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
afternoon_headache_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
afternoon_note = models.TextField(max_length=500, blank=True)
evening_neck_pain_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
evening_headache_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
evening_note = models.TextField(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 ToothBrushing(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='tooth_brushing')
date = models.DateField()
morning = models.BooleanField(default=False)
evening = models.BooleanField(default=False)
class Meta:
constraints = [models.UniqueConstraint(fields=('user', 'date'), name='unique_tooth_brushing_per_day')]
ordering = ('-date',)
class BowelHealthCheckIn(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='bowel_health_check_ins')
check_in_date = models.DateField()
morning_severity = models.PositiveSmallIntegerField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)])
morning_note = models.TextField(max_length=500, blank=True)
afternoon_severity = models.PositiveSmallIntegerField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)])
afternoon_note = models.TextField(max_length=500, blank=True)
evening_severity = models.PositiveSmallIntegerField(blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)])
evening_note = models.TextField(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', 'check_in_date'), name='unique_bowel_health_check_in_per_day')]
ordering = ('-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)
last_phase_notification_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 WaterIntakeEntry(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='water_entries')
amount_ml = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(3000)])
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-recorded_at', '-pk')
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}'