adding food logging, polish + demo updates

This commit is contained in:
Joren de Graaf
2026-10-03 21:44:38 +02:00
parent 90b21a39fc
commit be49b66dae
7 changed files with 184 additions and 13 deletions
+1 -1
View File
@@ -254,7 +254,7 @@ class BowelHealthCheckInForm(forms.ModelForm):
**{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')}}
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)
+111 -3
View File
@@ -1,12 +1,16 @@
"""Reset a safe, self-contained demo account with representative Tasknest data."""
from datetime import time, timedelta
from datetime import datetime, time, timedelta
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils import timezone
from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
from planner.models import (
BowelHealthCheckIn,
FastingPause,
FastingPeriod,
FastingSettings,
@@ -14,12 +18,76 @@ from planner.models import (
SickDaySettings,
SleepCheckIn,
Task,
ToothBrushing,
UserSettings,
WaterIntakeEntry,
Workout,
WorkoutCompletion,
)
from planner.services.fasting import synchronize_fasting_periods
from planner.timezones import DEFAULT_TIME_ZONE, localdate_for_user
from planner.timezones import DEFAULT_TIME_ZONE, localdate_for_user, timezone_for_user
def _seed_food(user, today):
"""Create local demo foods without network calls or third-party assets."""
product_data = (
('Greek yoghurt', 'Demo dairy', Unit.GRAM, '73', '4', '8', '2', '0'),
('Banana', '', Unit.GRAM, '89', '22.8', '1.1', '0.3', '2.6'),
('Wholegrain sandwich', 'Demo bakery', Unit.GRAM, '250', '42', '10', '4', '6'),
('Tomato soup', 'Home made', Unit.MILLILITRE, '35', '5', '1.2', '1', None),
('Pasta with vegetables', 'Home made', Unit.GRAM, '145', '23', '5', '3', '2.5'),
('Almonds', '', Unit.GRAM, '579', '10', '21', '50', '12.5'),
)
products = {}
for name, brand, unit, kcal, carbs, protein, fat, fibre in product_data:
products[name] = FoodProduct.objects.create(
owner=user, product_name=name, brand=brand, base_unit=unit,
energy_kcal_100=Decimal(kcal), carbohydrates_100=Decimal(carbs),
protein_100=Decimal(protein), fat_100=Decimal(fat),
fibre_100=Decimal(fibre) if fibre is not None else None,
source=FoodProduct.Source.MANUAL,
)
yoghurt = products['Greek yoghurt']
soup = products['Tomato soup']
for product in (yoghurt, soup):
FoodFavourite.objects.create(user=user, product=product)
FoodPortion.objects.create(user=user, product=yoghurt, label='My bowl',
amount=Decimal('250'), unit=Unit.GRAM, is_default=True)
FoodPortion.objects.create(user=user, product=soup, label='One mug',
amount=Decimal('250'), unit=Unit.MILLILITRE)
def log(days_ago, meal, name, amount, label=''):
product = products[name]
amount = Decimal(str(amount))
factor = amount / Decimal('100')
def consumed(value):
return (value * factor).quantize(Decimal('0.001')) if value is not None else None
FoodLogEntry.objects.create(
user=user, date=today - timedelta(days=days_ago), meal=meal, product=product,
product_name_snapshot=product.product_name, brand_snapshot=product.brand,
portion_label_snapshot=label, amount=amount, unit=product.base_unit,
calories_kcal=consumed(product.energy_kcal_100),
carbohydrates_g=consumed(product.carbohydrates_100),
protein_g=consumed(product.protein_100), fat_g=consumed(product.fat_100),
fibre_g=consumed(product.fibre_100), source=product.source,
)
for days_ago, meal, name, amount, label in (
(0, MealType.BREAKFAST, 'Greek yoghurt', 250, 'My bowl'),
(0, MealType.BREAKFAST, 'Banana', 120, ''),
(0, MealType.LUNCH, 'Wholegrain sandwich', 100, ''),
(0, MealType.LUNCH, 'Tomato soup', 250, 'One mug'),
(0, MealType.DINNER, 'Pasta with vegetables', 180, ''),
(0, MealType.SNACKS, 'Almonds', 30, ''),
(1, MealType.BREAKFAST, 'Greek yoghurt', 200, ''),
(1, MealType.DINNER, 'Pasta with vegetables', 200, ''),
(2, MealType.LUNCH, 'Wholegrain sandwich', 100, ''),
(5, MealType.SNACKS, 'Banana', 100, ''),
):
log(days_ago, meal, name, amount, label)
return len(products), 10
class Command(BaseCommand):
@@ -46,6 +114,14 @@ class Command(BaseCommand):
profile.longitude = '4.904100'
profile.onboarding_enabled = False
profile.onboarding_step = 0
profile.daily_water_goal_ml = 2000
profile.daily_calorie_goal = 2000
profile.carbohydrate_goal_g = Decimal('250.0')
profile.protein_goal_g = Decimal('100.0')
profile.fat_goal_g = Decimal('70.0')
profile.ntfy_url = ''
profile.ntfy_enabled = False
profile.ntfy_last_tested_at = None
profile.save()
SickDaySettings.objects.update_or_create(user=user, defaults={'enabled': False, 'recovery_date': None})
@@ -56,10 +132,37 @@ class Command(BaseCommand):
SleepCheckIn.objects.filter(user=user).delete()
FastingPause.objects.filter(user=user).delete()
FastingPeriod.objects.filter(user=user).delete()
WaterIntakeEntry.objects.filter(user=user).delete()
ToothBrushing.objects.filter(user=user).delete()
BowelHealthCheckIn.objects.filter(user=user).delete()
FoodLogEntry.objects.filter(user=user).delete()
FoodFavourite.objects.filter(user=user).delete()
FoodPortion.objects.filter(user=user).delete()
FoodProduct.objects.filter(owner=user).delete()
now = timezone.now()
today = localdate_for_user(user, now)
ToothBrushing.objects.create(user=user, date=today - timedelta(days=1), morning=True, evening=True)
ToothBrushing.objects.create(user=user, date=today, morning=True, evening=False)
for days_ago, severity, note in (
(2, 3, 'A slightly unsettled day.'),
(1, 1, 'Feeling better after lunch.'),
(0, 0, 'Feeling well today.'),
):
BowelHealthCheckIn.objects.create(
user=user, check_in_date=today - timedelta(days=days_ago),
morning_severity=severity, morning_note=note,
afternoon_severity=max(0, severity - 1),
evening_severity=max(0, severity - 1),
)
yesterday = today - timedelta(days=1)
local_zone = timezone_for_user(user)
for hour, amount in ((9, 350), (12, 500), (16, 400)):
WaterIntakeEntry.objects.create(user=user, amount_ml=amount,
recorded_at=timezone.make_aware(datetime.combine(yesterday, time(hour, 0)), local_zone))
WaterIntakeEntry.objects.create(user=user, amount_ml=350, recorded_at=now)
laundry = Task.objects.create(
owner=user,
title='Run the washing machine',
@@ -168,11 +271,16 @@ class Command(BaseCommand):
'fasting_start_time': time(20, 0),
'fasting_duration_minutes': 16 * 60,
'tracking_started_at': now - timedelta(days=3),
'last_phase_notification_at': None,
},
)
synchronize_fasting_periods(fasting, now)
food_products, food_entries = _seed_food(user, today)
verb = 'Created' if created else 'Reset'
self.stdout.write(self.style.SUCCESS(
f'{verb} demo user {username!r}: 5 tasks, 2 workouts, 4 pain check-ins, and 4 sleep check-ins.'
f'{verb} demo user {username!r}: 5 tasks, 2 workouts, 4 pain check-ins, '
f'4 sleep check-ins, 3 bowel check-ins, 4 water entries, '
f'{food_products} foods, and {food_entries} food logs.'
))
@@ -1,5 +1,5 @@
<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>
<header class="checkin-panel__header"><div><p class="eyebrow">Daily wellbeing</p><h2 id="bowel-heading">Gut health</h2><p>Record how your gut 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>
@@ -7,11 +7,11 @@
<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>
</div><div class="form-actions"><button class="button button--compact" type="submit">Save gut health 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:health' %}?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:health' %}?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__exports" aria-label="Export bowel tracker data"><a class="button button--secondary button--compact" href="{% url 'planner:bowel-export' 'week' %}?date={{ bowel_selected_date|date:'Y-m-d' }}">Export week</a><a class="button button--secondary button--compact" href="{% url 'planner:bowel-export' 'month' %}?date={{ bowel_selected_date|date:'Y-m-d' }}">Export month</a></div><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>
</header><div class="checkin-calendar__exports" aria-label="Export gut health data"><a class="button button--secondary button--compact" href="{% url 'planner:bowel-export' 'week' %}?date={{ bowel_selected_date|date:'Y-m-d' }}">Export week</a><a class="button button--secondary button--compact" href="{% url 'planner:bowel-export' 'month' %}?date={{ bowel_selected_date|date:'Y-m-d' }}">Export month</a></div><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:health' %}?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>
+46 -1
View File
@@ -9,7 +9,8 @@ from django.utils import timezone
from django.urls import reverse
from .models import FastingPause, FastingPeriod, FastingSettings, SickDaySettings, Task
from .models import UserSettings, WaterIntakeEntry
from .models import BowelHealthCheckIn, ToothBrushing, UserSettings, WaterIntakeEntry
from .timezones import localdate_for_user
from .services.hydration import hydration_context
from .forms import DAILY_FASTING_DURATION_CHOICES, FastingSettingsForm
from .services.deferrals import (
@@ -1025,10 +1026,17 @@ class OnboardingTests(TestCase):
class DemoSeedCommandTests(TestCase):
def test_command_creates_and_repeatedly_restores_only_the_demo_account(self):
from food.models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
other = get_user_model().objects.create_user(username="private-user", password="password")
private_task = Task.objects.create(
owner=other, title="Private task", scheduled_for=timezone.localdate()
)
private_food = FoodProduct.objects.create(owner=other, product_name='Private snack')
private_food_entry = FoodLogEntry.objects.create(
user=other, date=timezone.localdate(), meal=MealType.SNACKS,
product=private_food, product_name_snapshot='Private snack', amount=100, unit=Unit.GRAM,
)
call_command("seed_demo")
@@ -1039,17 +1047,54 @@ class DemoSeedCommandTests(TestCase):
self.assertEqual(NeckHeadacheCheckIn.objects.filter(user=demo).count(), 4)
self.assertEqual(SleepCheckIn.objects.filter(user=demo).count(), 4)
self.assertTrue(FastingSettings.objects.get(user=demo).enabled)
self.assertEqual(FoodProduct.objects.filter(owner=demo).count(), 6)
self.assertEqual(FoodLogEntry.objects.filter(user=demo).count(), 10)
self.assertEqual(FoodFavourite.objects.filter(user=demo).count(), 2)
self.assertEqual(FoodPortion.objects.filter(user=demo).count(), 2)
self.assertEqual(WaterIntakeEntry.objects.filter(user=demo).count(), 4)
self.assertEqual(ToothBrushing.objects.filter(user=demo).count(), 2)
self.assertEqual(BowelHealthCheckIn.objects.filter(user=demo).count(), 3)
profile = UserSettings.objects.get(user=demo)
self.assertEqual(profile.time_zone, "Europe/Amsterdam")
self.assertFalse(profile.onboarding_enabled)
self.assertEqual(profile.daily_calorie_goal, 2000)
self.assertEqual(profile.carbohydrate_goal_g, 250)
self.assertEqual(profile.protein_goal_g, 100)
self.assertEqual(profile.fat_goal_g, 70)
self.assertFalse(profile.ntfy_enabled)
today = localdate_for_user(demo)
self.assertEqual(FoodLogEntry.objects.filter(user=demo, date=today).count(), 6)
self.assertEqual(set(FoodLogEntry.objects.filter(user=demo, date=today).values_list('meal', flat=True)),
set(MealType.values))
bowl = FoodPortion.objects.get(user=demo, label='My bowl')
self.assertTrue(bowl.is_default)
self.assertEqual(FoodLogEntry.objects.get(user=demo, date=today, portion_label_snapshot='My bowl').calories_kcal, 182.5)
self.assertTrue(Task.objects.filter(owner=demo, title="Fold the clothes", parent_task__isnull=False).exists())
Task.objects.create(owner=demo, title="Temporary demo edit", scheduled_for=timezone.localdate())
FoodProduct.objects.create(owner=demo, product_name='Temporary demo food')
banana = FoodProduct.objects.get(owner=demo, product_name='Banana')
FoodFavourite.objects.create(user=demo, product=banana)
FoodPortion.objects.create(user=demo, product=banana, label='Temporary portion', amount=100, unit=Unit.GRAM)
FoodLogEntry.objects.filter(user=demo, portion_label_snapshot='My bowl').update(product_name_snapshot='Edited demo food')
profile.ntfy_url = 'https://ntfy.example.com/old-demo-topic'
profile.ntfy_enabled = True
profile.save()
call_command("seed_demo")
self.assertEqual(Task.objects.filter(owner=demo).count(), 5)
self.assertFalse(Task.objects.filter(owner=demo, title="Temporary demo edit").exists())
self.assertEqual(FoodProduct.objects.filter(owner=demo).count(), 6)
self.assertEqual(FoodLogEntry.objects.filter(user=demo).count(), 10)
self.assertFalse(FoodLogEntry.objects.filter(user=demo, product_name_snapshot='Edited demo food').exists())
self.assertEqual(FoodFavourite.objects.filter(user=demo).count(), 2)
self.assertEqual(FoodPortion.objects.filter(user=demo).count(), 2)
profile.refresh_from_db()
self.assertFalse(profile.ntfy_enabled)
self.assertEqual(profile.ntfy_url, '')
self.assertTrue(Task.objects.filter(pk=private_task.pk, owner=other).exists())
self.assertTrue(FoodProduct.objects.filter(pk=private_food.pk, owner=other).exists())
self.assertTrue(FoodLogEntry.objects.filter(pk=private_food_entry.pk, user=other).exists())
class UserTimeZoneTests(TestCase):
+1 -1
View File
@@ -60,7 +60,7 @@ ONBOARDING_STEPS = (
{
'target': 'wellbeing',
'title': 'Keep a lightweight wellbeing record',
'copy': 'Open Health for pain, sleep, and bowel check-ins, with calendars that make past days easy to revisit.',
'copy': 'Open Health for pain, sleep, and gut health check-ins, with calendars that make past days easy to revisit.',
},
{
'target': 'fasting',