Enhancements
This commit is contained in:
@@ -164,8 +164,13 @@ class NtfySettingsForm(forms.ModelForm):
|
||||
class HydrationGoalForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = UserSettings
|
||||
fields = ('daily_water_goal_ml',)
|
||||
labels = {'daily_water_goal_ml': 'Daily water goal (ml)'}
|
||||
fields = ('daily_water_goal_ml', 'auto_count_food_drinks', 'include_liquid_foods',
|
||||
'show_hydration_breakdown', 'allow_manual_hydration_adjustments')
|
||||
labels = {'daily_water_goal_ml': 'Daily water goal (ml)',
|
||||
'auto_count_food_drinks': 'Automatically count drinks from Food Diary',
|
||||
'include_liquid_foods': 'Include soups and other liquid foods',
|
||||
'show_hydration_breakdown': 'Show manual and Food Diary breakdown',
|
||||
'allow_manual_hydration_adjustments': 'Allow manual hydration entries'}
|
||||
widgets = {'daily_water_goal_ml': forms.NumberInput(attrs={'min': 250, 'max': 10000, 'step': 1})}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import uuid
|
||||
|
||||
import django.core.validators
|
||||
from django.db import migrations, models
|
||||
from django.db.models import Q
|
||||
|
||||
|
||||
def backfill_water_ids(apps, schema_editor):
|
||||
Entry = apps.get_model('planner', 'WaterIntakeEntry')
|
||||
for entry in Entry.objects.filter(api_id__isnull=True).iterator():
|
||||
Entry.objects.filter(pk=entry.pk).update(api_id=uuid.uuid4())
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('planner', '0020_usersettings_fibre_goal_g')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='usersettings', name='auto_count_food_drinks', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='include_liquid_foods', field=models.BooleanField(default=False)),
|
||||
migrations.AddField(model_name='usersettings', name='show_hydration_breakdown', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='allow_manual_hydration_adjustments', field=models.BooleanField(default=True)),
|
||||
migrations.AddField(model_name='usersettings', name='hydration_beverage_rules', field=models.JSONField(blank=True, default=dict)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='api_id', field=models.UUIDField(null=True)),
|
||||
migrations.RunPython(backfill_water_ids, migrations.RunPython.noop),
|
||||
migrations.AlterField(model_name='waterintakeentry', name='api_id', field=models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='beverage_type', field=models.CharField(default='water', max_length=32)),
|
||||
migrations.AddField(model_name='waterintakeentry', name='idempotency_key', field=models.CharField(blank=True, max_length=128)),
|
||||
migrations.AlterField(model_name='waterintakeentry', name='amount_ml', field=models.DecimalField(
|
||||
decimal_places=3, max_digits=10,
|
||||
validators=[django.core.validators.MinValueValidator(0.001), django.core.validators.MaxValueValidator(3000)])),
|
||||
migrations.AddConstraint(model_name='waterintakeentry', constraint=models.UniqueConstraint(
|
||||
fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''),
|
||||
name='planner_unique_water_idempotency')),
|
||||
]
|
||||
+12
-1
@@ -1,9 +1,11 @@
|
||||
from datetime import time
|
||||
import uuid
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.core.validators import MaxValueValidator, MinValueValidator
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.urls import reverse
|
||||
from django.utils import timezone
|
||||
|
||||
@@ -120,6 +122,11 @@ class UserSettings(models.Model):
|
||||
daily_water_goal_ml = models.PositiveIntegerField(
|
||||
default=2000, validators=[MinValueValidator(250), MaxValueValidator(10000)],
|
||||
)
|
||||
auto_count_food_drinks = models.BooleanField(default=True)
|
||||
include_liquid_foods = models.BooleanField(default=False)
|
||||
show_hydration_breakdown = models.BooleanField(default=True)
|
||||
allow_manual_hydration_adjustments = models.BooleanField(default=True)
|
||||
hydration_beverage_rules = models.JSONField(default=dict, blank=True)
|
||||
daily_calorie_goal = models.PositiveIntegerField(null=True, blank=True)
|
||||
carbohydrate_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)])
|
||||
protein_goal_g = models.DecimalField(max_digits=7, decimal_places=1, null=True, blank=True, validators=[MinValueValidator(0)])
|
||||
@@ -380,13 +387,17 @@ class FastingPause(models.Model):
|
||||
|
||||
|
||||
class WaterIntakeEntry(models.Model):
|
||||
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='water_entries')
|
||||
amount_ml = models.PositiveIntegerField(validators=[MinValueValidator(1), MaxValueValidator(3000)])
|
||||
amount_ml = models.DecimalField(max_digits=10, decimal_places=3, validators=[MinValueValidator(0.001), MaxValueValidator(3000)])
|
||||
beverage_type = models.CharField(max_length=32, default='water')
|
||||
idempotency_key = models.CharField(max_length=128, blank=True)
|
||||
recorded_at = models.DateTimeField(default=timezone.now, db_index=True)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-recorded_at', '-pk')
|
||||
constraints = [models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''), name='planner_unique_water_idempotency')]
|
||||
|
||||
|
||||
class FastingPeriod(models.Model):
|
||||
|
||||
@@ -1,9 +1,29 @@
|
||||
from datetime import datetime, time, timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import UserSettings, WaterIntakeEntry
|
||||
from planner.timezones import timezone_for_user
|
||||
from food.models import FoodLogEntry
|
||||
|
||||
|
||||
ZERO = Decimal('0')
|
||||
|
||||
|
||||
def daily_hydration(user, day):
|
||||
zone = timezone_for_user(user)
|
||||
start = timezone.make_aware(datetime.combine(day, time.min), zone)
|
||||
end = timezone.make_aware(datetime.combine(day + timedelta(days=1), time.min), zone)
|
||||
settings = UserSettings.objects.get_or_create(user=user)[0]
|
||||
manual = sum((entry.amount_ml for entry in WaterIntakeEntry.objects.filter(
|
||||
user=user, recorded_at__gte=start, recorded_at__lt=end)), ZERO)
|
||||
food = (sum((entry.hydration_amount_ml for entry in FoodLogEntry.objects.filter(user=user, date=day)), ZERO)
|
||||
if settings.auto_count_food_drinks else ZERO)
|
||||
total = manual + food
|
||||
return {'date': day, 'manual_ml': manual, 'food_ml': food, 'total_ml': total,
|
||||
'goal_ml': settings.daily_water_goal_ml,
|
||||
'remaining_ml': max(ZERO, Decimal(settings.daily_water_goal_ml) - total)}
|
||||
|
||||
|
||||
def hydration_context(user, now=None):
|
||||
@@ -12,11 +32,20 @@ def hydration_context(user, now=None):
|
||||
start = today - timedelta(days=today.weekday())
|
||||
week_start = timezone.make_aware(datetime.combine(start, time.min), zone)
|
||||
week_end = timezone.make_aware(datetime.combine(start + timedelta(days=7), time.min), zone)
|
||||
goal = UserSettings.objects.get_or_create(user=user)[0].daily_water_goal_ml
|
||||
settings = UserSettings.objects.get_or_create(user=user)[0]
|
||||
goal = settings.daily_water_goal_ml
|
||||
entries = WaterIntakeEntry.objects.filter(user=user, recorded_at__gte=week_start, recorded_at__lt=week_end)
|
||||
totals = {start + timedelta(days=i): 0 for i in range(7)}
|
||||
totals = {start + timedelta(days=i): ZERO for i in range(7)}
|
||||
for entry in entries:
|
||||
totals[timezone.localtime(entry.recorded_at, zone).date()] += entry.amount_ml
|
||||
manual_today = totals[today]
|
||||
food_today = ZERO
|
||||
if settings.auto_count_food_drinks:
|
||||
for entry in FoodLogEntry.objects.filter(user=user, date__gte=start,
|
||||
date__lt=start + timedelta(days=7)):
|
||||
totals[entry.date] += entry.hydration_amount_ml
|
||||
if entry.date == today:
|
||||
food_today += entry.hydration_amount_ml
|
||||
total = totals[today]
|
||||
last = entries.filter(
|
||||
recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone),
|
||||
@@ -31,6 +60,9 @@ def hydration_context(user, now=None):
|
||||
'state': state, 'state_label': {'none': 'no water logged', 'partial': 'partial goal', 'goal': 'goal met'}[state],
|
||||
'today': day == today})
|
||||
return {'hydration_total': total, 'hydration_goal': goal, 'hydration_percent': percent,
|
||||
'hydration_manual': manual_today, 'hydration_food': food_today,
|
||||
'hydration_show_breakdown': settings.show_hydration_breakdown,
|
||||
'hydration_allow_manual': settings.allow_manual_hydration_adjustments,
|
||||
'hydration_visual': visual, 'hydration_fill_y': 168 - round(visual * 1.22),
|
||||
'hydration_fill_height': round(visual * 1.22), 'hydration_last': last,
|
||||
'hydration_last_time': timezone.localtime(last.recorded_at, zone).strftime('%H:%M') if last else None,
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite">
|
||||
<article id="hydration-widget" class="hydration-widget" aria-labelledby="hydration-heading" aria-live="polite" hx-get="{% url 'planner:hydration-panel' %}" hx-trigger="hydrationChanged from:body" hx-swap="outerHTML">
|
||||
<p class="eyebrow">Daily hydration</p>
|
||||
<h2 id="hydration-heading">Water</h2>
|
||||
<div class="hydration-widget__main">
|
||||
<div class="hydration-widget__stats">
|
||||
<p class="hydration-widget__total">{{ hydration_total|floatformat:0 }} <span>/ {{ hydration_goal }} ml</span></p>
|
||||
<p>{{ hydration_percent }}% of daily goal</p>
|
||||
{% if hydration_show_breakdown %}<p class="hydration-widget__breakdown">Manual: {{ hydration_manual|floatformat:0 }} ml · Food Diary drinks: {{ hydration_food|floatformat:0 }} ml</p>{% endif %}
|
||||
<div class="hydration-widget__track" role="progressbar" aria-label="Daily water goal" aria-valuenow="{{ hydration_visual }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ hydration_visual }}%"></span></div>
|
||||
</div>
|
||||
{% include 'planner/partials/hydration_bottle.html' %}
|
||||
</div>
|
||||
<div class="hydration-widget__actions">
|
||||
{% if hydration_allow_manual %}<div class="hydration-widget__actions">
|
||||
<form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit" name="amount_ml" value="250">+250 ml</button><button type="submit" name="amount_ml" value="500">+500 ml</button></form>
|
||||
<details class="hydration-widget__other"><summary>Other</summary><form method="post" action="{% url 'planner:hydration-add' %}" hx-post="{% url 'planner:hydration-add' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<label for="hydration-amount">Amount (ml)</label><input id="hydration-amount" name="amount_ml" type="number" min="1" max="3000" step="1" required inputmode="numeric"><button type="submit">Add</button></form></details>
|
||||
</div>
|
||||
{% if hydration_error %}<p class="hydration-widget__error" role="alert">Enter a whole amount from 1 to 3000 ml.</p>{% endif %}
|
||||
<div class="hydration-widget__info">{% if hydration_last %}<span>Last: {{ hydration_last.amount_ml }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No water logged today</span>{% endif %}</div>
|
||||
<div class="hydration-widget__info">{% if hydration_last %}<span>Last manual entry: {{ hydration_last.amount_ml|floatformat:0 }} ml at {{ hydration_last_time }}</span><form method="post" action="{% url 'planner:hydration-undo' %}" hx-post="{% url 'planner:hydration-undo' %}" hx-target="#hydration-widget" hx-swap="outerHTML">{% csrf_token %}<button type="submit">Undo last</button></form>{% else %}<span>No manual water logged today</span>{% endif %}</div>
|
||||
{% endif %}
|
||||
<div class="hydration-widget__week"><p>This week</p><div class="hydration-widget__days">{% for day in hydration_days %}<span class="hydration-widget__day hydration-widget__day--{{ day.state }}{% if day.today %} hydration-widget__day--today{% endif %}" title="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}" aria-label="{{ day.date|date:'l' }}: {{ day.total }} ml, {{ day.state_label }}">{{ day.label }}</span>{% endfor %}</div></div>
|
||||
</article>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
<section class="settings-card"><h2>First-run help</h2><p>{% if onboarding_enabled %}The guided tour is ready to continue on your dashboard.{% else %}Help is off. You can run the tour again whenever you want.{% endif %}</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="onboarding"><button class="button" type="submit" name="action" value="restart">Run feature tour</button><button class="text-link" type="submit" name="action" value="disable">Turn help off</button></form></section>
|
||||
<section class="settings-card"><h2>Location & weather</h2><p>Location is optional and private. It is used only to retrieve your forecast.</p><form method="post" data-geolocation-form>{% csrf_token %}<input type="hidden" name="section" value="location">{% for field in profile_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<button class="button button--secondary" type="button" data-use-location>Use my current location</button><span data-location-status role="status"></span><button class="button" type="submit">Save location</button></form></section>
|
||||
<section class="settings-card"><h2>Sick Day Mode</h2><p>Temporarily defer routine work while you recover.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="sick-day">{% for field in sick_form %}{% if field.name == 'enabled' %}<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Enable Sick Day Mode</strong><small>Give routine tasks a rest while you recover.</small></span>{{ field }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ field.errors }}</div>{% else %}<div class="form-field">{{ field.label_tag }}{{ field }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endif %}{% endfor %}<button class="button" type="submit">Save Sick Day settings</button></form></section>
|
||||
<section class="settings-card"><h2>Hydration</h2><p>Set your daily water goal.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save water goal</button></form></section>
|
||||
<section class="settings-card"><h2>Hydration</h2><p>Set your daily fluid goal and how drinks are counted.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="hydration">{% for field in hydration_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save hydration settings</button></form></section>
|
||||
<section class="settings-card"><h2>Food</h2><p>Set optional daily nutrition goals. Exercise calories do not change these goals.</p><form method="post">{% csrf_token %}<input type="hidden" name="section" value="food">{% for field in food_goal_form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food goals</button></form></section>
|
||||
<section class="settings-card"><h2>API access</h2><p>Create scoped tokens for apps that need access to your food log or kitchen inventory.</p><a class="button" href="{% url 'food:tokens' %}">Manage API tokens</a></section>
|
||||
<section class="settings-card" aria-labelledby="ntfy-title">
|
||||
|
||||
@@ -8,7 +8,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, hydration_add, hydration_undo, test_ntfy, gitea_activity,
|
||||
bowel_health_panel, save_bowel_health_checkin, toggle_tooth_brushing, hydration_add, hydration_undo, hydration_panel, test_ntfy, gitea_activity,
|
||||
)
|
||||
|
||||
app_name = 'planner'
|
||||
@@ -33,6 +33,7 @@ urlpatterns = [
|
||||
path('teeth/toggle/', toggle_tooth_brushing, name='tooth-brushing-toggle'),
|
||||
path('hydration/add/', hydration_add, name='hydration-add'),
|
||||
path('hydration/undo/', hydration_undo, name='hydration-undo'),
|
||||
path('hydration/panel/', hydration_panel, name='hydration-panel'),
|
||||
path('bowel-health/panel/', bowel_health_panel, name='bowel-health-panel'),
|
||||
path('bowel-health/save/', save_bowel_health_checkin, name='bowel-health-save'),
|
||||
path('check-ins/export/<str:period>/', export_pain_csv, name='pain-export'),
|
||||
|
||||
+12
-2
@@ -14,7 +14,7 @@ from django.urls import reverse, reverse_lazy
|
||||
from django.utils import timezone
|
||||
from django.utils.http import url_has_allowed_host_and_scheme
|
||||
from django.utils.dateparse import parse_date
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||
from django.views.generic import CreateView, DeleteView, DetailView, ListView, TemplateView, UpdateView
|
||||
|
||||
@@ -771,7 +771,7 @@ def user_settings(request):
|
||||
hydration_goal_form = HydrationGoalForm(request.POST, instance=profile)
|
||||
if hydration_goal_form.is_valid():
|
||||
hydration_goal_form.save()
|
||||
messages.success(request, 'Your daily water goal was saved.')
|
||||
messages.success(request, 'Your hydration settings were saved.')
|
||||
return redirect('planner:user-settings')
|
||||
elif section == 'food':
|
||||
food_goal_form = FoodGoalForm(request.POST, instance=profile)
|
||||
@@ -877,6 +877,8 @@ def test_ntfy(request):
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_add(request):
|
||||
if not UserSettings.objects.get_or_create(user=request.user)[0].allow_manual_hydration_adjustments:
|
||||
return HttpResponse(status=403)
|
||||
form = WaterIntakeForm(request.POST)
|
||||
if form.is_valid():
|
||||
WaterIntakeEntry.objects.create(user=request.user, amount_ml=form.cleaned_data['amount_ml'])
|
||||
@@ -888,12 +890,20 @@ def hydration_add(request):
|
||||
@login_required
|
||||
@require_POST
|
||||
def hydration_undo(request):
|
||||
if not UserSettings.objects.get_or_create(user=request.user)[0].allow_manual_hydration_adjustments:
|
||||
return HttpResponse(status=403)
|
||||
context = hydration_context(request.user)
|
||||
if context['hydration_last']:
|
||||
context['hydration_last'].delete()
|
||||
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
|
||||
|
||||
|
||||
@login_required
|
||||
@require_GET
|
||||
def hydration_panel(request):
|
||||
return render(request, 'planner/partials/hydration_widget.html', hydration_context(request.user))
|
||||
|
||||
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def register(request):
|
||||
if request.user.is_authenticated:
|
||||
|
||||
Reference in New Issue
Block a user