added stool tracking + toothbrushing tracking

This commit is contained in:
Joren de Graaf
2026-10-02 11:32:59 +02:00
parent d1fbb52937
commit 943dc2280f
16 changed files with 641 additions and 87 deletions
+63
View File
@@ -320,3 +320,66 @@ body[data-theme="dark"] .checkin-tooltip { color: #d9f5e0; background: #315b41;
body[data-theme="dark"] .checkin-tooltip:hover { background: #3b704e; }
body[data-theme="dark"] .checkin-tooltip:focus-visible { outline-color: #a9ddba; }
body[data-theme="dark"] .checkin-tooltip__content { color: #edf5ef; background: #101713; box-shadow: 0 8px 20px rgba(0, 0, 0, .38); }
/* Three-part daily pain check-in ----------------------------------------- */
.checkin-form--pain { display: block; }
.checkin-form--pain .checkin-form__heading { margin-bottom: 18px; }
.checkin-form__topline { display: flex; align-items: end; justify-content: space-between; gap: 18px; }
.checkin-form__topline > .field:first-child { width: min(100%, 170px); }
.checkin-form__physio { padding-bottom: 1px; }
.checkin-periods { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; margin-top: 18px; }
.checkin-period { min-width: 0; padding: 15px; border: 1px solid $line; border-radius: 12px; background: #f8faf7; }
.checkin-period h4 { margin: 0 0 12px; color: $forest; font-family: Fraunces, Georgia, serif; font-size: 1rem; }
.checkin-period__scores { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
.checkin-period .field { min-width: 0; }
.checkin-period .field textarea { min-height: 82px; }
.checkin-form--pain .form-actions { margin-top: 18px; }
.checkin-day { display: block; min-height: 73px; padding: 5px; }
.checkin-day__number { display: block; margin: 0 0 4px; }
.checkin-day__periods { display: grid; gap: 2px; }
.checkin-day__period { display: flex; align-items: center; justify-content: space-between; min-height: 14px; padding: 1px 3px; border-radius: 3px; font-size: .62rem; font-weight: 700; line-height: 1; }
.checkin-day__period strong { font-size: .72rem; }
.checkin-day__period--unrecorded { color: #89908a; background: #f3f4f1; border: 1px dashed #d9ddd5; }
.checkin-day__period--zero { color: #35664d; background: #dff0e4; }
.checkin-day__period--low { color: #5d6a2a; background: #eef2d7; }
.checkin-day__period--moderate { color: #815d1d; background: #fff0c8; }
.checkin-day__period--high { color: #99412f; background: #ffe0d8; }
.checkin-day__period--severe { color: #fff; background: #be4c40; }
.checkin-day__physio { top: 5px; right: 20px; bottom: auto; left: auto; }
.checkin-day__sleep { top: 4px; right: 5px; }
@media (max-width: 760px) { .checkin-periods { grid-template-columns: 1fr; }.checkin-period .field textarea { min-height: 68px; } }
@media (max-width: 480px) { .checkin-form__topline { align-items: start; flex-direction: column; }.checkin-form__topline > .field:first-child { width: 100%; }.checkin-day { min-height: 64px; }.checkin-day__period { font-size: .55rem; }.checkin-day__period strong { font-size: .64rem; } }
body[data-theme="dark"] .checkin-period { border-color: #3b473f; background: #29342d; }
body[data-theme="dark"] .checkin-period h4 { color: #9bd5ae; }
body[data-theme="dark"] .checkin-day__period--unrecorded { color: #aab5ad; background: #242d27; border-color: #58645c; }
body[data-theme="dark"] .checkin-day__period--zero { color: #c8f3d2; background: #28533a; }
body[data-theme="dark"] .checkin-day__period--low { color: #eef2b8; background: #536036; }
body[data-theme="dark"] .checkin-day__period--moderate { color: #ffe5a8; background: #71521c; }
body[data-theme="dark"] .checkin-day__period--high { color: #ffd0c5; background: #733b31; }
body[data-theme="dark"] .checkin-day__period--severe { color: #fff; background: #a8463b; }
.brushing-widget { margin-bottom: 16px; padding: 20px; border: 1px solid $line; border-radius: 18px; background: $surface; box-shadow: $shadow; }
.brushing-widget h2 { margin: 0 0 12px; font-size: 1.35rem; }
.brushing-days { display: grid; gap: 6px; }
.brushing-day { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.brushing-day time { font-size: .78rem; font-weight: 700; }
.brushing-day__controls { display: flex; flex-wrap: wrap; gap: 3px; }
.brushing-control { margin: 0; }
.brushing-control button { padding: 5px 4px; border: 1px solid transparent; border-radius: 6px; color: $ink; background: transparent; font: inherit; font-size: .72rem; cursor: pointer; }
.brushing-control button:hover { border-color: $line; }
.brushing-control button:focus-visible { outline: 2px solid $forest; outline-offset: 2px; }
.brushing-control__mark { font-size: 1.1rem; color: $forest; vertical-align: -1px; }
.checkin-form--bowel { display: block; }
.checkin-form--bowel > .field { max-width: 180px; }
.bowel-periods { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; margin-top: 16px; }
.bowel-period { padding: 12px; border: 1px solid $line; border-radius: 10px; }
.bowel-period h3 { margin: 0 0 10px; font-size: 1rem; }
.bowel-period .field + .field { margin-top: 10px; }
.checkin-form--bowel .field textarea { width: 100%; padding: 8px; border: 1px solid #cfd4cb; border-radius: 8px; color: $ink; background: $surface; }
.checkin-form--bowel .form-actions { margin-top: 16px; }
@media (max-width: 700px) { .bowel-periods { grid-template-columns: 1fr; } }
body[data-theme="dark"] .brushing-widget, body[data-theme="dark"] .bowel-period { border-color: #3b473f; background: #242d27; }
body[data-theme="dark"] .brushing-control button { color: #edf5ef; }
body[data-theme="dark"] .brushing-control__mark { color: #9adab0; }
body[data-theme="dark"] .checkin-form--bowel .field textarea { border-color: #536159; color: #edf5ef; background: #161d19; }
+69 -14
View File
@@ -5,7 +5,7 @@ from django.urls import reverse
from django.utils import timezone
from zoneinfo import available_timezones
from .models import FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
from .models import BowelHealthCheckIn, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
from .timezones import localdate_for_user
@@ -199,35 +199,90 @@ class SleepCheckInForm(forms.ModelForm):
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': 'Bowel 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', 'neck_pain_severity', 'headache_severity', 'note',
'had_physiotherapy',
"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'}),
'neck_pain_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'headache_severity': forms.NumberInput(attrs={'min': 0, 'max': 10, 'inputmode': 'numeric'}),
'note': forms.TextInput(attrs={'maxlength': 500, 'placeholder': 'Anything useful to remember?'}),
"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',
'neck_pain_severity': 'Neck pain (0–10)',
'headache_severity': 'Headache (0–10)',
'note': 'Note (optional)',
'had_physiotherapy': 'I had a physiotherapy session',
"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 = {
'neck_pain_severity': '0 means no pain.',
'headache_severity': '0 means no headache.',
"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()
@@ -136,10 +136,16 @@ class Command(BaseCommand):
NeckHeadacheCheckIn.objects.create(
user=user,
check_in_date=today - timedelta(days=days_ago),
neck_pain_severity=neck,
headache_severity=headache,
morning_neck_pain_severity=neck,
morning_headache_severity=headache,
morning_note=note,
afternoon_neck_pain_severity=max(0, neck - 1),
afternoon_headache_severity=headache,
afternoon_note='Symptoms after lunch.',
evening_neck_pain_severity=max(0, neck - 1),
evening_headache_severity=max(0, headache - 1),
evening_note='Evening check-in.',
had_physiotherapy=physiotherapy,
note=note,
)
for days_ago, rested, watch_score, note in (
(3, 5, 68, 'Late evening.'),
@@ -0,0 +1,84 @@
# Generated by Django 6.1.1 on 2026-10-01
import django.core.validators
from django.db import migrations, models
def move_legacy_check_ins_to_morning(apps, schema_editor):
"""Keep historical single daily records without inventing later-day scores."""
CheckIn = apps.get_model("planner", "NeckHeadacheCheckIn")
for check_in in CheckIn.objects.all().iterator():
check_in.morning_neck_pain_severity = check_in.neck_pain_severity
check_in.morning_headache_severity = check_in.headache_severity
check_in.morning_note = check_in.note
check_in.save(update_fields=(
"morning_neck_pain_severity", "morning_headache_severity", "morning_note",
))
def restore_legacy_check_ins_from_morning(apps, schema_editor):
CheckIn = apps.get_model("planner", "NeckHeadacheCheckIn")
for check_in in CheckIn.objects.all().iterator():
check_in.neck_pain_severity = check_in.morning_neck_pain_severity or 0
check_in.headache_severity = check_in.morning_headache_severity or 0
check_in.note = check_in.morning_note
check_in.save(update_fields=("neck_pain_severity", "headache_severity", "note"))
class Migration(migrations.Migration):
dependencies = [
("planner", "0013_usersettings_appearance"),
]
operations = [
migrations.AddField(
model_name="neckheadachecheckin",
name="morning_neck_pain_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="morning_headache_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="morning_note",
field=models.TextField(blank=True, max_length=500),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="afternoon_neck_pain_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="afternoon_headache_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="afternoon_note",
field=models.TextField(blank=True, max_length=500),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="evening_neck_pain_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="evening_headache_severity",
field=models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)]),
),
migrations.AddField(
model_name="neckheadachecheckin",
name="evening_note",
field=models.TextField(blank=True, max_length=500),
),
migrations.RunPython(move_legacy_check_ins_to_morning, restore_legacy_check_ins_from_morning),
migrations.RemoveField(model_name="neckheadachecheckin", name="headache_severity"),
migrations.RemoveField(model_name="neckheadachecheckin", name="neck_pain_severity"),
migrations.RemoveField(model_name="neckheadachecheckin", name="note"),
]
@@ -0,0 +1,51 @@
# Generated by Django 6.1.1 on 2026-10-02 09:19
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('planner', '0014_three_part_pain_checkins'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='BowelHealthCheckIn',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('check_in_date', models.DateField()),
('morning_severity', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('morning_note', models.TextField(blank=True, max_length=500)),
('afternoon_severity', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('afternoon_note', models.TextField(blank=True, max_length=500)),
('evening_severity', models.PositiveSmallIntegerField(blank=True, null=True, validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(10)])),
('evening_note', models.TextField(blank=True, max_length=500)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='bowel_health_check_ins', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-check_in_date',),
'constraints': [models.UniqueConstraint(fields=('user', 'check_in_date'), name='unique_bowel_health_check_in_per_day')],
},
),
migrations.CreateModel(
name='ToothBrushing',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date', models.DateField()),
('morning', models.BooleanField(default=False)),
('evening', models.BooleanField(default=False)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tooth_brushing', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-date',),
'constraints': [models.UniqueConstraint(fields=('user', 'date'), name='unique_tooth_brushing_per_day')],
},
),
]
+53 -5
View File
@@ -209,13 +209,33 @@ class NeckHeadacheCheckIn(models.Model):
related_name='neck_headache_check_ins',
)
check_in_date = models.DateField()
neck_pain_severity = models.PositiveSmallIntegerField(
validators=[MinValueValidator(0), MaxValueValidator(10)],
PERIODS = (
('morning', 'Morning', 'M'),
('afternoon', 'Afternoon', 'A'),
('evening', 'Evening', 'E'),
)
headache_severity = models.PositiveSmallIntegerField(
validators=[MinValueValidator(0), MaxValueValidator(10)],
morning_neck_pain_severity = models.PositiveSmallIntegerField(
blank=True, null=True, validators=[MinValueValidator(0), MaxValueValidator(10)],
)
note = models.CharField(max_length=500, blank=True)
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)
@@ -232,6 +252,34 @@ class NeckHeadacheCheckIn(models.Model):
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."""
+7 -4
View File
@@ -16,10 +16,13 @@ class CheckInStreaks:
def is_low_pain(check_in, threshold=LOW_PAIN_STREAK_THRESHOLD):
return (
check_in.neck_pain_severity <= threshold
and check_in.headache_severity <= threshold
)
"""A confirmed low-pain day needs both scores in every time period."""
for period, _, _ in check_in.PERIODS:
neck = getattr(check_in, f"{period}_neck_pain_severity")
headache = getattr(check_in, f"{period}_headache_severity")
if neck is None or headache is None or neck > threshold or headache > threshold:
return False
return True
def calculate_check_in_streaks(check_ins, as_of_date, threshold=LOW_PAIN_STREAK_THRESHOLD):
@@ -0,0 +1,17 @@
<section class="checkin-panel bowel-panel" id="bowel-health-checkin" aria-labelledby="bowel-heading">
<header class="checkin-panel__header"><div><p class="eyebrow">Daily wellbeing</p><h2 id="bowel-heading">Bowel health</h2><p>Record how your bowels felt during each part of the day. Choose a date below to edit an entry.</p></div></header>
<form class="checkin-form checkin-form--bowel" method="post" action="{% url 'planner:bowel-health-save' %}" hx-post="{% url 'planner:bowel-health-save' %}" hx-target="#bowel-health-checkin" hx-swap="outerHTML" novalidate>
{% csrf_token %}{% if bowel_form.non_field_errors %}<div class="form-errors">{{ bowel_form.non_field_errors }}</div>{% endif %}
<div class="field">{{ bowel_form.check_in_date.label_tag }}{{ bowel_form.check_in_date }}{{ bowel_form.check_in_date.errors }}</div>
<div class="bowel-periods">
<div class="bowel-period"><h3>Morning</h3><div class="field">{{ bowel_form.morning_severity.label_tag }}{{ bowel_form.morning_severity }}{{ bowel_form.morning_severity.errors }}</div><div class="field">{{ bowel_form.morning_note.label_tag }}{{ bowel_form.morning_note }}{{ bowel_form.morning_note.errors }}</div></div>
<div class="bowel-period"><h3>Afternoon</h3><div class="field">{{ bowel_form.afternoon_severity.label_tag }}{{ bowel_form.afternoon_severity }}{{ bowel_form.afternoon_severity.errors }}</div><div class="field">{{ bowel_form.afternoon_note.label_tag }}{{ bowel_form.afternoon_note }}{{ bowel_form.afternoon_note.errors }}</div></div>
<div class="bowel-period"><h3>Evening</h3><div class="field">{{ bowel_form.evening_severity.label_tag }}{{ bowel_form.evening_severity }}{{ bowel_form.evening_severity.errors }}</div><div class="field">{{ bowel_form.evening_note.label_tag }}{{ bowel_form.evening_note }}{{ bowel_form.evening_note.errors }}</div></div>
</div><div class="form-actions"><button class="button button--compact" type="submit">Save bowel check-in</button></div>
</form>
<section class="checkin-calendar" aria-labelledby="bowel-calendar-heading"><header class="checkin-calendar__header">
<a class="text-link" href="{% url 'planner:task-list' %}?bowel_date={{ bowel_previous_month|date:'Y-m-d' }}#bowel-health-checkin" hx-get="{% url 'planner:bowel-health-panel' %}?date={{ bowel_previous_month|date:'Y-m-d' }}" hx-target="#bowel-health-checkin" hx-swap="outerHTML" aria-label="Previous month">←</a><h3 id="bowel-calendar-heading">{{ bowel_selected_date|date:'F Y' }}</h3><a class="text-link" href="{% url 'planner:task-list' %}?bowel_date={{ bowel_next_month|date:'Y-m-d' }}#bowel-health-checkin" hx-get="{% url 'planner:bowel-health-panel' %}?date={{ bowel_next_month|date:'Y-m-d' }}" hx-target="#bowel-health-checkin" hx-swap="outerHTML" aria-label="Next month">→</a>
</header><div class="checkin-calendar__weekdays" aria-hidden="true"><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span></div>
<div class="checkin-calendar__grid">{% for week in bowel_calendar_weeks %}{% for day in week %}<a class="checkin-day{% if day.is_today %} checkin-day--today{% endif %}{% if day.is_selected %} checkin-day--selected{% endif %}{% if day.is_outside_month %} checkin-day--outside{% endif %}" href="{% url 'planner:task-list' %}?bowel_date={{ day.date|date:'Y-m-d' }}#bowel-health-checkin" hx-get="{% url 'planner:bowel-health-panel' %}?date={{ day.date|date:'Y-m-d' }}" hx-target="#bowel-health-checkin" hx-swap="outerHTML" aria-label="{{ day.label }}"><span class="checkin-day__number">{{ day.date|date:'j' }}</span><span class="checkin-day__periods" aria-hidden="true">{% for period in day.periods %}<span class="checkin-day__period checkin-day__period--{{ period.level }}"><span>{{ period.short_label }}</span><strong>{% if period.score is not None %}{{ period.score }}{% else %}—{% endif %}</strong></span>{% endfor %}</span></a>{% endfor %}{% endfor %}</div>
<p class="checkin-calendar__legend">M = morning · A = afternoon · E = evening · 0 = no symptoms · 10 = worst symptoms</p></section>
</section>
@@ -7,7 +7,7 @@
</div>
{% if check_in_active_tab == 'pain' %}
<dl class="checkin-streaks" aria-label="Pain check-in summary">
<div><dt>Current <span class="checkin-tooltip" tabindex="0" aria-label="A confirmed day has both pain scores at {{ check_in_streak_threshold }} or below">ⓘ<span class="checkin-tooltip__content" role="tooltip">A confirmed day has both scores at {{ check_in_streak_threshold }} or below.</span></span></dt><dd>{{ check_in_streaks.current }} day{{ check_in_streaks.current|pluralize }}</dd></div>
<div><dt>Current <span class="checkin-tooltip" tabindex="0" aria-label="A confirmed day has both scores in morning, afternoon, and evening at {{ check_in_streak_threshold }} or below">ⓘ<span class="checkin-tooltip__content" role="tooltip">A confirmed day has both scores in every time period at {{ check_in_streak_threshold }} or below.</span></span></dt><dd>{{ check_in_streaks.current }} day{{ check_in_streaks.current|pluralize }}</dd></div>
<div><dt>Longest</dt><dd>{{ check_in_streaks.longest }} day{{ check_in_streaks.longest|pluralize }}</dd></div>
<div><dt>Physio sessions this year</dt><dd>{{ physio_sessions_this_year }}/{{ annual_physio_session_allowance }}</dd></div>
</dl>
@@ -21,15 +21,19 @@
{% if check_in_active_tab == 'pain' %}
<div id="pain-checkin-panel" role="tabpanel" aria-labelledby="pain-checkin-tab" tabindex="0">
<form class="checkin-form" method="post" action="{% url 'planner:neck-headache-checkin-save' %}" hx-post="{% url 'planner:neck-headache-checkin-save' %}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" novalidate>
<form class="checkin-form checkin-form--pain" method="post" action='{% url "planner:neck-headache-checkin-save" %}' hx-post='{% url "planner:neck-headache-checkin-save" %}' hx-target="#neck-headache-checkin" hx-swap="outerHTML" novalidate>
{% csrf_token %}
<h3 class="checkin-form__heading">Neck &amp; headache</h3>
{% if check_in_form.non_field_errors %}<div class="form-errors">{{ check_in_form.non_field_errors }}</div>{% endif %}
<div class="field{% if check_in_form.check_in_date.errors %} field--error{% endif %}">{{ check_in_form.check_in_date.label_tag }}{{ check_in_form.check_in_date }}{% for error in check_in_form.check_in_date.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
<div class="field{% if check_in_form.neck_pain_severity.errors %} field--error{% endif %}">{{ check_in_form.neck_pain_severity.label_tag }}{{ check_in_form.neck_pain_severity }}<small>{{ check_in_form.neck_pain_severity.help_text }}</small>{% for error in check_in_form.neck_pain_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
<div class="field{% if check_in_form.headache_severity.errors %} field--error{% endif %}">{{ check_in_form.headache_severity.label_tag }}{{ check_in_form.headache_severity }}<small>{{ check_in_form.headache_severity.help_text }}</small>{% for error in check_in_form.headache_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
<div class="field checkin-form__note{% if check_in_form.note.errors %} field--error{% endif %}">{{ check_in_form.note.label_tag }}{{ check_in_form.note }}{% for error in check_in_form.note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
<div class="field checkin-form__physio"><label class="checkbox-field">{{ check_in_form.had_physiotherapy }} <span>{{ check_in_form.had_physiotherapy.label }}</span></label></div>
<div class="checkin-form__topline">
<div class="field{% if check_in_form.check_in_date.errors %} field--error{% endif %}">{{ check_in_form.check_in_date.label_tag }}{{ check_in_form.check_in_date }}{% for error in check_in_form.check_in_date.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div>
<div class="field checkin-form__physio"><label class="checkbox-field">{{ check_in_form.had_physiotherapy }} <span>{{ check_in_form.had_physiotherapy.label }}</span></label></div>
</div>
<div class="checkin-periods">
<section class="checkin-period" aria-labelledby="morning-checkin-heading"><h4 id="morning-checkin-heading">Morning</h4><div class="checkin-period__scores"><div class="field{% if check_in_form.morning_neck_pain_severity.errors %} field--error{% endif %}">{{ check_in_form.morning_neck_pain_severity.label_tag }}{{ check_in_form.morning_neck_pain_severity }}<small>{{ check_in_form.morning_neck_pain_severity.help_text }}</small>{% for error in check_in_form.morning_neck_pain_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div><div class="field{% if check_in_form.morning_headache_severity.errors %} field--error{% endif %}">{{ check_in_form.morning_headache_severity.label_tag }}{{ check_in_form.morning_headache_severity }}<small>{{ check_in_form.morning_headache_severity.help_text }}</small>{% for error in check_in_form.morning_headache_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></div><div class="field{% if check_in_form.morning_note.errors %} field--error{% endif %}">{{ check_in_form.morning_note.label_tag }}{{ check_in_form.morning_note }}{% for error in check_in_form.morning_note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></section>
<section class="checkin-period" aria-labelledby="afternoon-checkin-heading"><h4 id="afternoon-checkin-heading">Afternoon</h4><div class="checkin-period__scores"><div class="field{% if check_in_form.afternoon_neck_pain_severity.errors %} field--error{% endif %}">{{ check_in_form.afternoon_neck_pain_severity.label_tag }}{{ check_in_form.afternoon_neck_pain_severity }}<small>{{ check_in_form.afternoon_neck_pain_severity.help_text }}</small>{% for error in check_in_form.afternoon_neck_pain_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div><div class="field{% if check_in_form.afternoon_headache_severity.errors %} field--error{% endif %}">{{ check_in_form.afternoon_headache_severity.label_tag }}{{ check_in_form.afternoon_headache_severity }}<small>{{ check_in_form.afternoon_headache_severity.help_text }}</small>{% for error in check_in_form.afternoon_headache_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></div><div class="field{% if check_in_form.afternoon_note.errors %} field--error{% endif %}">{{ check_in_form.afternoon_note.label_tag }}{{ check_in_form.afternoon_note }}{% for error in check_in_form.afternoon_note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></section>
<section class="checkin-period" aria-labelledby="evening-checkin-heading"><h4 id="evening-checkin-heading">Evening</h4><div class="checkin-period__scores"><div class="field{% if check_in_form.evening_neck_pain_severity.errors %} field--error{% endif %}">{{ check_in_form.evening_neck_pain_severity.label_tag }}{{ check_in_form.evening_neck_pain_severity }}<small>{{ check_in_form.evening_neck_pain_severity.help_text }}</small>{% for error in check_in_form.evening_neck_pain_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div><div class="field{% if check_in_form.evening_headache_severity.errors %} field--error{% endif %}">{{ check_in_form.evening_headache_severity.label_tag }}{{ check_in_form.evening_headache_severity }}<small>{{ check_in_form.evening_headache_severity.help_text }}</small>{% for error in check_in_form.evening_headache_severity.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></div><div class="field{% if check_in_form.evening_note.errors %} field--error{% endif %}">{{ check_in_form.evening_note.label_tag }}{{ check_in_form.evening_note }}{% for error in check_in_form.evening_note.errors %}<p class="field-error">{{ error }}</p>{% endfor %}</div></section>
</div>
<div class="form-actions"><button class="button button--compact" type="submit">Save pain check-in</button></div>
</form>
</div>
@@ -53,8 +57,8 @@
<a class="text-link" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_previous_month|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_previous_month|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="Previous month">←</a><h3 id="checkin-calendar-heading">{{ check_in_selected_date|date:"F Y" }}</h3><a class="text-link" href="{% url 'planner:task-list' %}?check_in_date={{ check_in_next_month|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ check_in_next_month|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="Next month">→</a>
</header>
<div class="checkin-calendar__weekdays" aria-hidden="true"><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span></div>
<div class="checkin-calendar__grid">{% for week in check_in_calendar_weeks %}{% for day in week %}<a class="checkin-day checkin-day--{{ day.level }}{% if day.is_today %} checkin-day--today{% endif %}{% if day.is_selected %} checkin-day--selected{% endif %}{% if day.is_outside_month %} checkin-day--outside{% endif %}" href="{% url 'planner:task-list' %}?check_in_date={{ day.date|date:'Y-m-d' }}&wellbeing_tab={{ check_in_active_tab }}" hx-get="{% url 'planner:neck-headache-checkin-panel' %}?date={{ day.date|date:'Y-m-d' }}&tab={{ check_in_active_tab }}" hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="{{ day.label }}"><span class="checkin-day__number">{{ day.date|date:"j" }}</span>{% if day.check_in %}<strong class="checkin-day__score">{{ day.highest_score }}</strong>{% if day.check_in.had_physiotherapy %}<span class="checkin-day__physio" aria-hidden="true">✚</span>{% endif %}{% else %}<span class="checkin-day__empty" aria-hidden="true">—</span>{% endif %}{% if day.sleep_check_in %}<span class="checkin-day__sleep" aria-hidden="true">☾</span>{% endif %}</a>{% endfor %}{% endfor %}</div>
<p class="checkin-calendar__legend"><span><i class="checkin-legend checkin-legend--unrecorded"></i> Pain unrecorded</span><span><i class="checkin-legend checkin-legend--zero"></i> Pain recorded: 0</span><span>Number = highest pain score</span><span><i class="checkin-legend checkin-legend--sleep">☾</i> Sleep check-in</span></p>
<div class="checkin-calendar__grid">{% for week in check_in_calendar_weeks %}{% for day in week %}<a class="checkin-day{% if day.is_today %} checkin-day--today{% endif %}{% if day.is_selected %} checkin-day--selected{% endif %}{% if day.is_outside_month %} checkin-day--outside{% endif %}" href='{% url "planner:task-list" %}?check_in_date={{ day.date|date:"Y-m-d" }}&wellbeing_tab={{ check_in_active_tab }}' hx-get='{% url "planner:neck-headache-checkin-panel" %}?date={{ day.date|date:"Y-m-d" }}&tab={{ check_in_active_tab }}' hx-target="#neck-headache-checkin" hx-swap="outerHTML" aria-label="{{ day.label }}"><span class="checkin-day__number">{{ day.date|date:"j" }}</span><span class="checkin-day__periods" aria-hidden="true">{% for period in day.periods %}<span class="checkin-day__period checkin-day__period--{{ period.level }}"><span>{{ period.short_label }}</span><strong>{% if period.score is not None %}{{ period.score }}{% else %}—{% endif %}</strong></span>{% endfor %}</span>{% if day.check_in and day.check_in.had_physiotherapy %}<span class="checkin-day__physio" aria-hidden="true">✚</span>{% endif %}{% if day.sleep_check_in %}<span class="checkin-day__sleep" aria-hidden="true">☾</span>{% endif %}</a>{% endfor %}{% endfor %}</div>
<p class="checkin-calendar__legend"><span><i class="checkin-legend checkin-legend--unrecorded"></i> Unrecorded period</span><span><i class="checkin-legend checkin-legend--zero"></i> Recorded: 0</span><span>Three bands: morning, afternoon, evening</span><span><i class="checkin-legend checkin-legend--sleep">☾</i> Sleep check-in</span></p>
</section>
{% if check_in_active_tab == 'sleep' %}<section class="sleep-trend" aria-labelledby="sleep-trend-heading"><header><h3 id="sleep-trend-heading">Sleep scores over time</h3><p>Rested and watch scores are shown together for comparison only; neither is presented as causing a change in the other.</p></header>{% if sleep_check_in_trend %}<div class="sleep-trend__table-wrap"><table><thead><tr><th scope="col">Wake-up date</th><th scope="col">Rested</th><th scope="col">Watch</th></tr></thead><tbody>{% for sleep in sleep_check_in_trend %}<tr><th scope="row"><time datetime="{{ sleep.wake_up_date|date:'Y-m-d' }}">{{ sleep.wake_up_date|date:"j M" }}</time></th><td>{{ sleep.rested_score }}/10</td><td>{% if sleep.watch_sleep_score is not None %}{{ sleep.watch_sleep_score }}%{% else %}—{% endif %}</td></tr>{% endfor %}</tbody></table></div>{% else %}<p class="sleep-trend__empty">Save a sleep check-in to start the comparison.</p>{% endif %}</section>{% endif %}
@@ -0,0 +1,4 @@
<form class="brushing-control" method="post" action="{% url 'planner:tooth-brushing-toggle' %}" hx-post="{% url 'planner:tooth-brushing-toggle' %}" hx-target="this" hx-swap="outerHTML">
{% csrf_token %}<input type="hidden" name="date" value="{{ brushing_day|date:'Y-m-d' }}"><input type="hidden" name="period" value="{{ brushing_period }}">
<button type="submit" aria-pressed="{% if brushing_done %}true{% else %}false{% endif %}" aria-label="{{ brushing_day|date:'l j F' }} {{ brushing_period }} brushing{% if brushing_done %}, done{% else %}, not done{% endif %}"><span class="brushing-control__mark" aria-hidden="true">{% if brushing_done %}●{% else %}○{% endif %}</span> {{ brushing_period|capfirst }}</button>
</form>
@@ -0,0 +1,9 @@
<article class="brushing-widget" aria-labelledby="brushing-heading">
<p class="eyebrow">Daily routine</p><h2 id="brushing-heading">Teeth</h2>
<div class="brushing-days">{% for day in brushing_days %}
<div class="brushing-day"><time datetime="{{ day.date|date:'Y-m-d' }}">{{ day.date|date:'l' }}</time><div class="brushing-day__controls">
{% include 'planner/partials/tooth_brushing_control.html' with brushing_day=day.date brushing_period='morning' brushing_done=day.record.morning %}
{% include 'planner/partials/tooth_brushing_control.html' with brushing_day=day.date brushing_period='evening' brushing_done=day.record.evening %}
</div></div>
{% endfor %}</div>
</article>
@@ -40,10 +40,12 @@
{% include 'planner/partials/workout_section.html' %}
{% include 'planner/partials/neck_headache_checkin.html' %}
{% include 'planner/partials/bowel_health_checkin.html' %}
</div>
{% if user.is_authenticated %}
<aside class="homepage-sidebar" aria-label="Personal routines">
{% include 'planner/partials/weather_widget.html' %}
{% include 'planner/partials/tooth_brushing_widget.html' %}
{% include 'planner/partials/fasting_widget.html' %}
</aside>
{% endif %}
+102
View File
@@ -0,0 +1,102 @@
from datetime import date, timedelta
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.test import Client
from django.urls import reverse
from .models import BowelHealthCheckIn, NeckHeadacheCheckIn, ToothBrushing
from .views import bowel_context, brushing_context, check_in_context
class HealthTrackerTests(TestCase):
def setUp(self):
User = get_user_model()
self.user = User.objects.create_user(username='health-owner', password='password')
self.other = User.objects.create_user(username='health-other', password='password')
self.today = date(2026, 10, 2)
def test_brushing_week_grows_and_history_remains(self):
previous = ToothBrushing.objects.create(user=self.user, date=date(2026, 9, 27), morning=True)
self.assertEqual(len(brushing_context(self.user, date(2026, 9, 28))['brushing_days']), 1)
self.assertEqual(len(brushing_context(self.user, date(2026, 9, 29))['brushing_days']), 2)
self.assertEqual(len(brushing_context(self.user, date(2026, 10, 4))['brushing_days']), 7)
self.assertEqual(len(brushing_context(self.user, date(2026, 10, 5))['brushing_days']), 1)
self.assertTrue(ToothBrushing.objects.get(pk=previous.pk).morning)
@patch('planner.views.localdate_for_user', return_value=date(2026, 10, 2))
def test_dashboard_order_and_csrf(self, _):
self.client.force_login(self.user)
response = self.client.get(reverse('planner:task-list'))
html = response.content.decode()
self.assertLess(html.index('id="brushing-heading"'), html.index('id="fasting-widget"'))
self.assertEqual(len(response.context['brushing_days']), 5)
csrf_client = Client(enforce_csrf_checks=True)
csrf_client.force_login(self.user)
self.assertEqual(csrf_client.post(reverse('planner:tooth-brushing-toggle'),
{'date': '2026-10-02', 'period': 'morning'}).status_code, 403)
@patch('planner.views.localdate_for_user', return_value=date(2026, 10, 2))
def test_brushing_toggle_is_private_and_partial(self, _):
url = reverse('planner:tooth-brushing-toggle')
self.assertEqual(self.client.post(url, {'date': '2026-10-02', 'period': 'morning'}).status_code, 302)
self.client.force_login(self.user)
response = self.client.post(url, {'date': '2026-10-02', 'period': 'evening'}, HTTP_HX_REQUEST='true')
self.assertContains(response, 'aria-pressed="true"')
self.assertNotContains(response, 'brushing-widget')
self.client.post(url, {'date': '2026-10-02', 'period': 'morning'})
record = ToothBrushing.objects.get(user=self.user, date=self.today)
self.assertTrue(record.morning and record.evening)
self.assertEqual(ToothBrushing.objects.filter(user=self.user, date=self.today).count(), 1)
self.client.post(url, {'date': '2026-10-02', 'period': 'morning'})
record.refresh_from_db()
self.assertFalse(record.morning)
self.assertTrue(record.evening)
self.assertEqual(self.client.post(url, {'date': '2026-10-03', 'period': 'morning'}).status_code, 400)
self.assertEqual(self.client.post(url, {'date': '2026-10-02', 'period': 'night'}).status_code, 400)
self.client.force_login(self.other)
self.client.post(url, {'date': '2026-10-02', 'period': 'morning'})
record.refresh_from_db()
self.assertFalse(record.morning)
@patch('planner.views.localdate_for_user', return_value=date(2026, 10, 2))
@patch('planner.forms.localdate_for_user', return_value=date(2026, 10, 2))
def test_bowel_save_calendar_and_ownership(self, _form_today, _view_today):
url = reverse('planner:bowel-health-save')
payload = {'check_in_date': '2026-10-02', 'morning_severity': '0', 'morning_note': 'Fine',
'afternoon_severity': '4', 'afternoon_note': 'Cramping', 'evening_severity': '7', 'evening_note': 'Bloating'}
self.assertEqual(self.client.post(url, payload).status_code, 302)
self.client.force_login(self.user)
self.assertEqual(self.client.post(url, payload, HTTP_HX_REQUEST='true').status_code, 200)
entry = BowelHealthCheckIn.objects.get(user=self.user)
self.assertEqual((entry.morning_severity, entry.afternoon_severity, entry.evening_severity), (0, 4, 7))
self.assertEqual(entry.afternoon_note, 'Cramping')
cells = [cell for week in bowel_context(self.user, self.today)['bowel_calendar_weeks'] for cell in week]
selected = next(cell for cell in cells if cell['date'] == self.today)
self.assertEqual([period['level'] for period in selected['periods']], ['zero', 'moderate', 'high'])
self.assertEqual(next(cell for cell in cells if cell['date'] == self.today - timedelta(days=1))['periods'][0]['level'], 'unrecorded')
self.assertContains(self.client.get(reverse('planner:bowel-health-panel'), {'date': '2026-09-01'}), 'September 2026')
self.client.force_login(self.other)
self.client.post(url, dict(payload, morning_severity='9'))
entry.refresh_from_db()
self.assertEqual(entry.morning_severity, 0)
@patch('planner.views.localdate_for_user', return_value=date(2026, 10, 2))
def test_existing_pain_record_and_calendar_remain_unchanged(self, _):
record = NeckHeadacheCheckIn.objects.create(
user=self.user, check_in_date=self.today, morning_neck_pain_severity=1,
morning_headache_severity=2, morning_note='Morning note',
afternoon_neck_pain_severity=4, afternoon_headache_severity=3,
afternoon_note='Afternoon note', evening_neck_pain_severity=7,
evening_headache_severity=6, evening_note='Evening note',
)
original_pk = record.pk
fetched = NeckHeadacheCheckIn.objects.get(pk=original_pk)
self.assertEqual((fetched.morning_neck_pain_severity, fetched.afternoon_headache_severity,
fetched.evening_neck_pain_severity, fetched.morning_note, fetched.afternoon_note,
fetched.evening_note), (1, 3, 7, 'Morning note', 'Afternoon note', 'Evening note'))
self.client.force_login(self.user)
self.assertContains(self.client.get(reverse('planner:neck-headache-checkin-panel')), 'Morning note')
cells = [cell for week in check_in_context(self.user, self.today)['check_in_calendar_weeks'] for cell in week]
self.assertEqual([period['score'] for period in next(cell for cell in cells if cell['date'] == self.today)['periods']], [2, 4, 7])
+40 -19
View File
@@ -1263,11 +1263,17 @@ class NeckHeadacheCheckInTests(TestCase):
self.today = timezone.localdate()
def check_in(self, user, day, neck=0, headache=0, **kwargs):
if "note" in kwargs:
kwargs["morning_note"] = kwargs.pop("note")
return NeckHeadacheCheckIn.objects.create(
user=user,
check_in_date=day,
neck_pain_severity=neck,
headache_severity=headache,
morning_neck_pain_severity=neck,
morning_headache_severity=headache,
afternoon_neck_pain_severity=neck,
afternoon_headache_severity=headache,
evening_neck_pain_severity=neck,
evening_headache_severity=headache,
**kwargs,
)
@@ -1282,32 +1288,50 @@ class NeckHeadacheCheckInTests(TestCase):
response = self.client.post(reverse('planner:neck-headache-checkin-save'), {
'check_in_date': self.today.isoformat(),
'neck_pain_severity': 2,
'headache_severity': 2,
'note': 'My update',
"morning_neck_pain_severity": 2, "morning_headache_severity": 2, "morning_note": "My update",
"afternoon_neck_pain_severity": 2, "afternoon_headache_severity": 2,
"evening_neck_pain_severity": 2, "evening_headache_severity": 2,
})
self.assertEqual(response.status_code, 302)
mine.refresh_from_db()
self.assertEqual((mine.neck_pain_severity, mine.headache_severity), (2, 2))
self.assertEqual((mine.morning_neck_pain_severity, mine.morning_headache_severity), (2, 2))
self.assertEqual(NeckHeadacheCheckIn.objects.filter(user=self.other).count(), 1)
def test_saving_an_existing_date_edits_instead_of_creating_a_second_entry(self):
check_in = self.check_in(self.user, self.today - timedelta(days=2), neck=7, headache=1)
response = self.client.post(reverse('planner:neck-headache-checkin-save'), {
'check_in_date': check_in.check_in_date.isoformat(),
'neck_pain_severity': 0,
'headache_severity': 2,
'note': 'Improved after treatment',
"morning_neck_pain_severity": 0, "morning_headache_severity": 2, "morning_note": "Improved after treatment",
"afternoon_neck_pain_severity": 1, "afternoon_headache_severity": 1,
"evening_neck_pain_severity": 0, "evening_headache_severity": 0,
'had_physiotherapy': 'on',
}, HTTP_HX_REQUEST='true')
self.assertEqual(response.status_code, 200)
self.assertEqual(NeckHeadacheCheckIn.objects.filter(user=self.user).count(), 1)
check_in.refresh_from_db()
self.assertEqual(check_in.neck_pain_severity, 0)
self.assertEqual(check_in.morning_neck_pain_severity, 0)
self.assertTrue(check_in.had_physiotherapy)
self.assertContains(response, 'Improved after treatment')
def test_unrecorded_time_period_breaks_a_confirmed_streak_and_notes_are_textareas(self):
yesterday = self.check_in(self.user, self.today - timedelta(days=1), neck=1, headache=1)
partial_today = NeckHeadacheCheckIn.objects.create(
user=self.user,
check_in_date=self.today,
morning_neck_pain_severity=1,
morning_headache_severity=1,
morning_note="Only checked in this morning.",
)
streaks = calculate_check_in_streaks([yesterday, partial_today], self.today)
self.assertEqual(streaks.current, 0)
self.assertEqual(streaks.longest, 1)
response = self.client.get(reverse("planner:neck-headache-checkin-panel"))
self.assertContains(response, "name=\"morning_note\"")
self.assertContains(response, "textarea")
self.assertContains(response, "checkin-day__period--unrecorded")
def test_missing_days_break_confirmed_streaks(self):
entries = [
self.check_in(self.user, self.today - timedelta(days=6), neck=1, headache=2),
@@ -1341,7 +1365,7 @@ class SleepCheckInTests(TestCase):
self.sleep_check_in(self.other, self.today, rested=1, note="Private sleep")
mine = self.sleep_check_in(self.user, self.today, rested=8, watch_sleep_score=87)
NeckHeadacheCheckIn.objects.create(
user=self.user, check_in_date=self.today, neck_pain_severity=2, headache_severity=1
user=self.user, check_in_date=self.today, morning_neck_pain_severity=2, morning_headache_severity=1
)
response = self.client.get(reverse("planner:neck-headache-checkin-panel"))
@@ -1357,7 +1381,7 @@ class SleepCheckInTests(TestCase):
self.assertContains(response, "role=\"tablist\"")
self.assertContains(response, "aria-selected=\"true\"")
self.assertContains(response, "name=\"rested_score\"")
self.assertNotContains(response, "name=\"neck_pain_severity\"")
self.assertNotContains(response, "name=\"morning_neck_pain_severity\"")
self.assertContains(response, "&tab=sleep")
def test_past_sleep_entry_is_edited_without_touching_another_users_entry(self):
@@ -1401,20 +1425,17 @@ class PhysiotherapyCounterTests(TestCase):
other = get_user_model().objects.create_user(username='other-physio-counter', password='password')
today = timezone.localdate()
NeckHeadacheCheckIn.objects.create(
user=user, check_in_date=today, neck_pain_severity=0,
headache_severity=0, had_physiotherapy=True,
user=user, check_in_date=today, had_physiotherapy=True,
)
NeckHeadacheCheckIn.objects.create(
user=user, check_in_date=today - timedelta(days=1), neck_pain_severity=0,
headache_severity=0, had_physiotherapy=True,
user=user, check_in_date=today - timedelta(days=1), had_physiotherapy=True,
)
NeckHeadacheCheckIn.objects.create(
user=user, check_in_date=date(today.year - 1, 12, 31),
neck_pain_severity=0, headache_severity=0, had_physiotherapy=True,
had_physiotherapy=True,
)
NeckHeadacheCheckIn.objects.create(
user=other, check_in_date=today, neck_pain_severity=0,
headache_severity=0, had_physiotherapy=True,
user=other, check_in_date=today, had_physiotherapy=True,
)
self.client.force_login(user)
+4
View File
@@ -6,6 +6,7 @@ from .views import (
TaskUpdateView, WorkoutCreateView, WorkoutUpdateView, delete_workout, fasting_configure, neck_headache_checkin_panel,
fasting_toggle_tracking, fasting_widget, logout_view, register, toggle_task_active, toggle_task_completed,
save_neck_headache_checkin, save_sleep_checkin, advance_onboarding, toggle_workout_completed, user_settings, workout_today,
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing,
)
app_name = 'planner'
@@ -24,6 +25,9 @@ urlpatterns = [
path('check-ins/panel/', neck_headache_checkin_panel, name='neck-headache-checkin-panel'),
path('check-ins/save/', save_neck_headache_checkin, name='neck-headache-checkin-save'),
path('sleep-check-ins/save/', save_sleep_checkin, name='sleep-checkin-save'),
path('teeth/toggle/', toggle_tooth_brushing, name='tooth-brushing-toggle'),
path('bowel-health/panel/', bowel_health_panel, name='bowel-health-panel'),
path('bowel-health/save/', save_bowel_health_checkin, name='bowel-health-save'),
path('workouts/today/', workout_today, name='workout-today'),
path('workouts/new/', WorkoutCreateView.as_view(), name='workout-create'),
path('workouts/<int:pk>/edit/', WorkoutUpdateView.as_view(), name='workout-update'),
+114 -33
View File
@@ -16,9 +16,9 @@ from django.views.generic import CreateView, DeleteView, DetailView, ListView, T
from .forms import (
DailyPlannerForm, FastingSettingsForm, RegistrationForm, SickDaySettingsForm, SleepCheckInForm, TimeZoneSettingsForm,
NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm,
BowelHealthCheckInForm, NeckHeadacheCheckInForm, TaskForm, UserSettingsForm, WorkoutForm,
)
from .models import FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, UserSettings, Workout
from .models import BowelHealthCheckIn, FastingPeriod, FastingSettings, NeckHeadacheCheckIn, SickDaySettings, SleepCheckIn, Task, ToothBrushing, UserSettings, Workout
from .services.checkins import (
ANNUAL_PHYSIOTHERAPY_SESSION_ALLOWANCE, LOW_PAIN_STREAK_THRESHOLD, calculate_check_in_streaks,
)
@@ -133,6 +133,43 @@ def pain_level(score):
return 'severe'
def brushing_context(user, today=None):
today = today or localdate_for_user(user)
monday = today - timedelta(days=today.weekday())
records = {record.date: record for record in ToothBrushing.objects.filter(user=user, date__range=(monday, today))}
return {'brushing_days': [{'date': day, 'record': records.get(day)} for day in
(monday + timedelta(days=offset) for offset in range(today.weekday() + 1))]}
def bowel_context(user, selected_date=None, form=None):
today = localdate_for_user(user)
selected_date = selected_date or today
month_start = selected_date.replace(day=1)
first_day = calendar.Calendar(firstweekday=0).monthdatescalendar(selected_date.year, selected_date.month)[0][0]
last_day = calendar.Calendar(firstweekday=0).monthdatescalendar(selected_date.year, selected_date.month)[-1][-1]
records = {entry.check_in_date: entry for entry in BowelHealthCheckIn.objects.filter(user=user, check_in_date__range=(first_day, min(last_day, today)))}
if form is None:
form = BowelHealthCheckInForm(instance=records.get(selected_date), initial={'check_in_date': selected_date}, user=user)
weeks = []
for week in calendar.Calendar(firstweekday=0).monthdatescalendar(selected_date.year, selected_date.month):
cells = []
for day in week:
entry = records.get(day)
periods = []
labels = []
for period, short in (('morning', 'M'), ('afternoon', 'A'), ('evening', 'E')):
score = getattr(entry, f'{period}_severity', None)
periods.append({'short_label': short, 'score': score, 'level': pain_level(score) if score is not None else 'unrecorded'})
labels.append(f'{period.title()}: {score} of 10' if score is not None else f'{period.title()}: not recorded')
cells.append({'date': day, 'periods': periods, 'label': f'{day:%A, %d %B}: ' + '; '.join(labels),
'is_today': day == today, 'is_selected': day == selected_date,
'is_outside_month': day.month != selected_date.month})
weeks.append(cells)
return {'bowel_form': form, 'bowel_selected_date': selected_date, 'bowel_calendar_weeks': weeks,
'bowel_previous_month': month_start - timedelta(days=1),
'bowel_next_month': (month_start + timedelta(days=32)).replace(day=1)}
def check_in_context(user, selected_date=None, form=None, sleep_form=None, active_tab='pain'):
active_tab = active_tab if active_tab in {'pain', 'sleep'} else 'pain'
today = localdate_for_user(user)
@@ -149,13 +186,12 @@ def check_in_context(user, selected_date=None, form=None, sleep_form=None, activ
selected_sleep_check_in = sleep_check_in_by_date.get(selected_date)
if form is None:
initial = {'check_in_date': selected_date}
if selected_check_in is None:
initial.update(neck_pain_severity=0, headache_severity=0)
form = NeckHeadacheCheckInForm(instance=selected_check_in, initial=initial, user=user)
form = NeckHeadacheCheckInForm(
instance=selected_check_in, initial={"check_in_date": selected_date}, user=user
)
if sleep_form is None:
sleep_form = SleepCheckInForm(
instance=selected_sleep_check_in, initial={'wake_up_date': selected_date}, user=user
instance=selected_sleep_check_in, initial={"wake_up_date": selected_date}, user=user
)
calendar_weeks = []
@@ -166,35 +202,38 @@ def check_in_context(user, selected_date=None, form=None, sleep_form=None, activ
for day in week:
check_in = check_in_by_date.get(day)
sleep_check_in = sleep_check_in_by_date.get(day)
if check_in is None:
label = f'{day:%A, %d %B}: pain not recorded'
highest_score = None
level = 'unrecorded'
else:
highest_score = max(
check_in.neck_pain_severity, check_in.headache_severity
)
level = pain_level(highest_score)
label = (
f'{day:%A, %d %B}: neck pain {check_in.neck_pain_severity} of 10; '
f'headache {check_in.headache_severity} of 10'
)
if check_in.had_physiotherapy:
label += '; physiotherapy session'
periods = []
period_labels = []
for period, period_label, short_label in NeckHeadacheCheckIn.PERIODS:
neck = getattr(check_in, f"{period}_neck_pain_severity", None)
headache = getattr(check_in, f"{period}_headache_severity", None)
if neck is not None and headache is not None:
score = max(neck, headache)
level = pain_level(score)
period_labels.append(
f"{period_label}: neck pain {neck} of 10; headache {headache} of 10"
)
else:
score = None
level = "unrecorded"
period_labels.append(f"{period_label}: pain not recorded")
periods.append({"short_label": short_label, "score": score, "level": level})
label = f"{day:%A, %d %B}: " + "; ".join(period_labels)
if check_in is not None and check_in.had_physiotherapy:
label += "; physiotherapy session"
if sleep_check_in is not None:
label += f'; sleep rested {sleep_check_in.rested_score} of 10'
label += f"; sleep rested {sleep_check_in.rested_score} of 10"
if sleep_check_in.watch_sleep_score is not None:
label += f'; watch sleep score {sleep_check_in.watch_sleep_score} percent'
label += f"; watch sleep score {sleep_check_in.watch_sleep_score} percent"
calendar_week.append({
'date': day,
'check_in': check_in,
'sleep_check_in': sleep_check_in,
'highest_score': highest_score,
'level': level,
'label': label,
'is_today': day == today,
'is_selected': day == selected_date,
'is_outside_month': day.month != selected_date.month,
"date": day,
"check_in": check_in,
"sleep_check_in": sleep_check_in,
"periods": periods,
"label": label,
"is_today": day == today,
"is_selected": day == selected_date,
"is_outside_month": day.month != selected_date.month,
})
calendar_weeks.append(calendar_week)
@@ -385,6 +424,46 @@ def save_sleep_checkin(request):
return render_check_in_panel(request, selected_date, sleep_form=form, active_tab='sleep')
@login_required
@require_POST
def toggle_tooth_brushing(request):
day = parse_date(request.POST.get('date', ''))
period = request.POST.get('period')
today = localdate_for_user(request.user)
if day is None or day > today or day < today - timedelta(days=today.weekday()) or period not in ('morning', 'evening'):
return HttpResponse('Invalid brushing day or period.', status=400)
record, _ = ToothBrushing.objects.get_or_create(user=request.user, date=day)
setattr(record, period, not getattr(record, period))
record.save(update_fields=[period])
return render(request, 'planner/partials/tooth_brushing_control.html',
{'brushing_day': day, 'brushing_period': period, 'brushing_done': getattr(record, period)})
@login_required
@require_http_methods(['GET'])
def bowel_health_panel(request):
selected_date = selected_check_in_date(request.GET.get('date'), request.user)
if selected_date is None:
return HttpResponse('Invalid date.', status=400)
return render(request, 'planner/partials/bowel_health_checkin.html', bowel_context(request.user, selected_date))
@login_required
@require_POST
def save_bowel_health_checkin(request):
selected_date = parse_date(request.POST.get('check_in_date', ''))
existing = BowelHealthCheckIn.objects.filter(user=request.user, check_in_date=selected_date).first() if selected_date else None
form = BowelHealthCheckInForm(request.POST, instance=existing, user=request.user)
if form.is_valid():
entry = form.save(commit=False)
entry.user = request.user
entry.save()
if request.headers.get('HX-Request') == 'true':
return render(request, 'planner/partials/bowel_health_checkin.html', bowel_context(request.user, entry.check_in_date))
return redirect(reverse('planner:task-list') + '?bowel_date=' + entry.check_in_date.isoformat() + '#bowel-health-checkin')
return render(request, 'planner/partials/bowel_health_checkin.html', bowel_context(request.user, selected_date, form))
class OwnedTaskQuerysetMixin(LoginRequiredMixin):
"""Constrain every normal task endpoint to the authenticated owner."""
@@ -418,12 +497,14 @@ class TaskListView(LoginRequiredMixin, ListView):
context.update(fasting_widget_context(self.request.user))
context.update(dashboard_weather_context(self.request.user))
context.update(workout_context(self.request.user))
context.update(brushing_context(self.request.user))
profile, _ = UserSettings.objects.get_or_create(user=self.request.user)
context['onboarding_tour'] = onboarding_context(profile)
context.update(check_in_context(
self.request.user, selected_check_in_date(self.request.GET.get('check_in_date'), self.request.user),
active_tab=self.request.GET.get('wellbeing_tab', 'pain')
))
context.update(bowel_context(self.request.user, selected_check_in_date(self.request.GET.get('bowel_date'), self.request.user)))
return context