From 86e3afaca7a76aaedabe0e9929e17922a2c00016 Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Thu, 15 Oct 2026 20:35:56 +0200 Subject: [PATCH] quantity fields in food log and recipe upload drop zone --- main/food/forms.py | 16 ++++ main/food/migrations/0011_log_quantity.py | 21 +++++ main/food/models.py | 8 ++ main/food/services/diary.py | 18 ++-- main/food/static/food/food.css | 2 + main/food/static/food/quantity.js | 10 +++ main/food/templates/food/diary.html | 5 +- .../food/partials/diary_content.html | 28 +----- .../templates/food/partials/edit_content.html | 7 +- main/food/templates/food/partials/entry.html | 11 +++ .../templates/food/partials/meal_heading.html | 1 + .../food/partials/nutrition_summary.html | 14 +++ main/food/templatetags/food_quantity.py | 10 +++ main/food/test_quantity.py | 80 +++++++++++++++++ main/food/urls.py | 2 + main/food/views.py | 51 ++++++++++- main/planner/services/hydration.py | 6 +- main/recipes/forms.py | 38 ++++---- main/recipes/static/recipes/photo_upload.js | 89 +++++++++++++++++++ main/recipes/static/recipes/recipes.css | 6 ++ main/recipes/templates/recipes/form.html | 6 +- main/recipes/templates/recipes/library.html | 6 +- main/recipes/tests.py | 24 +++++ main/recipes/urls.py | 1 + main/recipes/views.py | 27 +++++- 25 files changed, 420 insertions(+), 67 deletions(-) create mode 100644 main/food/migrations/0011_log_quantity.py create mode 100644 main/food/static/food/quantity.js create mode 100644 main/food/templates/food/partials/entry.html create mode 100644 main/food/templates/food/partials/meal_heading.html create mode 100644 main/food/templates/food/partials/nutrition_summary.html create mode 100644 main/food/templatetags/food_quantity.py create mode 100644 main/food/test_quantity.py create mode 100644 main/recipes/static/recipes/photo_upload.js diff --git a/main/food/forms.py b/main/food/forms.py index a1a8cf4..c8cc1f7 100644 --- a/main/food/forms.py +++ b/main/food/forms.py @@ -149,6 +149,22 @@ class FoodLogForm(forms.ModelForm): return data +class FoodLogEditForm(FoodLogForm): + class Meta(FoodLogForm.Meta): + fields = FoodLogForm.Meta.fields + ('quantity',) + labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)'} + widgets = {**FoodLogForm.Meta.widgets, + 'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})} + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + # Older clients may omit the new field; keep the saved quantity in that case. + self.fields['quantity'].required = False + + def clean_quantity(self): + return self.cleaned_data['quantity'] if self.cleaned_data['quantity'] is not None else self.instance.quantity + + class FoodProductHydrationForm(forms.ModelForm): class Meta: model = FoodProduct diff --git a/main/food/migrations/0011_log_quantity.py b/main/food/migrations/0011_log_quantity.py new file mode 100644 index 0000000..49a44ca --- /dev/null +++ b/main/food/migrations/0011_log_quantity.py @@ -0,0 +1,21 @@ +from decimal import Decimal + +from django.core.validators import MinValueValidator +from django.db import migrations, models +from django.db.models import Q + + +class Migration(migrations.Migration): + dependencies = [('food', '0010_alter_foodlogentry_unit')] + + operations = [ + migrations.AddField( + model_name='foodlogentry', name='quantity', + field=models.DecimalField(decimal_places=2, default=1, max_digits=7, + validators=[MinValueValidator(Decimal('0.01'))]), + ), + migrations.AddConstraint( + model_name='foodlogentry', + constraint=models.CheckConstraint(condition=Q(quantity__gt=0), name='food_positive_log_quantity'), + ), + ] diff --git a/main/food/models.py b/main/food/models.py index ef821b6..686a8c1 100644 --- a/main/food/models.py +++ b/main/food/models.py @@ -1,4 +1,5 @@ import uuid +from decimal import Decimal from django.conf import settings from django.core.exceptions import ValidationError @@ -79,6 +80,8 @@ class FoodLogEntry(models.Model): barcode_snapshot = models.CharField(max_length=64, blank=True) portion_label_snapshot = models.CharField(max_length=100, blank=True) amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) + quantity = models.DecimalField(max_digits=7, decimal_places=2, default=1, + validators=[MinValueValidator(Decimal('0.01'))]) unit = models.CharField(max_length=8, choices=[*Unit.choices, ('servings', 'servings')]) beverage_volume_ml = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) hydration_amount_ml = models.DecimalField(max_digits=10, decimal_places=3, default=0, validators=NON_NEGATIVE) @@ -99,6 +102,11 @@ class FoodLogEntry(models.Model): class Meta: ordering = ('date', 'time', 'pk') + constraints = [models.CheckConstraint(condition=Q(quantity__gt=0), name='food_positive_log_quantity')] + + def effective_nutrient(self, name): + value = getattr(self, name) + return value * self.quantity if value is not None else None def clean(self): super().clean() diff --git a/main/food/services/diary.py b/main/food/services/diary.py index 4de3278..4fcf502 100644 --- a/main/food/services/diary.py +++ b/main/food/services/diary.py @@ -28,22 +28,24 @@ def diary_context(user, day, language='en'): entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product', 'recipe_cooking_run') .prefetch_related('attachments').defer('product__raw_data')) for entry in entries: + entry.effective_calories = entry.effective_nutrient('calories_kcal') run = getattr(entry, 'recipe_cooking_run', None) entry.nutrition_incomplete = bool(run and any( not row.get('complete', False) for row in run.nutrition_snapshot.values())) - totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in - ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')} - fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None] - fibre_incomplete = len(fibre_values) != len(entries) or any( + names = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') + totals = {name: sum((entry.effective_nutrient(name) or ZERO for entry in entries), ZERO) + if all(getattr(entry, name) is not None for entry in entries) else None for name in names} + fibre_incomplete = totals['fibre_g'] is None or any( (getattr(entry, 'recipe_cooking_run', None) and not entry.recipe_cooking_run.nutrition_snapshot.get('fibre_g', {}).get('complete', False)) for entry in entries) - totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None + if fibre_incomplete: + totals['fibre_g'] = sum((entry.effective_nutrient('fibre_g') or ZERO for entry in entries), ZERO) if any(entry.fibre_g is not None for entry in entries) else None meals = [] for key, label in MealType.choices: items = [entry for entry in entries if entry.meal == key] meals.append({'key': key, 'label': label, 'entries': items, - 'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)}) + 'calories': sum((entry.effective_calories or ZERO for entry in items), ZERO)}) macros = [] for label, name, goal, color in ( ('Protein', 'protein_g', goals.protein_goal_g, 'blue'), @@ -63,5 +65,5 @@ def diary_context(user, day, language='en'): return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1), 'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language, 'calorie_goal': calorie_goal, - 'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None, - 'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0} + 'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None and calories is not None else None, + 'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal and calories is not None else 0} diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index 4db6b09..b807977 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -88,3 +88,5 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .inventory-heading-actions{display:flex;align-items:center;justify-content:flex-end;gap:.5rem;flex-wrap:wrap} .inventory-heading-actions .button{min-height:44px} @media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}} +.food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} +.food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0} diff --git a/main/food/static/food/quantity.js b/main/food/static/food/quantity.js new file mode 100644 index 0000000..07b9aa5 --- /dev/null +++ b/main/food/static/food/quantity.js @@ -0,0 +1,10 @@ +document.addEventListener('htmx:responseError', (event) => { + if (!event.detail.elt?.closest('.food-quantity-form')) return; + const status = document.getElementById('food-quantity-status'); + if (status) status.textContent = 'Quantity could not be updated. Reload the diary and try again.'; +}); +document.addEventListener('htmx:sendError', (event) => { + if (!event.detail.elt?.closest('.food-quantity-form')) return; + const status = document.getElementById('food-quantity-status'); + if (status) status.textContent = 'Connection failed. Reload the diary and try again.'; +}); diff --git a/main/food/templates/food/diary.html b/main/food/templates/food/diary.html index e1085b9..1b88ae4 100644 --- a/main/food/templates/food/diary.html +++ b/main/food/templates/food/diary.html @@ -2,7 +2,8 @@ {% load static %} {% block title %}Food · Tasknest{% endblock %} {% block content %} - + {% include 'food/partials/diary_content.html' %} - + + {% endblock %} diff --git a/main/food/templates/food/partials/diary_content.html b/main/food/templates/food/partials/diary_content.html index 5934ba1..bfb507c 100644 --- a/main/food/templates/food/partials/diary_content.html +++ b/main/food/templates/food/partials/diary_content.html @@ -1,39 +1,19 @@ -
+

Food diary

{{ day|date:"l j F Y" }}

{% for meal in meals %}
-

{{ meal.label }}

{{ meal.calories|floatformat:0 }} kcal

+
+ {% include 'food/partials/meal_heading.html' %} {% if meal.entries %}
    {% for entry in meal.entries %} -
  • -
    - {% with images=entry.attachments.all %} - {% if images %}
    {% for attachment in images %}{% endfor %}
    - {% elif entry.product and entry.product.image_url %}{% endif %} - {% endwith %} -
    {{ entry.product_name_snapshot }}{% if entry.brand_snapshot %}{{ entry.brand_snapshot }}{% endif %}{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }}){% if entry.nutrition_incomplete %} · Incomplete nutrition estimate{% endif %}
    -
    -
    Edit{% if entry.product %}Drink settings{% endif %}
    -
  • + {% include 'food/partials/entry.html' %} {% endfor %}
{% else %}

Nothing logged yet.

{% endif %}
{% endfor %} Add food
diff --git a/main/food/templates/food/partials/edit_content.html b/main/food/templates/food/partials/edit_content.html index 98f350d..73a092a 100644 --- a/main/food/templates/food/partials/edit_content.html +++ b/main/food/templates/food/partials/edit_content.html @@ -1,13 +1,14 @@ -{% load static %} +{% load static food_quantity %}
← Back to diary

{{ entry.product_name_snapshot }}

{% if entry.brand_snapshot %}

{{ entry.brand_snapshot }}

{% endif %} -

{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.carbohydrates_g is not None %}{{ entry.carbohydrates_g|floatformat:-1 }}{% else %}—{% endif %} g carbs · {% if entry.protein_g is not None %}{{ entry.protein_g|floatformat:-1 }}{% else %}—{% endif %} g protein · {% if entry.fat_g is not None %}{{ entry.fat_g|floatformat:-1 }}{% else %}—{% endif %} g fat

-
Nutrition information
Fibre
{{ entry.fibre_g|default_if_none:'—' }} g
Sugars
{{ entry.sugars_g|default_if_none:'—' }} g
Salt
{{ entry.salt_g|default_if_none:'—' }} g
+

Nutrition at current quantity ({{ entry.quantity|quantity_display }}×):

{% if entry.effective_calories_kcal is not None %}{{ entry.effective_calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.effective_carbohydrates_g is not None %}{{ entry.effective_carbohydrates_g|floatformat:-1 }}{% else %}—{% endif %} g carbs · {% if entry.effective_protein_g is not None %}{{ entry.effective_protein_g|floatformat:-1 }}{% else %}—{% endif %} g protein · {% if entry.effective_fat_g is not None %}{{ entry.effective_fat_g|floatformat:-1 }}{% else %}—{% endif %} g fat

+
Nutrition information
Fibre
{{ entry.effective_fibre_g|default_if_none:'—' }} g
Sugars
{{ entry.effective_sugars_g|default_if_none:'—' }} g
Salt
{{ entry.effective_salt_g|default_if_none:'—' }} g
{% csrf_token %} {% include 'food/partials/portion_fields.html' %} +
{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}Multiplies the selected portion. For example, 2 means two of that portion.
{% csrf_token %}
diff --git a/main/food/templates/food/partials/entry.html b/main/food/templates/food/partials/entry.html new file mode 100644 index 0000000..741de28 --- /dev/null +++ b/main/food/templates/food/partials/entry.html @@ -0,0 +1,11 @@ +{% load food_quantity %} +
  • +
    + {% with images=entry.attachments.all %} + {% if images %}
    {% for attachment in images %}{% endfor %}
    + {% elif entry.product and entry.product.image_url %}{% endif %} + {% endwith %} +
    {{ entry.product_name_snapshot }}{% if entry.brand_snapshot %}{{ entry.brand_snapshot }}{% endif %}{% if entry.effective_calories is not None %}{{ entry.effective_calories|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {% if entry.portion_label_snapshot %}{{ entry.portion_label_snapshot }} {% endif %}({{ entry.amount|floatformat:-3 }} {{ entry.unit }}){% if entry.nutrition_incomplete %} · Incomplete nutrition estimate{% endif %}
    +
    +
    {% if entry.quantity > 1 %}
    {% csrf_token %}
    {% endif %}{{ entry.quantity|quantity_display }}×
    {% csrf_token %}
    Edit{% if entry.product %}Drink settings{% endif %}
    +
  • diff --git a/main/food/templates/food/partials/meal_heading.html b/main/food/templates/food/partials/meal_heading.html new file mode 100644 index 0000000..e89db6b --- /dev/null +++ b/main/food/templates/food/partials/meal_heading.html @@ -0,0 +1 @@ +

    {{ meal.label }}

    {{ meal.calories|floatformat:0 }} kcal

    +
    diff --git a/main/food/templates/food/partials/nutrition_summary.html b/main/food/templates/food/partials/nutrition_summary.html new file mode 100644 index 0000000..ae50206 --- /dev/null +++ b/main/food/templates/food/partials/nutrition_summary.html @@ -0,0 +1,14 @@ +
    +

    Calories

    {% if calorie_goal is not None and totals.calories_kcal is not None %}

    {% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}

    {{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal

    {% else %}

    {% if totals.calories_kcal is None %}Calories unknown{% else %}{{ totals.calories_kcal|floatformat:0 }} kcal eaten{% endif %}

    No calorie goal. Set one in Settings.

    {% endif %}
    +
    {% for macro in macros %}
    + +
    +

    {{ macro.label }}

    {% if macro.eaten is None %}Unknown{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}

    {% if macro.incomplete %}

    Some entries unknown

    {% elif macro.goal is not None %}

    {% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}

    {% else %}

    No target

    {% endif %}
    + +
    {% endfor %}
    +
    diff --git a/main/food/templatetags/food_quantity.py b/main/food/templatetags/food_quantity.py new file mode 100644 index 0000000..2ee9945 --- /dev/null +++ b/main/food/templatetags/food_quantity.py @@ -0,0 +1,10 @@ +from decimal import Decimal + +from django import template + +register = template.Library() + + +@register.filter +def quantity_display(value): + return format(Decimal(value).normalize(), 'f') diff --git a/main/food/test_quantity.py b/main/food/test_quantity.py new file mode 100644 index 0000000..6d11c24 --- /dev/null +++ b/main/food/test_quantity.py @@ -0,0 +1,80 @@ +from datetime import date +from decimal import Decimal + +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 FoodLogEntry +from .services.diary import diary_context + + +class FoodQuantityTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='quantity-owner', password='password') + self.other = get_user_model().objects.create_user(username='quantity-other', password='password') + self.day = date(2026, 10, 3) + self.entry = FoodLogEntry.objects.create(user=self.user, date=self.day, meal='lunch', + product_name_snapshot='Soup', amount=Decimal('250'), unit='ml', + calories_kcal=Decimal('100'), protein_g=Decimal('4'), carbohydrates_g=Decimal('12'), + fat_g=Decimal('2'), fibre_g=None) + self.client.force_login(self.user) + + def test_increment_preserves_snapshot_and_updates_day(self): + url = reverse('food:increment', args=[self.entry.pk]) + for _ in range(2): + response = self.client.post(url, HTTP_HX_REQUEST='true') + self.assertEqual(response.status_code, 200) + self.assertContains(response, 'hx-swap-oob="outerHTML"') + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('3.00')) + self.assertEqual(self.entry.calories_kcal, Decimal('100')) + self.assertEqual(diary_context(self.user, self.day)['totals']['calories_kcal'], Decimal('300')) + self.assertEqual(diary_context(self.user, date(2026, 10, 4))['totals']['calories_kcal'], 0) + self.assertEqual(diary_context(self.user, self.day)['totals']['fibre_g'], None) + + def test_other_user_cannot_increment(self): + self.client.force_login(self.other) + self.assertEqual(self.client.post(reverse('food:increment', args=[self.entry.pk])).status_code, 404) + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('1.00')) + + def test_fractional_quantity_and_csrf(self): + self.entry.quantity = Decimal('1.25') + self.entry.save(update_fields=['quantity']) + self.assertEqual(diary_context(self.user, self.day)['totals']['calories_kcal'], Decimal('125.00000')) + url = reverse('food:increment', args=[self.entry.pk]) + csrf_client = Client(enforce_csrf_checks=True) + csrf_client.force_login(self.user) + self.assertEqual(csrf_client.post(url).status_code, 403) + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('1.25')) + + def test_edit_quantity_and_decrement_floor(self): + edit_url = reverse('food:edit', args=[self.entry.pk]) + self.assertContains(self.client.get(edit_url), 'Quantity (portions)') + response = self.client.post(edit_url, {'meal': 'lunch', 'amount': '250', 'unit': 'ml', + 'quantity': '2.50'}) + self.assertEqual(response.status_code, 302) + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('2.50')) + self.assertEqual(self.entry.calories_kcal, Decimal('100')) + url = reverse('food:decrement', args=[self.entry.pk]) + response = self.client.post(url, HTTP_HX_REQUEST='true') + self.assertContains(response, '1.5×') + self.assertContains(response, 'Remove one portion of Soup') + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('1.50')) + response = self.client.post(url, HTTP_HX_REQUEST='true') + self.assertContains(response, '0.5×') + self.assertNotContains(response, 'Remove one portion of Soup') + self.assertEqual(self.client.post(url).status_code, 409) + self.entry.refresh_from_db() + self.assertEqual(self.entry.quantity, Decimal('0.50')) + + def test_other_user_cannot_decrement(self): + self.entry.quantity = Decimal('2') + self.entry.save(update_fields=['quantity']) + self.client.force_login(self.other) + self.assertEqual(self.client.post(reverse('food:decrement', args=[self.entry.pk])).status_code, 404) diff --git a/main/food/urls.py b/main/food/urls.py index d4f0378..6f9e8c3 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -26,6 +26,8 @@ urlpatterns = [ path('not-found/', views.product_not_found, name='not-found'), path('manual/', views.manual_food, name='manual'), path('log//', views.edit_entry, name='edit'), + path('log//increment/', views.increment_entry, name='increment'), + path('log//decrement/', views.decrement_entry, name='decrement'), path('log//delete/', views.delete_entry, name='delete'), path('attachments//file/', views.attachment_file, name='attachment-file'), path('product//favourite/', views.toggle_favourite, name='toggle-favourite'), diff --git a/main/food/views.py b/main/food/views.py index 0d64c3e..e008897 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -9,7 +9,9 @@ from urllib.parse import urlencode from django.contrib.auth.decorators import login_required from django.http import FileResponse, Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse from django.contrib import messages -from django.db.models import Q +from django.db.models import Q, F +from django.template.loader import render_to_string +from django.utils.html import format_html from django.db.models import Max from django.db import transaction from django.shortcuts import get_object_or_404, redirect, render @@ -18,7 +20,7 @@ from django.utils.translation import get_language_from_request from django.views.decorators.http import require_GET, require_http_methods, require_POST from django.views.decorators.cache import never_cache -from .forms import FoodLogForm, ManualFoodForm +from .forms import FoodLogEditForm, FoodLogForm, ManualFoodForm from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType from .services.diary import diary_context, selected_date from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search @@ -362,7 +364,7 @@ def edit_entry(request, pk): original_amount = entry.amount original_nutrients = {field: getattr(entry, field) for field in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')} - form = FoodLogForm(request.POST or None, instance=entry, product=product) + form = FoodLogEditForm(request.POST or None, instance=entry, product=product) if request.method == 'POST' and form.is_valid(): updated = form.save(commit=False) factor = updated.amount / original_amount @@ -380,6 +382,8 @@ def edit_entry(request, pk): if product: _save_custom_portion(form, request.user, product, updated) return _diary_response(request, entry.date) + for name in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g'): + setattr(entry, f'effective_{name}', entry.effective_nutrient(name)) template = 'food/partials/edit_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/edit.html' return render(request, template, {'entry': entry, 'form': form, 'product': product, 'portion_options': _portion_options(form, product)}) @@ -394,6 +398,47 @@ def delete_entry(request, pk): return _diary_response(request, day) +@login_required +@require_POST +def increment_entry(request, pk): + return _change_entry_quantity(request, pk, Decimal('1.00')) + + +@login_required +@require_POST +def decrement_entry(request, pk): + return _change_entry_quantity(request, pk, Decimal('-1.00')) + + +def _change_entry_quantity(request, pk, delta): + entry = get_object_or_404(FoodLogEntry, pk=pk, user=request.user) + with transaction.atomic(): + entries = FoodLogEntry.objects.filter(pk=entry.pk, user=request.user) + if delta < 0: + entries = entries.filter(quantity__gt=1) + changed = entries.update(quantity=F('quantity') + delta) + entry.refresh_from_db() + if not changed: + return HttpResponse('Quantity cannot be reduced further. Reload the diary.', status=409) + if request.headers.get('HX-Request') != 'true': + return _diary_response(request, entry.date) + context = diary_context(request.user, entry.date, get_language_from_request(request)) + for meal in context['meals']: + for item in meal['entries']: + if item.pk == entry.pk: + entry = item + break + html = render_to_string('food/partials/entry.html', {'entry': entry}, request=request) + summary = render_to_string('food/partials/nutrition_summary.html', context, request=request) + meal = next(meal for meal in context['meals'] if meal['key'] == entry.meal) + heading = render_to_string('food/partials/meal_heading.html', {'meal': meal, 'day': entry.date}, request=request) + response = HttpResponse(html + summary.replace('id="food-nutrition-summary"', 'id="food-nutrition-summary" hx-swap-oob="outerHTML"', 1) + + heading.replace('id="food-meal-heading-', 'hx-swap-oob="outerHTML" id="food-meal-heading-', 1) + + format_html('
    {} quantity updated to {} portions.
    ', entry.product_name_snapshot, entry.quantity.normalize())) + response['HX-Trigger'] = 'hydrationChanged' + return response + + @login_required @require_http_methods(['GET', 'POST']) def product_hydration(request, pk): diff --git a/main/planner/services/hydration.py b/main/planner/services/hydration.py index c7b6336..5aa0414 100644 --- a/main/planner/services/hydration.py +++ b/main/planner/services/hydration.py @@ -18,7 +18,7 @@ def daily_hydration(user, day): 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) + food = (sum((entry.hydration_amount_ml * entry.quantity 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, @@ -43,9 +43,9 @@ def hydration_context(user, now=None): 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 + totals[entry.date] += entry.hydration_amount_ml * entry.quantity if entry.date == today: - food_today += entry.hydration_amount_ml + food_today += entry.hydration_amount_ml * entry.quantity total = totals[today] last = entries.filter( recorded_at__gte=timezone.make_aware(datetime.combine(today, time.min), zone), diff --git a/main/recipes/forms.py b/main/recipes/forms.py index 76ab2b0..7bd7952 100644 --- a/main/recipes/forms.py +++ b/main/recipes/forms.py @@ -27,7 +27,7 @@ class RecipeForm(forms.ModelForm): 'description': forms.Textarea(attrs={'rows': 3}), 'instructions_markdown': forms.Textarea(attrs={'rows': 10}), 'notes_markdown': forms.Textarea(attrs={'rows': 4}), - 'photo': forms.ClearableFileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}), + 'photo': forms.FileInput(attrs={'accept': 'image/jpeg,image/png,image/webp'}), 'preparation_minutes': forms.NumberInput(attrs={'min': 0}), 'cooking_minutes': forms.NumberInput(attrs={'min': 0}), 'default_servings': forms.NumberInput(attrs={'min': '.01', 'step': '.01'}), @@ -48,22 +48,7 @@ class RecipeForm(forms.ModelForm): def clean_photo(self): photo = self.cleaned_data.get('photo') - if not isinstance(photo, UploadedFile): - return photo - if photo.size > 5 * 1024 * 1024: - raise forms.ValidationError('Choose an image smaller than 5 MB.') - if photo.content_type not in ('image/jpeg', 'image/png', 'image/webp'): - raise forms.ValidationError('Choose a JPEG, PNG, or WebP image.') - try: - image = Image.open(photo) - if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 25_000_000: - raise forms.ValidationError('Choose a valid image smaller than 25 megapixels.') - image.verify() - except (UnidentifiedImageError, OSError): - raise forms.ValidationError('Choose a valid JPEG, PNG, or WebP image.') from None - finally: - photo.seek(0) - return photo + return validate_recipe_photo(photo) def save(self, commit=True): recipe = super().save(commit=False) @@ -73,6 +58,25 @@ class RecipeForm(forms.ModelForm): return recipe +def validate_recipe_photo(photo): + if not isinstance(photo, UploadedFile): + return photo + if photo.size > 5 * 1024 * 1024: + raise forms.ValidationError('Choose an image smaller than 5 MB.') + if photo.content_type not in ('image/jpeg', 'image/png', 'image/webp'): + raise forms.ValidationError('Choose a JPEG, PNG, or WebP image.') + try: + image = Image.open(photo) + if image.format not in ('JPEG', 'PNG', 'WEBP') or image.width * image.height > 25_000_000: + raise forms.ValidationError('Choose a valid image smaller than 25 megapixels.') + image.verify() + except (UnidentifiedImageError, OSError): + raise forms.ValidationError('Choose a valid JPEG, PNG, or WebP image.') from None + finally: + photo.seek(0) + return photo + + class RecipeIngredientForm(forms.ModelForm): class Meta: model = RecipeIngredient diff --git a/main/recipes/static/recipes/photo_upload.js b/main/recipes/static/recipes/photo_upload.js new file mode 100644 index 0000000..6715a7b --- /dev/null +++ b/main/recipes/static/recipes/photo_upload.js @@ -0,0 +1,89 @@ +(() => { + const supported = new Set(['image/jpeg', 'image/png', 'image/webp']); + const check = (file, status) => { + if (!file) return false; + if (!supported.has(file.type)) { + status.textContent = 'Choose a JPEG, PNG or WebP image.'; + return false; + } + if (file.size > 5 * 1024 * 1024) { + status.textContent = 'Choose an image smaller than 5 MB.'; + return false; + } + return true; + }; + const drop = (zone, input, onFile) => { + if (!zone || !input) return; + zone.addEventListener('dragover', event => { + if (!Array.from(event.dataTransfer?.types || []).includes('Files')) return; + event.preventDefault(); + zone.classList.add('is-dragging'); + }); + zone.addEventListener('dragleave', () => zone.classList.remove('is-dragging')); + zone.addEventListener('drop', event => { + event.preventDefault(); + zone.classList.remove('is-dragging'); + if (!event.dataTransfer?.files.length) return; + input.files = event.dataTransfer.files; + onFile(); + }); + }; + + const detail = document.querySelector('[data-photo-upload]'); + if (detail) { + const input = detail.querySelector('input[type=file]'); + const status = detail.querySelector('[data-photo-status]'); + const zone = detail.querySelector('.recipes-photo-placeholder'); + const submit = detail.querySelector('.recipe-photo-submit'); + if (submit) submit.hidden = true; + const upload = () => { + const file = input.files[0]; + if (!check(file, status)) return; + status.textContent = `Uploading ${file.name}…`; + detail.requestSubmit(); + }; + input.addEventListener('change', upload); + drop(zone, input, upload); + } + + const editor = document.querySelector('[data-photo-editor]'); + if (editor) { + const input = editor.querySelector('input[type=file]'); + const zone = editor.querySelector('.recipe-photo-editor__zone'); + const preview = editor.querySelector('[data-photo-preview]'); + const prompt = editor.querySelector('[data-photo-prompt]'); + const remove = editor.querySelector('[data-photo-remove]'); + const checkbox = editor.parentElement.querySelector('input[name=remove_photo]'); + const status = editor.parentElement.querySelector('[data-photo-edit-status]'); + const hasPhoto = !preview.hidden; + let previewUrl; + const selected = () => { + const file = input.files[0]; + if (!file) return; + if (!check(file, status)) { input.value = ''; return; } + if (previewUrl) URL.revokeObjectURL(previewUrl); + previewUrl = URL.createObjectURL(file); + preview.src = previewUrl; + preview.hidden = false; + checkbox.checked = false; + remove.hidden = false; + prompt.firstChild.textContent = 'Click or drop to change photo'; + status.textContent = `${file.name} selected. Save the recipe to upload it.`; + }; + input.addEventListener('change', selected); + drop(zone, input, () => input.dispatchEvent(new Event('change', {bubbles: true}))); + remove.addEventListener('click', () => { + input.value = ''; + if (previewUrl) URL.revokeObjectURL(previewUrl); + previewUrl = null; + preview.removeAttribute('src'); + preview.hidden = true; + checkbox.checked = hasPhoto; + remove.hidden = true; + prompt.firstChild.textContent = 'Click or drop a photo here'; + status.textContent = hasPhoto ? 'Current photo will be removed when you save.' : 'Selected photo cleared.'; + checkbox.dispatchEvent(new Event('change', {bubbles: true})); + input.focus(); + }); + } +})(); diff --git a/main/recipes/static/recipes/recipes.css b/main/recipes/static/recipes/recipes.css index 91f22f7..a178b8f 100644 --- a/main/recipes/static/recipes/recipes.css +++ b/main/recipes/static/recipes/recipes.css @@ -40,3 +40,9 @@ body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[da .recipes-saved-badge{align-self:center;padding:5px 8px;border-radius:99px;background:#e1f2e8;color:#235943;font-size:.72rem;font-weight:700} .cook-later{max-width:850px;margin:0 auto;padding:20px;color:var(--recipe-ink,#25292e)}.cook-later h1{margin:15px 0 5px;font-family:Fraunces,Georgia,serif}.cook-later__list{display:grid;gap:12px;margin-top:24px}.cook-later__item{display:flex;align-items:center;justify-content:space-between;gap:20px;padding:18px;border:1px solid var(--recipe-line,#d0d8d0);border-radius:14px;background:var(--recipe-surface,#fff)}.cook-later__item h2{margin:0;font-size:1.15rem}.cook-later__item p{margin:6px 0}.cook-later__item small{color:var(--recipe-muted,#687178)}.cook-later__item button{min-height:44px;padding:8px 14px;border:1px solid #b94a55;border-radius:9px;background:transparent;color:#a12435;cursor:pointer}body[data-theme=dark] .cook-later__item button{color:#ffb3bb}body[data-theme=dark] .recipes-saved-badge{background:#294d38;color:#b7e8c5}@media(max-width:600px){.cook-later__item{align-items:flex-start;flex-direction:column}} body[data-theme=dark] .cook-later{--recipe-ink:#eaf0ea;--recipe-muted:#afbbb2;--recipe-surface:#202a23;--recipe-line:#435046}body[data-theme=dark] .cook-later a{color:#a7d9b6} +/* Recipe photo upload controls */ +.recipe-photo-upload{min-width:0}.recipe-photo-upload .recipes-photo-placeholder{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:7px;height:220px;padding:20px;border:2px dashed #719d7d;border-radius:14px;color:#24573b;background:#e5f1e8;text-align:center;cursor:pointer;font-family:inherit;transition:border-color .15s,background .15s}.recipe-photo-upload__icon{display:grid;place-items:center;width:42px;height:42px;border-radius:50%;background:#d0e6d6;font-size:1.5rem;font-weight:700}.recipe-photo-upload .recipes-photo-placeholder strong{font-size:1rem}.recipe-photo-upload .recipes-photo-placeholder span:last-of-type{max-width:220px;font-size:.77rem;line-height:1.4}.recipe-photo-upload .recipes-photo-placeholder:hover,.recipe-photo-upload .recipes-photo-placeholder.is-dragging{border-color:#235943;background:#d9ebdf}.recipe-photo-upload .recipes-photo-placeholder:focus-within,.recipe-photo-editor__zone:focus-within{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-upload input[type=file],.recipe-photo-editor input[type=file]{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}.recipe-photo-submit{margin-top:8px;min-height:40px;padding:7px 12px;border:0;border-radius:8px;color:#fff;background:#235943;cursor:pointer}.recipe-photo-submit[hidden]{display:none}.recipe-photo-upload__status{display:block;margin-top:6px;color:var(--recipe-muted);font-size:.75rem} +.recipes-photo-field-label{display:block;margin-bottom:6px;font-size:.81rem;font-weight:700}.recipe-photo-editor{position:relative;max-width:490px}.recipe-photo-editor__zone{position:relative;display:grid;place-items:center;min-height:225px;overflow:hidden;border:2px dashed #719d7d;border-radius:14px;background:#e5f1e8;color:#24573b;text-align:center;cursor:pointer}.recipe-photo-editor__zone.is-dragging,.recipe-photo-editor__zone:hover{border-color:#235943;background:#d9ebdf}.recipe-photo-editor__zone img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}.recipe-photo-editor__zone img[hidden]{display:none}.recipe-photo-editor__prompt{z-index:1;max-width:260px;padding:10px 16px;border-radius:10px;background:rgba(255,255,255,.88);font-size:.9rem;font-weight:700}.recipe-photo-editor__prompt small{display:block;margin-top:4px;font-weight:400}.recipe-photo-editor__remove{position:absolute;z-index:2;top:10px;right:10px;display:grid;place-items:center;width:36px;height:36px;border:0;border-radius:50%;color:#fff;background:#223029;font-size:1.45rem;line-height:1;cursor:pointer}.recipe-photo-editor__remove[hidden]{display:none}.recipe-photo-editor__remove:focus-visible{outline:3px solid #a44cbe;outline-offset:3px}.recipe-photo-editor__status{min-height:1.2em;margin:7px 0 0;color:var(--recipe-muted);font-size:.78rem}.recipe-photo-editor__checkbox[hidden]{display:none}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder,body[data-theme=dark] .recipe-photo-editor__zone{color:#c7e8cf;background:#314d39;border-color:#79a889}body[data-theme=dark] .recipe-photo-upload .recipes-photo-placeholder:hover,body[data-theme=dark] .recipe-photo-editor__zone:hover,body[data-theme=dark] .recipe-photo-editor__zone.is-dragging{background:#3a6246}body[data-theme=dark] .recipe-photo-upload__icon{background:#446f50}body[data-theme=dark] .recipe-photo-editor__prompt{color:#24372a} +.recipes-field .recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center} +.recipes-field label.recipe-photo-editor__zone{display:grid;margin:0;align-items:center;justify-items:center} +.recipe-photo-editor__prompt small,body[data-theme=dark] .recipe-photo-editor__prompt small{color:#415c4b} diff --git a/main/recipes/templates/recipes/form.html b/main/recipes/templates/recipes/form.html index 547eb62..636b2e7 100644 --- a/main/recipes/templates/recipes/form.html +++ b/main/recipes/templates/recipes/form.html @@ -1,13 +1,13 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %} {% block page_class %}recipes-page-content{% endblock %} -{% block content %} +{% block content %}
    ← Back to recipes

    {% if creating %}New recipe{% else %}Edit recipe{% endif %}

    Keep ingredients structured and instructions in Markdown.

    {% csrf_token %} {% if creating %}{% endif %} {% if form.non_field_errors %}{% endif %} -

    Recipe details

    {% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name != 'remove_photo' %}
    {{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}
    {% endif %}{% if field.help_text %}{{ field.help_text }}{% endif %}{% if field.errors %}{% endif %}
    {% endif %}{% endfor %}{% if recipe.photo %}
    Current recipe photo
    {% endif %}
    +

    Recipe details

    {% for field in form %}{% if field.name == 'markdown_revision' %}{{ field }}{% elif field.name == 'photo' %}
    Recipe photo

    {% if field.errors %}{% endif %}
    {% elif field.name != 'remove_photo' %}
    {{ field }}{% if field.name == 'instructions_markdown' or field.name == 'notes_markdown' %}
    {% endif %}{% if field.help_text %}{{ field.help_text }}{% endif %}{% if field.errors %}{% endif %}
    {% endif %}{% endfor %}

    Ingredients

    Add measured ingredients now; product matching can be refined later.

    {{ ingredients.management_form }}{% if ingredients.non_form_errors %}{% endif %}
    {% for ingredient in ingredients %}{% include 'recipes/ingredient_row.html' %}{% endfor %}

    Subrecipes

    Include an independently editable recipe as a component.

    {{ subrecipes.management_form }}{% if subrecipes.non_form_errors %}{% endif %}
    {% for subrecipe in subrecipes %}{% include 'recipes/subrecipe_row.html' %}{% endfor %}
    Cancel{% if creating %}Add a title to start autosave.{% else %}Saved{% endif %}
    -
    {% endblock %} +
    {% endblock %} diff --git a/main/recipes/templates/recipes/library.html b/main/recipes/templates/recipes/library.html index fcfef73..080ba84 100644 --- a/main/recipes/templates/recipes/library.html +++ b/main/recipes/templates/recipes/library.html @@ -2,7 +2,7 @@ {% block title %}Recipes · Tasknest{% endblock %} {% block page_class %}recipes-page-content{% endblock %} {% block content %} - +
    {% endif %}
    - + {% endblock %} diff --git a/main/recipes/tests.py b/main/recipes/tests.py index d839f27..a1325a0 100644 --- a/main/recipes/tests.py +++ b/main/recipes/tests.py @@ -99,6 +99,30 @@ class RecipeWebTests(TestCase): self.client.force_login(self.other) self.assertEqual(self.client.get(photo_url).status_code, 404) + def test_detail_photo_drop_zone_upload_validates_and_scopes(self): + recipe = Recipe.objects.create(owner=self.user, title='Photo target') + image = BytesIO() + Image.new('RGB', (2, 2), '#217857').save(image, format='PNG') + url = reverse('recipes:photo-upload', args=[recipe.api_id]) + with TemporaryDirectory() as media_root, override_settings(MEDIA_ROOT=media_root): + self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])), + 'Add a recipe photo') + self.assertEqual(self.client.get(url).status_code, 405) + self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile( + 'bad.png', b'not an image', content_type='image/png')}).status_code, 302) + recipe.refresh_from_db() + self.assertFalse(recipe.photo) + response = self.client.post(url, {'photo': SimpleUploadedFile( + 'good.png', image.getvalue(), content_type='image/png')}) + self.assertEqual(response.status_code, 302) + recipe.refresh_from_db() + self.assertTrue(recipe.photo) + self.assertContains(self.client.get(reverse('recipes:detail', args=[recipe.api_id])), + 'Photo of Photo target') + self.client.force_login(self.other) + self.assertEqual(self.client.post(url, {'photo': SimpleUploadedFile( + 'other.png', image.getvalue(), content_type='image/png')}).status_code, 404) + def test_markdown_round_trip_and_safe_rendering(self): source = '# Dinner\n\n- [x] Prepare\n- [ ] Cook\n\n**Ready** [bad](javascript:alert(1))' recipe = Recipe.objects.create(owner=self.user, title='Dinner', instructions_markdown=source) diff --git a/main/recipes/urls.py b/main/recipes/urls.py index 39f99d4..4ab05f5 100644 --- a/main/recipes/urls.py +++ b/main/recipes/urls.py @@ -17,6 +17,7 @@ urlpatterns = [ path('new/autosave/', views.autosave_new, name='autosave-new'), path('/', views.detail, name='detail'), path('/edit/', views.edit, name='edit'), + path('/photo/upload/', views.photo_upload, name='photo-upload'), path('/cook/', views.cook, name='cook'), path('/cook/finish/', views.cook_finish, name='cook-finish'), path('/autosave/', views.autosave, name='autosave'), diff --git a/main/recipes/views.py b/main/recipes/views.py index 6d2d2a7..e846b06 100644 --- a/main/recipes/views.py +++ b/main/recipes/views.py @@ -2,6 +2,7 @@ import json import uuid from django.conf import settings +from django.core.exceptions import ValidationError from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.decorators import login_required @@ -17,7 +18,7 @@ from food.models import MealType from PIL import Image from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet, - RecipeSubstitutionForm) + RecipeSubstitutionForm, validate_recipe_photo) from .models import (CookLater, Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSelection, RecipeSubrecipe, RecipeUse) from .services import cook_later @@ -364,6 +365,7 @@ def _edit(request, recipe=None, allow_draft_resume=False): return render(request, 'recipes/form.html', { 'form': form, 'ingredients': ingredients, 'subrecipes': subrecipes, 'recipe': recipe, 'creating': creating, 'new_draft_id': recipe.api_id if creating else None, + 'existing_photo': bool(old_photo), }) @@ -389,6 +391,29 @@ def edit(request, identifier): return _edit(request, get_object_or_404(_owned(request.user), api_id=identifier)) +@login_required +@require_POST +def photo_upload(request, identifier): + recipe = get_object_or_404(_owned(request.user), api_id=identifier) + uploaded = request.FILES.get('photo') + if uploaded is None: + messages.error(request, 'Choose a photo to upload.') + return redirect('recipes:detail', identifier=identifier) + try: + validate_recipe_photo(uploaded) + except ValidationError as exc: + messages.error(request, exc.messages[0]) + return redirect('recipes:detail', identifier=identifier) + old_name = recipe.photo.name if recipe.photo else '' + storage = recipe.photo.storage + recipe.photo = uploaded + recipe.save(update_fields=('photo', 'updated_at')) + if old_name and old_name != recipe.photo.name: + transaction.on_commit(lambda: storage.delete(old_name)) + messages.success(request, 'Recipe photo uploaded.') + return redirect('recipes:detail', identifier=identifier) + + @login_required @require_POST def autosave(request, identifier):