quantity fields in food log and recipe upload drop zone
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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'),
|
||||
),
|
||||
]
|
||||
@@ -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()
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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.';
|
||||
});
|
||||
@@ -2,7 +2,8 @@
|
||||
{% load static %}
|
||||
{% block title %}Food · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261011-help">
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261015-quantity">
|
||||
{% include 'food/partials/diary_content.html' %}
|
||||
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261011-help"></script>
|
||||
<script defer src="{% static 'food/quantity.js' %}?v=20261015"></script>
|
||||
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261015-quantity"></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,39 +1,19 @@
|
||||
<div id="food-workspace" class="food-page"><div id="food-diary">
|
||||
<div id="food-workspace" class="food-page"><div id="food-quantity-status" class="food-screen-reader" role="status" aria-live="polite"></div><div id="food-diary">
|
||||
<header class="food-heading"><div><p class="eyebrow">Food diary</p><h1>{{ day|date:"l j F Y" }}</h1></div><nav aria-label="Diary dates"><a href="{% url 'food:diary' %}?date={{ previous_day|date:'Y-m-d' }}" aria-label="Previous day">←</a><a href="{% url 'food:diary' %}">Today</a><a href="{% url 'food:diary' %}?date={{ next_day|date:'Y-m-d' }}" aria-label="Next day">→</a></nav></header>
|
||||
<div class="food-layout">
|
||||
<div class="food-meals">
|
||||
{% for meal in meals %}
|
||||
<section class="food-meal" id="meal-{{ meal.key }}" aria-labelledby="meal-title-{{ meal.key }}">
|
||||
<div class="food-meal-heading"><div><h2 id="meal-title-{{ meal.key }}">{{ meal.label }}</h2><p>{{ meal.calories|floatformat:0 }} kcal</p></div><a class="food-add-meal" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal.key }}" aria-label="Add food to {{ meal.label }}">+</a></div>
|
||||
{% include 'food/partials/meal_heading.html' %}
|
||||
{% if meal.entries %}<ul class="food-entry-list">{% for entry in meal.entries %}
|
||||
<li class="food-entry">
|
||||
<div class="food-entry-main">
|
||||
{% with images=entry.attachments.all %}
|
||||
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
|
||||
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
|
||||
{% endwith %}
|
||||
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% 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 %}</small></div>
|
||||
</div>
|
||||
<div class="food-entry-actions"><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
|
||||
</li>
|
||||
{% include 'food/partials/entry.html' %}
|
||||
{% endfor %}</ul>{% else %}<p class="food-empty">Nothing logged yet.</p>{% endif %}
|
||||
</section>
|
||||
{% endfor %}
|
||||
<a class="button" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}">Add food</a>
|
||||
</div>
|
||||
<aside class="food-sidebar" aria-label="Daily nutrition summary">
|
||||
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None %}<p class="food-remaining">{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p><div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}"><span style="width:{{ calorie_percent }}%"></span></div><p>{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal</p>{% else %}<p class="food-remaining">{{ totals.calories_kcal|floatformat:0 }} kcal eaten</p><p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}</section>
|
||||
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
|
||||
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
|
||||
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
|
||||
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% 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 %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}</div>
|
||||
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
|
||||
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
|
||||
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
|
||||
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
|
||||
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
|
||||
</div>
|
||||
</article>{% endfor %}</section>
|
||||
{% include 'food/partials/nutrition_summary.html' %}
|
||||
<section class="food-card food-export" aria-labelledby="food-export-title"><h2 id="food-export-title">Export food diary</h2><p>Download your logged entries as CSV.</p><div class="food-export-actions"><a href="{% url 'food:export' 'week' %}">Current week CSV</a><a href="{% url 'food:export' 'month' %}">Current month CSV</a></div></section>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{% load static %}
|
||||
{% load static food_quantity %}
|
||||
<div id="food-workspace" class="food-form-page">
|
||||
<a href="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">← Back to diary</a>
|
||||
<h1>{{ entry.product_name_snapshot }}</h1>
|
||||
{% if entry.brand_snapshot %}<p>{{ entry.brand_snapshot }}</p>{% endif %}
|
||||
<div class="food-card food-edit-nutrition"><p>{% 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</p>
|
||||
<details><summary>Nutrition information</summary><dl><dt>Fibre</dt><dd>{{ entry.fibre_g|default_if_none:'—' }} g</dd><dt>Sugars</dt><dd>{{ entry.sugars_g|default_if_none:'—' }} g</dd><dt>Salt</dt><dd>{{ entry.salt_g|default_if_none:'—' }} g</dd></dl></details>
|
||||
<div class="food-card food-edit-nutrition"><p>Nutrition at current quantity ({{ entry.quantity|quantity_display }}×):</p><p>{% 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</p>
|
||||
<details><summary>Nutrition information</summary><dl><dt>Fibre</dt><dd>{{ entry.effective_fibre_g|default_if_none:'—' }} g</dd><dt>Sugars</dt><dd>{{ entry.effective_sugars_g|default_if_none:'—' }} g</dd><dt>Salt</dt><dd>{{ entry.effective_salt_g|default_if_none:'—' }} g</dd></dl></details>
|
||||
</div>
|
||||
<form method="post" class="food-card food-entry-form" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}
|
||||
{% include 'food/partials/portion_fields.html' %}
|
||||
<div class="form-field">{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}<small>Multiplies the selected portion. For example, 2 means two of that portion.</small></div>
|
||||
<button class="button" type="submit">Save changes</button>
|
||||
</form>
|
||||
<form method="post" action="{% url 'food:delete' entry.pk %}" onsubmit="return confirm('Delete this food entry?')" hx-post="{% url 'food:delete' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form>
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{% load food_quantity %}
|
||||
<li class="food-entry" id="food-entry-{{ entry.pk }}">
|
||||
<div class="food-entry-main">
|
||||
{% with images=entry.attachments.all %}
|
||||
{% if images %}<div class="food-entry-images">{% for attachment in images %}<a href="{% url 'food:attachment-file' attachment.api_id %}" target="_blank" rel="noopener" aria-label="View attached image{% if attachment.caption %}: {{ attachment.caption }}{% else %} for {{ entry.product_name_snapshot }}{% endif %}"><img src="{% url 'food:attachment-file' attachment.api_id %}" alt="" loading="lazy"></a>{% endfor %}</div>
|
||||
{% elif entry.product and entry.product.image_url %}<img src="{{ entry.product.image_url }}" alt="" loading="lazy">{% endif %}
|
||||
{% endwith %}
|
||||
<div><strong>{{ entry.product_name_snapshot }}</strong>{% if entry.brand_snapshot %}<span>{{ entry.brand_snapshot }}</span>{% endif %}<small>{% 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 %}</small></div>
|
||||
</div>
|
||||
<div class="food-entry-actions"><div class="food-quantity-controls">{% if entry.quantity > 1 %}<form hx-post="{% url 'food:decrement' entry.pk %}" hx-target="#food-entry-{{ entry.pk }}" hx-swap="outerHTML" hx-sync="closest .food-entry-list:queue all" method="post" class="food-quantity-form">{% csrf_token %}<button type="submit" aria-label="Remove one portion of {{ entry.product_name_snapshot }}" title="Remove one portion">−</button></form>{% endif %}<span class="food-quantity" aria-label="Quantity {{ entry.quantity|quantity_display }} portions">{{ entry.quantity|quantity_display }}×</span><form hx-post="{% url 'food:increment' entry.pk %}" hx-target="#food-entry-{{ entry.pk }}" hx-swap="outerHTML" hx-sync="closest .food-entry-list:queue all" method="post" class="food-quantity-form">{% csrf_token %}<button type="submit" aria-label="Add one portion of {{ entry.product_name_snapshot }}" title="Add one portion">+</button></form></div><a href="{% url 'food:edit' entry.pk %}" aria-label="Edit {{ entry.product_name_snapshot }}">Edit</a>{% if entry.product %}<a href="{% url 'food:product-hydration' entry.product.pk %}" aria-label="Drink settings for {{ entry.product_name_snapshot }}">Drink settings</a>{% endif %}</div>
|
||||
</li>
|
||||
@@ -0,0 +1 @@
|
||||
<div class="food-meal-heading" id="food-meal-heading-{{ meal.key }}"><div><h2 id="meal-title-{{ meal.key }}">{{ meal.label }}</h2><p>{{ meal.calories|floatformat:0 }} kcal</p></div><a class="food-add-meal" href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal.key }}" aria-label="Add food to {{ meal.label }}">+</a></div>
|
||||
@@ -0,0 +1,14 @@
|
||||
<div id="food-nutrition-summary">
|
||||
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None and totals.calories_kcal is not None %}<p class="food-remaining">{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p><div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}"><span style="width:{{ calorie_percent }}%"></span></div><p>{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal</p>{% else %}<p class="food-remaining">{% if totals.calories_kcal is None %}Calories unknown{% else %}{{ totals.calories_kcal|floatformat:0 }} kcal eaten{% endif %}</p><p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}</section>
|
||||
<section class="food-macros" id="food-macro-summary" aria-label="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
|
||||
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
|
||||
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
|
||||
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% 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 %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}</div>
|
||||
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
|
||||
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
|
||||
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
|
||||
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
|
||||
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
|
||||
</div>
|
||||
</article>{% endfor %}</section>
|
||||
</div>
|
||||
@@ -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')
|
||||
@@ -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)
|
||||
@@ -26,6 +26,8 @@ urlpatterns = [
|
||||
path('not-found/', views.product_not_found, name='not-found'),
|
||||
path('manual/', views.manual_food, name='manual'),
|
||||
path('log/<int:pk>/', views.edit_entry, name='edit'),
|
||||
path('log/<int:pk>/increment/', views.increment_entry, name='increment'),
|
||||
path('log/<int:pk>/decrement/', views.decrement_entry, name='decrement'),
|
||||
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
|
||||
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
|
||||
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
|
||||
|
||||
+48
-3
@@ -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('<div id="food-quantity-status" hx-swap-oob="innerHTML">{} quantity updated to {} portions.</div>', 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):
|
||||
|
||||
Reference in New Issue
Block a user