Files
Django_TasksApp/main/planner/forms.py
T

340 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.utils import timezone
from zoneinfo import available_timezones
from .models import BowelHealthCheckIn, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
from .timezones import localdate_for_user
class TaskForm(forms.ModelForm):
class Meta:
model = Task
fields = (
'title', 'description', 'estimated_duration_minutes', 'priority', 'category',
'scheduled_for', 'is_recurring', 'recurrence_interval', 'recurrence_unit',
'defer_days', 'is_active', 'is_outdoor', 'weather_profile', 'required_on_sick_day', 'parent_task',
)
widgets = {
'description': forms.Textarea(attrs={'rows': 5}),
'scheduled_for': forms.DateInput(attrs={'type': 'date'}),
}
def __init__(self, *args, owner=None, **kwargs):
super().__init__(*args, **kwargs)
self.owner = owner
parents = Task.objects.filter(parent_task__isnull=True)
if owner is not None:
parents = parents.filter(owner=owner)
if self.instance.pk:
# Keeping choices top-level prevents accidental deep nesting in the UI.
parents = parents.exclude(pk=self.instance.pk)
self.fields['parent_task'].queryset = parents
self.fields['defer_days'].help_text = 'Days to defer this one-time task after it is missed.'
category_id = self['category'].id_for_label
self.fields['category'].widget.attrs.update({
'autocomplete': 'off',
'role': 'combobox',
'aria-autocomplete': 'list',
'aria-expanded': 'false',
'aria-controls': f'{category_id}-suggestions',
'aria-haspopup': 'listbox',
'data-category-input': '',
'data-suggestions-url': reverse('planner:category-suggestions'),
})
def clean_category(self):
category = self.cleaned_data['category'].strip()
if not category or self.owner is None:
return category
for existing_category in Task.objects.filter(owner=self.owner).exclude(category='').order_by('pk').values_list('category', flat=True):
normalized = existing_category.strip()
if normalized.casefold() == category.casefold():
return normalized
return category
class DailyPlannerForm(forms.Form):
selected_date = forms.DateField(
label='Plan for',
widget=forms.DateInput(attrs={'type': 'date'}),
)
energy_level = forms.TypedChoiceField(
label='Energy level',
coerce=int,
choices=(
(1, '1 — Very low (15 min)'),
(2, '2 — Low (30 min)'),
(3, '3 — Steady (60 min)'),
(4, '4 — High (90 min)'),
(5, '5 — Fully charged (180 min)'),
),
)
DAILY_FASTING_DURATION_CHOICES = (
('Beginner', (
(12 * 60, '12:12 — Fast 12 hours, eat within 12 hours'),
(13 * 60, '13:11 — Fast 13 hours, eat within 11 hours'),
(14 * 60, '14:10 — Fast 14 hours, eat within 10 hours'),
(15 * 60, '15:9 — Fast 15 hours, eat within 9 hours'),
)),
('Experienced', (
(16 * 60, '16:8 — Fast 16 hours, eat within 8 hours'),
(17 * 60, '17:7 — Fast 17 hours, eat within 7 hours'),
(18 * 60, '18:6 — Fast 18 hours, eat within 6 hours'),
)),
('Professional', (
(19 * 60, '19:5 — Fast 19 hours, eat within 5 hours'),
(20 * 60, '20:4 — Fast 20 hours, eat within 4 hours'),
(21 * 60, '21:3 — Fast 21 hours, eat within 3 hours'),
(22 * 60, '22:2 — Fast 22 hours, eat within 2 hours'),
)),
)
class FastingSettingsForm(forms.ModelForm):
fasting_duration_minutes = forms.TypedChoiceField(
label='Daily fasting schedule',
choices=DAILY_FASTING_DURATION_CHOICES,
coerce=int,
help_text='Choose a daily fasting and eating-window rhythm.',
)
class Meta:
model = FastingSettings
fields = ('enabled', 'fasting_start_time', 'fasting_duration_minutes')
widgets = {
'fasting_start_time': forms.TimeInput(attrs={'type': 'time'}),
}
labels = {
'fasting_start_time': 'Fasting starts at',
}
help_texts = {
}
TIME_ZONE_CHOICES = tuple((name, name) for name in sorted(available_timezones()))
class TimeZoneSettingsForm(forms.ModelForm):
time_zone = forms.ChoiceField(label='Time zone', choices=TIME_ZONE_CHOICES)
class Meta:
model = UserSettings
fields = ('time_zone',)
help_texts = {
'time_zone': 'Used for dates and displayed times, including fasting.',
}
class UserSettingsForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('latitude', 'longitude')
widgets = {
'latitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 52.36760'}),
'longitude': forms.TextInput(attrs={'inputmode': 'decimal', 'autocomplete': 'off', 'placeholder': 'e.g. 4.90410'}),
}
help_texts = {
'latitude': 'Between -90 and 90.',
'longitude': 'Between -180 and 180.',
}
class NtfySettingsForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('ntfy_url', 'ntfy_enabled')
widgets = {'ntfy_url': forms.URLInput(attrs={'id': 'ntfy-url', 'placeholder': 'https://ntfy.example.com/my-topic'})}
def clean_ntfy_url(self):
return self.cleaned_data['ntfy_url'].strip()
def clean(self):
data = super().clean()
if data.get('ntfy_enabled') and not data.get('ntfy_url'):
self.add_error('ntfy_url', 'Enter a topic URL before enabling notifications.')
return data
class HydrationGoalForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('daily_water_goal_ml',)
labels = {'daily_water_goal_ml': 'Daily water goal (ml)'}
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})}
class FoodGoalForm(forms.ModelForm):
class Meta:
model = UserSettings
fields = ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g', 'fibre_goal_g')
labels = {
'daily_calorie_goal': 'Daily calorie goal (kcal)',
'carbohydrate_goal_g': 'Daily carbohydrate target (g)',
'protein_goal_g': 'Daily protein target (g)',
'fat_goal_g': 'Daily fat target (g)',
'fibre_goal_g': 'Daily fibre goal (g)',
}
widgets = {
'daily_calorie_goal': forms.NumberInput(attrs={'min': 0, 'step': 1}),
'carbohydrate_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}),
'protein_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}),
'fat_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}),
'fibre_goal_g': forms.NumberInput(attrs={'min': 0, 'step': '0.1'}),
}
class WaterIntakeForm(forms.Form):
amount_ml = forms.IntegerField(min_value=1, max_value=3000)
class SickDaySettingsForm(forms.ModelForm):
class Meta:
model = SickDaySettings
fields = ('enabled', 'recovery_date')
widgets = {'recovery_date': forms.DateInput(attrs={'type': 'date'})}
help_texts = {'recovery_date': 'Optional. Tasks resume the day after this date.'}
class RegistrationForm(UserCreationForm):
class Meta(UserCreationForm.Meta):
model = get_user_model()
fields = ('username',)
class WorkoutForm(forms.ModelForm):
class Meta:
model = Workout
fields = ('name', 'scheduled_for', 'is_daily_recurring', 'duration_minutes', 'calories_burned')
widgets = {'scheduled_for': forms.DateInput(attrs={'type': 'date'})}
help_texts = {
'is_daily_recurring': 'Show this workout every day from its start date.',
'calories_burned': 'Optional; only completed workouts with a value contribute to today’s total.',
}
class SleepCheckInForm(forms.ModelForm):
class Meta:
model = SleepCheckIn
fields = ('wake_up_date', 'rested_score', 'watch_sleep_score', 'note')
widgets = {
'wake_up_date': forms.DateInput(attrs={'type': 'date'}),
'rested_score': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'watch_sleep_score': forms.NumberInput(attrs={'min': 0, 'max': 100, 'inputmode': 'numeric'}),
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
}
labels = {
'wake_up_date': 'Wake-up date',
'rested_score': 'How rested (0–10)',
'watch_sleep_score': 'Watch sleep score (0–100%, optional)',
'note': 'Note (optional)',
}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_wake_up_date(self):
wake_up_date = self.cleaned_data['wake_up_date']
today = localdate_for_user(self.user) if self.user else timezone.localdate()
if wake_up_date > today:
raise forms.ValidationError('Sleep can only be recorded for today or earlier.')
return wake_up_date
class BowelHealthCheckInForm(forms.ModelForm):
class Meta:
model = BowelHealthCheckIn
fields = ('check_in_date', 'morning_severity', 'morning_note', 'afternoon_severity', 'afternoon_note', 'evening_severity', 'evening_note')
widgets = {
'check_in_date': forms.DateInput(attrs={'type': 'date'}),
**{f'{period}_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}) for period in ('morning', 'afternoon', 'evening')},
**{f'{period}_note': forms.Textarea(attrs={'maxlength': 500, 'rows': 2}) for period in ('morning', 'afternoon', 'evening')},
}
labels = {'check_in_date': 'Date', **{f'{period}_severity': 'Gut symptoms (0–10)' for period in ('morning', 'afternoon', 'evening')}, **{f'{period}_note': 'Note (optional)' for period in ('morning', 'afternoon', 'evening')}}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean_check_in_date(self):
value = self.cleaned_data['check_in_date']
if value > (localdate_for_user(self.user) if self.user else timezone.localdate()):
raise forms.ValidationError('Check-ins can only be recorded for today or earlier.')
return value
def clean(self):
cleaned = super().clean()
if not any(cleaned.get(f'{period}_severity') is not None for period in ('morning', 'afternoon', 'evening')):
raise forms.ValidationError('Record a score for at least one time of day.')
return cleaned
class NeckHeadacheCheckInForm(forms.ModelForm):
periods = ("morning", "afternoon", "evening")
class Meta:
model = NeckHeadacheCheckIn
fields = (
"check_in_date",
"morning_neck_pain_severity", "morning_headache_severity", "morning_note",
"afternoon_neck_pain_severity", "afternoon_headache_severity", "afternoon_note",
"evening_neck_pain_severity", "evening_headache_severity", "evening_note",
"had_physiotherapy",
)
widgets = {
"check_in_date": forms.DateInput(attrs={"type": "date"}),
"morning_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"morning_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"morning_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
"afternoon_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"afternoon_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"afternoon_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
"evening_neck_pain_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"evening_headache_severity": forms.NumberInput(attrs={"min": 0, "max": 10, "inputmode": "numeric"}),
"evening_note": forms.Textarea(attrs={"maxlength": 500, "rows": 3, "placeholder": "Anything useful to remember?"}),
}
labels = {
"check_in_date": "Date",
"morning_neck_pain_severity": "Neck pain (0–10)", "morning_headache_severity": "Headache (0–10)", "morning_note": "Note (optional)",
"afternoon_neck_pain_severity": "Neck pain (0–10)", "afternoon_headache_severity": "Headache (0–10)", "afternoon_note": "Note (optional)",
"evening_neck_pain_severity": "Neck pain (0–10)", "evening_headache_severity": "Headache (0–10)", "evening_note": "Note (optional)",
"had_physiotherapy": "I had a physiotherapy session",
}
help_texts = {
"morning_neck_pain_severity": "0 means no pain.", "morning_headache_severity": "0 means no headache.",
"afternoon_neck_pain_severity": "0 means no pain.", "afternoon_headache_severity": "0 means no headache.",
"evening_neck_pain_severity": "0 means no pain.", "evening_headache_severity": "0 means no headache.",
}
def __init__(self, *args, user=None, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
def clean(self):
cleaned_data = super().clean()
has_scores = False
for period in self.periods:
neck = cleaned_data.get(f"{period}_neck_pain_severity")
headache = cleaned_data.get(f"{period}_headache_severity")
if (neck is None) != (headache is None):
field = f"{period}_headache_severity" if neck is not None else f"{period}_neck_pain_severity"
self.add_error(field, "Enter both scores for a time of day.")
if neck is not None and headache is not None:
has_scores = True
if not has_scores and not cleaned_data.get("had_physiotherapy"):
raise forms.ValidationError("Record both scores for at least one time of day, or mark your physiotherapy session.")
return cleaned_data
def clean_check_in_date(self):
check_in_date = self.cleaned_data['check_in_date']
today = localdate_for_user(self.user) if self.user else timezone.localdate()
if check_in_date > today:
raise forms.ValidationError('Check-ins can only be recorded for today or earlier.')
return check_in_date