adding food logging, phase 5

This commit is contained in:
Joren de Graaf
2026-10-03 21:25:56 +02:00
parent e7ddb0ea28
commit 8d1afab9e8
20 changed files with 627 additions and 73 deletions
+105 -5
View File
@@ -1,27 +1,70 @@
from django import forms
from decimal import Decimal
from .models import FoodLogEntry, FoodProduct, MealType
from .models import FoodLogEntry, FoodPortion, FoodProduct
class ManualFoodForm(forms.ModelForm):
basis_amount = forms.DecimalField(min_value=Decimal('0.001'), max_digits=10, decimal_places=3,
initial=100, label='Nutrition basis amount')
class Meta:
model = FoodProduct
fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'fibre_100', 'sugars_100', 'salt_100')
labels = {
'energy_kcal_100': 'Calories per 100 g or ml',
'carbohydrates_100': 'Carbohydrates per 100 g or ml',
'protein_100': 'Protein per 100 g or ml',
'fat_100': 'Fat per 100 g or ml',
'energy_kcal_100': 'Calories for base quantity',
'carbohydrates_100': 'Carbohydrates for base quantity',
'protein_100': 'Protein for base quantity',
'fat_100': 'Fat for base quantity',
'fibre_100': 'Fibre for base quantity (optional)',
'sugars_100': 'Sugars for base quantity (optional)',
'salt_100': 'Salt for base quantity (optional)',
}
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super().__init__(*args, **kwargs)
self.fields['barcode'].required = False
for field in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100'):
self.fields[field].required = True
def clean_barcode(self):
barcode = self.cleaned_data['barcode'].strip()
if barcode and (not barcode.isascii() or not barcode.isdigit()):
raise forms.ValidationError('Enter a numeric barcode.')
if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exists():
raise forms.ValidationError('This barcode is already saved in your foods.')
return barcode
def clean(self):
data = super().clean()
basis = data.get('basis_amount')
if basis:
factor = Decimal('100') / basis
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100'):
value = data.get(name)
if value is not None and value * factor > Decimal('9999999.999'):
self.add_error(name, 'This amount is too large for the chosen base quantity.')
return data
def save(self, commit=True):
product = super().save(commit=False)
factor = Decimal('100') / self.cleaned_data['basis_amount']
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100'):
value = self.cleaned_data[name]
setattr(product, name, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
if commit:
product.save()
return product
class FoodLogForm(forms.ModelForm):
portion = forms.ChoiceField(label='Portion', required=False)
save_portion = forms.BooleanField(required=False, label='Save custom amount as a portion')
new_portion_label = forms.CharField(max_length=100, required=False, label='New portion label')
make_default = forms.BooleanField(required=False, label='Use this portion by default')
class Meta:
model = FoodLogEntry
fields = ('meal', 'amount', 'unit', 'portion_label_snapshot')
@@ -33,9 +76,66 @@ class FoodLogForm(forms.ModelForm):
self.product = product or getattr(self.instance, 'product', None)
if self.product and self.product.pk:
self.fields['unit'].initial = self.product.base_unit
unit = self.product.base_unit
choices = [('custom', 'Custom amount'), ('base', f'100 {unit}')]
if self.product.serving_amount and self.product.serving_unit == unit:
choices.append(('serving', f'Serving — {self.product.serving_amount:g} {unit}'))
portions = list(FoodPortion.objects.filter(product=self.product, user=self.product.owner).order_by('label'))
choices.extend((f'portion:{item.pk}', f'{item.label} — {item.amount:g} {item.unit}') for item in portions)
self.fields['portion'].choices = choices
self.portions = {str(item.pk): item for item in portions}
default = next((item for item in portions if item.is_default), None)
if default is None:
last = self.product.log_entries.filter(user=self.product.owner).order_by('-created_at').first()
default = next((item for item in portions if last and item.label == last.portion_label_snapshot and
item.amount == last.amount and item.unit == last.unit), None)
if self.instance.pk:
selected = next((item for item in portions if item.label == self.instance.portion_label_snapshot and
item.amount == self.instance.amount and item.unit == self.instance.unit), None)
self.fields['portion'].initial = f'portion:{selected.pk}' if selected else 'custom'
elif default:
self.fields['portion'].initial = f'portion:{default.pk}'
self.fields['amount'].initial = default.amount
elif self.product.serving_amount and self.product.serving_unit == unit:
self.fields['portion'].initial = 'serving'
self.fields['amount'].initial = self.product.serving_amount
else:
self.fields['portion'].initial = 'base'
self.fields['amount'].initial = 100
self.fields['amount'].required = False
def clean_unit(self):
unit = self.cleaned_data['unit']
if self.product and unit != self.product.base_unit:
raise forms.ValidationError('Use the same unit as the product nutrition basis.')
return unit
def clean(self):
data = super().clean()
selected = data.get('portion') or 'custom'
if not self.product or not selected:
return data
if selected == 'base':
data['amount'], data['portion_label_snapshot'] = Decimal('100'), ''
elif selected == 'serving':
data['amount'], data['portion_label_snapshot'] = self.product.serving_amount, 'Serving'
elif selected.startswith('portion:'):
portion = self.portions.get(selected.partition(':')[2])
if not portion:
self.add_error('portion', 'Choose a valid portion.')
else:
data['amount'], data['portion_label_snapshot'] = portion.amount, portion.label
elif selected == 'custom':
if data.get('amount') is None or data['amount'] <= 0:
self.add_error('amount', 'Enter an amount greater than zero.')
if data.get('save_portion'):
label = (data.get('new_portion_label') or '').strip()
if not label:
self.add_error('new_portion_label', 'Enter a label for the saved portion.')
elif FoodPortion.objects.filter(user=self.product.owner, product=self.product, label=label).exists():
self.add_error('new_portion_label', 'You already have a portion with this label.')
else:
data['portion_label_snapshot'] = label
elif data.get('make_default'):
self.add_error('make_default', 'Save the portion before making it the default.')
return data
@@ -0,0 +1,19 @@
# Generated by Django 6.1.1 on 2026-10-03 19:10
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddConstraint(
model_name='foodportion',
constraint=models.UniqueConstraint(condition=models.Q(('is_default', True)), fields=('user', 'product'), name='food_one_default_portion'),
),
]
+6 -1
View File
@@ -117,9 +117,14 @@ class FoodPortion(models.Model):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
constraints = [models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label')]
constraints = [
models.UniqueConstraint(fields=('user', 'product', 'label'), name='food_unique_portion_label'),
models.UniqueConstraint(fields=('user', 'product'), condition=Q(is_default=True), name='food_one_default_portion'),
]
def clean(self):
super().clean()
if self.product_id and self.user_id and self.product.owner_id != self.user_id:
raise ValidationError({'product': 'Choose one of your own food products.'})
if self.product_id and self.unit != self.product.base_unit:
raise ValidationError({'unit': 'Use the same unit as the product nutrition basis.'})
+1 -1
View File
@@ -24,7 +24,7 @@ def selected_date(request):
def diary_context(user, day):
goals, _ = UserSettings.objects.get_or_create(user=user)
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product'))
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product').defer('product__raw_data'))
totals = {name: sum((getattr(entry, name) or ZERO for entry in entries), ZERO) for name in
('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g')}
meals = []
+3
View File
@@ -2,3 +2,6 @@
.food-product-image{display:block;max-width:180px;max-height:180px;object-fit:contain;background:#fff;border-radius:1rem;margin:0 auto 1rem}
.food-tabs,.food-actions{display:flex;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-tabs a{padding:.55rem .9rem;border-radius:2rem;border:1px solid currentColor;text-decoration:none}.food-tabs a[aria-current=page]{background:#62bd70;color:#111;border-color:#62bd70}.food-product-list a,.food-result-button{display:flex;align-items:center;gap:.8rem;width:100%;text-align:left}.food-product-list img{width:58px;height:58px;object-fit:contain;background:#fff;border-radius:.6rem}.food-product-list strong,.food-product-list small{display:block}.food-result-button{border:0;background:none;color:inherit;font:inherit;cursor:pointer;min-height:44px}.food-barcode-form{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap;margin:1rem 0}.food-barcode-form input{min-width:130px;flex:1}.food-attribution{font-size:.85rem;opacity:.8}
.food-scanner{max-width:620px;margin:1.5rem auto 6rem}.food-scanner-header{display:flex;align-items:center;gap:1rem}.food-scanner-header a{display:grid;place-items:center;min-width:44px;min-height:44px;font-size:2rem;text-decoration:none}.food-camera-frame{position:relative;aspect-ratio:4/3;background:#111;border-radius:1rem;overflow:hidden}.food-camera-frame video{width:100%;height:100%;object-fit:cover}.food-scan-guide{position:absolute;inset:25% 10%;border:3px solid #62bd70;border-radius:.8rem;pointer-events:none}.food-mobile-switch{display:none}@media(max-width:760px){.food-mobile-switch{position:fixed;bottom:env(safe-area-inset-bottom,0px);left:50%;transform:translateX(-50%);display:flex;gap:.3rem;background:#222;color:#fff;padding:.35rem;border-radius:2rem;z-index:20;box-shadow:0 2px 15px #0008}.food-mobile-switch a,.food-mobile-switch span{display:grid;place-items:center;min-width:110px;min-height:44px;padding:.2rem 1rem;border-radius:2rem;color:inherit;text-decoration:none}.food-mobile-switch [aria-current=page]{background:#555}}
.food-detail-title{display:flex;align-items:center;justify-content:space-between;gap:1rem}.food-favourite-form{flex:none}.food-favourite{min-width:44px;min-height:44px;border:0;background:none;color:#62bd70;font-size:2rem;cursor:pointer}.food-product-list li{display:flex;align-items:center;justify-content:space-between;gap:.5rem}.food-product-list li>a{flex:1;min-width:0}.food-product-list li>.food-favourite-form{margin:0}
/* V1 polish: keep the date and search titles from crowding the useful content. */
.food-heading{align-items:end;margin-bottom:1.1rem}.food-heading h1{font-size:clamp(2rem,3.2vw,3.2rem);line-height:1.08;margin:.25rem 0 0}.food-heading nav a:nth-child(2){border-radius:999px;padding:0 1rem}.food-form-page h1{font-size:clamp(2.3rem,4vw,3.8rem);line-height:1.05;margin:.45rem 0 1rem;overflow-wrap:anywhere}.food-product-list li>a{text-decoration:none}.food-product-list li>a:hover strong,.food-product-list li>a:focus-visible strong{text-decoration:underline}.food-list-empty{border-style:dashed!important;opacity:.72}.food-entry>a{min-width:44px;min-height:44px;display:grid;place-items:center}.food-entry-main strong{overflow-wrap:anywhere}.food-export{margin-top:1.25rem}.food-export p{margin:.3rem 0 1rem;opacity:.75}.food-export-actions{display:flex;gap:.6rem;flex-wrap:wrap}.food-export-actions a{display:inline-flex;align-items:center;min-height:44px;padding:.55rem .8rem;border:1px solid currentColor;border-radius:999px;text-decoration:none}.food-export-actions a:hover,.food-export-actions a:focus-visible{background:#62bd7028}.food-entry-form{display:grid;gap:1rem}.food-entry-form [data-food-custom-fields],.food-entry-form [data-food-save-fields]{display:grid;gap:1rem}.food-entry-form .settings-switch-row{margin:.25rem 0}.food-edit-nutrition p{line-height:1.55}.food-edit-nutrition details{margin-top:.7rem}.food-entry-form .settings-switch input[type=checkbox]{min-height:0;padding:0;border:0;border-radius:0}.food-entry-form .settings-switch__copy strong{font-weight:700}.food-form-page .food-card .form-field label{line-height:1.35}@media(max-width:760px){.food-heading{align-items:start}.food-heading nav{flex:none}.food-heading nav a:nth-child(2){padding:0 .6rem}.food-heading h1{font-size:clamp(1.55rem,6vw,2.2rem)}.food-export{margin-top:.5rem}}
+19
View File
@@ -0,0 +1,19 @@
(() => {
const select = document.querySelector('[data-food-portion-choice]');
if (!select) return;
const amount = document.querySelector('#id_amount');
const custom = document.querySelector('[data-food-custom-fields]');
const amountField = document.querySelector('[data-food-amount-field]');
const save = document.querySelector('#id_save_portion');
const saveFields = document.querySelector('[data-food-save-fields]');
const sync = () => {
const customSelected = select.value === 'custom';
custom.hidden = !customSelected;
amountField.hidden = !customSelected;
if (!customSelected) amount.value = select.selectedOptions[0].dataset.amount || '100';
saveFields.hidden = !customSelected || !save.checked;
};
select.addEventListener('change', sync);
save.addEventListener('change', sync);
sync();
})();
+1 -46
View File
@@ -2,50 +2,5 @@
{% block title %}Add food · Tasknest{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}">
<div id="food-workspace" class="food-form-page">
<a href="{% url 'food:diary' %}?date={{ day|date:'Y-m-d' }}">← Back to diary</a>
<h1>Add food</h1>
{% if product %}
<section class="food-card">
{% if product.image_url %}<img class="food-product-image" src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}
<h2>{{ product.product_name }}</h2>
{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}
<p>Per 100 {{ product.base_unit }}: {% if product.energy_kcal_100 is not None %}{{ product.energy_kcal_100|floatformat:0 }} kcal{% else %}— kcal{% endif %}</p>
<details><summary>Nutrition information</summary><dl>
<dt>Carbohydrates</dt><dd>{{ product.carbohydrates_100|default_if_none:'—' }} g</dd>
<dt>Protein</dt><dd>{{ product.protein_100|default_if_none:'—' }} g</dd>
<dt>Fat</dt><dd>{{ product.fat_100|default_if_none:'—' }} g</dd>
<dt>Sugars</dt><dd>{{ product.sugars_100|default_if_none:'—' }} g</dd>
<dt>Fibre</dt><dd>{{ product.fibre_100|default_if_none:'—' }} g</dd>
<dt>Salt</dt><dd>{{ product.salt_100|default_if_none:'—' }} g</dd>
</dl></details>
{% if product.source == 'openfoodfacts' %}<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/product/{{ product.barcode }}" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %}
</section>
<form method="post" class="food-card" hx-post="{% url 'food:add' %}" hx-target="#food-workspace" hx-push-url="{% url 'food:diary' %}?date={{ day|date:'Y-m-d' }}" hx-swap="outerHTML">
{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="product" value="{{ product.pk }}">
{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}
<button class="button" type="submit">Log food</button>
</form>
{% else %}
<form method="get" class="food-search">
<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><input type="hidden" name="tab" value="{{ tab }}">
<label for="food-query">Search your foods</label><input id="food-query" name="q" value="{{ query }}" type="search"><button class="button" type="submit">Search</button>
</form>
<nav class="food-tabs" aria-label="Local food lists">
<a {% if tab == 'recent' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=recent&amp;q={{ query|urlencode }}">Recent</a>
<a {% if tab == 'favourites' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=favourites&amp;q={{ query|urlencode }}">Favourites</a>
<a {% if tab == 'mine' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=mine&amp;q={{ query|urlencode }}">My foods</a>
</nav>
<ul class="food-product-list">{% for item in products %}
<li><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;product={{ item.pk }}">
{% if item.image_url %}<img src="{{ item.image_url }}" alt="" loading="lazy">{% endif %}<span><strong>{{ item.product_name }}</strong>{% if item.brand %}<small>{{ item.brand }}</small>{% endif %}<small>{% if item.energy_kcal_100 is not None %}{{ item.energy_kcal_100|floatformat:0 }} kcal / 100 {{ item.base_unit }}{% else %}— kcal / 100 {{ item.base_unit }}{% endif %}</small></span>
</a></li>{% empty %}<li>No foods in this list yet.</li>{% endfor %}</ul>
<div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a>
<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Scan barcode</a>
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;q={{ query|urlencode }}">Search Open Food Facts</a></div>
<form method="post" action="{% url 'food:import-product' %}" class="food-barcode-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-barcode">Barcode</label><input id="food-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up barcode</button></form>
<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
{% endif %}
</div>
{% if not product %}<nav class="food-mobile-switch" aria-label="Add food method"><span aria-current="page">Search</span><a href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Barcode</a></nav>{% endif %}
{% include 'food/partials/add_content.html' %}
{% endblock %}
+4 -1
View File
@@ -1,3 +1,6 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit food log · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><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"><p>{% if entry.calories_kcal is not None %}{{ entry.calories_kcal|floatformat:0 }} kcal{% else %}— kcal{% endif %} · {{ entry.carbohydrates_g|default_if_none:'—' }} g carbs · {{ entry.protein_g|default_if_none:'—' }} g protein · {{ entry.fat_g|default_if_none:'—' }} 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><form method="post" class="food-card" hx-post="{% url 'food:edit' entry.pk %}" hx-target="#food-workspace" hx-swap="outerHTML" hx-push-url="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">{% csrf_token %}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<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" hx-push-url="{% url 'food:diary' %}?date={{ entry.date|date:'Y-m-d' }}">{% csrf_token %}<button type="submit" class="button button--secondary">Delete entry</button></form></div>{% endblock %}
{% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}">
{% include 'food/partials/edit_content.html' %}
{% endblock %}
+1 -1
View File
@@ -1,3 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Create food · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Enter nutrition per 100 g or 100 ml. Missing optional values stay unknown.</p><form method="post" class="food-card">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food</button></form></div>{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Enter nutrition for the base quantity and unit you choose. Missing optional values stay unknown.</p><form method="post" class="food-card">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Save food</button></form></div>{% endblock %}
@@ -0,0 +1,49 @@
{% load static %}
<div id="food-workspace" class="food-form-page">
<a href="{% url 'food:diary' %}?date={{ day|date:'Y-m-d' }}">← Back to diary</a>
<h1>Add food</h1>
{% if product %}
<section class="food-card">
{% if product.image_url %}<img class="food-product-image" src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}
<div class="food-detail-title"><h2>{{ product.product_name }}</h2>{% include "food/partials/favourite_button.html" with is_favourite=product.is_favourite %}</div>
{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}
<p>Per 100 {{ product.base_unit }}: {% if product.energy_kcal_100 is not None %}{{ product.energy_kcal_100|floatformat:0 }} kcal{% else %}— kcal{% endif %}</p>
<details><summary>Nutrition information</summary><dl>
<dt>Carbohydrates</dt><dd>{{ product.carbohydrates_100|default_if_none:'—' }} g</dd>
<dt>Protein</dt><dd>{{ product.protein_100|default_if_none:'—' }} g</dd>
<dt>Fat</dt><dd>{{ product.fat_100|default_if_none:'—' }} g</dd>
<dt>Sugars</dt><dd>{{ product.sugars_100|default_if_none:'—' }} g</dd>
<dt>Fibre</dt><dd>{{ product.fibre_100|default_if_none:'—' }} g</dd>
<dt>Salt</dt><dd>{{ product.salt_100|default_if_none:'—' }} g</dd>
</dl></details>
{% if product.source == 'openfoodfacts' %}<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/product/{{ product.barcode }}" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %}
</section>
<form method="post" class="food-card" hx-post="{% url 'food:add' %}" hx-target="#food-workspace" hx-swap="outerHTML">
{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="product" value="{{ product.pk }}">
{% include 'food/partials/portion_fields.html' %}
<button class="button" type="submit">Log food</button>
</form>
{% else %}
<form method="get" class="food-search">
<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><input type="hidden" name="tab" value="{{ tab }}">
<label for="food-query">Search your foods</label><input id="food-query" name="q" value="{{ query }}" type="search"><button class="button" type="submit">Search</button>
</form>
<nav class="food-tabs" aria-label="Local food lists">
<a {% if tab == 'overview' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=overview">For you</a>
<a {% if tab == 'recent' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=recent&amp;q={{ query|urlencode }}">Recent</a>
<a {% if tab == 'favourites' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=favourites&amp;q={{ query|urlencode }}">Favourites</a>
<a {% if tab == 'mine' %}aria-current="page"{% endif %} href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;tab=mine&amp;q={{ query|urlencode }}">My foods</a>
</nav>
{% if tab == 'overview' and not query %}
<div id="food-favourites-list"><h2>Favourites</h2>{% include 'food/partials/product_list.html' with products=favourites %}</div>
<div id="food-recents-list"><h2>Recent</h2>{% include 'food/partials/product_list.html' with products=recents %}</div>
{% else %}{% include 'food/partials/product_list.html' with products=products %}{% endif %}
<div class="food-actions"><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a>
<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Scan barcode</a>
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;q={{ query|urlencode }}">Search Open Food Facts</a></div>
<form method="post" action="{% url 'food:import-product' %}" class="food-barcode-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="food-barcode">Barcode</label><input id="food-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up barcode</button></form>
<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
{% endif %}
</div>
{% if product %}<script src="{% static 'food/portions.js' %}" defer></script>{% endif %}
{% if not product %}<nav class="food-mobile-switch" aria-label="Add food method"><span aria-current="page">Search</span><a href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Barcode</a></nav>{% endif %}
@@ -13,6 +13,7 @@
<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="Macronutrients">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}"><div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%"{% endif %}><span>{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div><div><h3>{{ macro.label }}</h3><p>{{ macro.eaten|floatformat:1 }} g eaten</p>{% if 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></article>{% endfor %}</section>
<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>
</div>
@@ -0,0 +1,15 @@
{% load static %}
<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>
<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' %}
<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>
</div>
{% if product %}<script src="{% static 'food/portions.js' %}" defer></script>{% endif %}
@@ -0,0 +1,4 @@
<form method="post" action="{% url 'food:toggle-favourite' product.pk %}" class="food-favourite-form" hx-post="{% url 'food:toggle-favourite' product.pk %}" hx-target="{% if is_list and tab == 'favourites' and is_favourite %}closest li{% else %}this{% endif %}" hx-swap="outerHTML">
{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><input type="hidden" name="tab" value="{{ tab }}"><input type="hidden" name="is_list" value="{% if is_list %}1{% else %}0{% endif %}">
<button type="submit" class="food-favourite" aria-label="{% if is_favourite %}Remove {{ product.product_name }} from favourites{% else %}Add {{ product.product_name }} to favourites{% endif %}" aria-pressed="{% if is_favourite %}true{% else %}false{% endif %}" title="{% if is_favourite %}Remove from favourites{% else %}Add to favourites{% endif %}">{% if is_favourite %}♥{% else %}♡{% endif %}</button>
</form>
@@ -0,0 +1,3 @@
{% include 'food/partials/favourite_button.html' %}
<div id="food-favourites-list" hx-swap-oob="outerHTML"><h2>Favourites</h2>{% include 'food/partials/product_list.html' with products=favourites %}</div>
<div id="food-recents-list" hx-swap-oob="outerHTML"><h2>Recent</h2>{% include 'food/partials/product_list.html' with products=recents %}</div>
@@ -0,0 +1,15 @@
<div class="form-field">{{ form.meal.label_tag }}{{ form.meal }}{{ form.meal.errors }}</div>
{% if product %}
<div class="form-field"><label for="food-portion-choice">Portion</label><select id="food-portion-choice" name="portion" data-food-portion-choice>{% for option in portion_options %}<option value="{{ option.value }}" data-amount="{{ option.amount }}" {% if form.portion.value == option.value %}selected{% endif %}>{{ option.label }}</option>{% endfor %}</select>{{ form.portion.errors }}</div>
<div class="form-field" data-food-amount-field>{{ form.amount.label_tag }}{{ form.amount }}{{ form.amount.errors }}<small>{{ product.base_unit }}</small></div><input type="hidden" name="unit" value="{{ product.base_unit }}">
<div data-food-custom-fields><div class="form-field">{{ form.portion_label_snapshot.label_tag }}{{ form.portion_label_snapshot }}{{ form.portion_label_snapshot.errors }}</div>
<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Save custom amount as a portion</strong><small>Use this amount again without typing it.</small></span>{{ form.save_portion }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ form.save_portion.errors }}</div>
<div data-food-save-fields><div class="form-field">{{ form.new_portion_label.label_tag }}{{ form.new_portion_label }}{{ form.new_portion_label.errors }}</div>
<div class="settings-switch-row"><label class="settings-switch"><span class="settings-switch__copy"><strong>Use this portion by default</strong><small>Preselect it next time you log this food.</small></span>{{ form.make_default }}<span class="settings-switch__track" aria-hidden="true"></span></label>{{ form.make_default.errors }}</div>
</div>
</div>
{% else %}
<div class="form-field">{{ form.amount.label_tag }}{{ form.amount }}{{ form.amount.errors }}</div>
<div class="form-field">{{ form.unit.label_tag }}{{ form.unit }}{{ form.unit.errors }}</div>
<div class="form-field">{{ form.portion_label_snapshot.label_tag }}{{ form.portion_label_snapshot }}{{ form.portion_label_snapshot.errors }}</div>
{% endif %}
@@ -0,0 +1,5 @@
<ul class="food-product-list">{% for item in products %}
<li><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}&amp;product={{ item.pk }}">
{% if item.image_url %}<img src="{{ item.image_url }}" alt="" loading="lazy">{% endif %}<span><strong>{{ item.product_name }}</strong>{% if item.brand %}<small>{{ item.brand }}</small>{% endif %}<small>{% if item.energy_kcal_100 is not None %}{{ item.energy_kcal_100|floatformat:0 }} kcal / 100 {{ item.base_unit }}{% else %}— kcal / 100 {{ item.base_unit }}{% endif %}</small></span>
</a>{% include 'food/partials/favourite_button.html' with product=item is_favourite=item.is_favourite is_list=True %}</li>
{% empty %}<li class="food-list-empty">No foods in this list yet.</li>{% endfor %}</ul>
+74
View File
@@ -0,0 +1,74 @@
import csv
from datetime import date, time
from decimal import Decimal
from io import StringIO
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import FoodLogEntry, FoodProduct, MealType, Unit
from .services.diary import diary_context
from planner.models import UserSettings
class FoodExportTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='csv-user', password='test-password')
self.other = get_user_model().objects.create_user(username='other-csv-user', password='test-password')
self.client.force_login(self.user)
self.product = FoodProduct.objects.create(owner=self.user, product_name='Changed later')
def entry(self, user, day, name, **values):
return FoodLogEntry.objects.create(user=user, date=day, time=time(8, 42), meal=MealType.BREAKFAST,
product_name_snapshot=name, brand_snapshot='Lidl', barcode_snapshot='1234567890123',
portion_label_snapshot='My bowl', amount=Decimal('300'), unit=Unit.GRAM,
calories_kcal=Decimal('174'), carbohydrates_g=Decimal('12'), protein_g=Decimal('18'),
fat_g=Decimal('6'), source=FoodProduct.Source.MANUAL, **values)
def rows(self, period):
response = self.client.get(reverse('food:export', args=[period]))
self.assertEqual(response.status_code, 200)
self.assertTrue(response.streaming)
body = b''.join(response.streaming_content).decode('utf-8')
return response, list(csv.DictReader(StringIO(body)))
@patch('food.views.localdate_for_user', return_value=date(2026, 10, 3))
def test_week_is_monday_sunday_user_scoped_and_snapshot_based(self, today):
self.entry(self.user, date(2026, 9, 28), 'Monday food')
self.entry(self.user, date(2026, 10, 3), '=Snapshot food')
self.entry(self.user, date(2026, 10, 4), 'Sunday food')
self.entry(self.user, date(2026, 9, 27), 'Outside week')
self.entry(self.other, date(2026, 10, 3), 'Private food')
response, rows = self.rows('week')
self.assertIn('food-2026-W40.csv', response['Content-Disposition'])
self.assertEqual([row['date'] for row in rows], ['2026-09-28', '2026-10-03', '2026-10-04'])
self.assertEqual(rows[1]['product_name'], "'=Snapshot food")
self.assertEqual(rows[1]['portion_label'], 'My bowl')
self.assertEqual(rows[1]['calories_kcal'], '174')
self.assertEqual(rows[1]['fibre_g'], '')
self.assertEqual(rows[1]['time'], '08:42:00')
@patch('food.views.localdate_for_user', return_value=date(2026, 10, 3))
def test_month_includes_only_calendar_month(self, today):
self.entry(self.user, date(2026, 9, 30), 'September')
self.entry(self.user, date(2026, 10, 1), 'October first')
self.entry(self.user, date(2026, 10, 31), 'October last')
response, rows = self.rows('month')
self.assertIn('food-2026-10.csv', response['Content-Disposition'])
self.assertEqual([row['product_name'] for row in rows], ['October first', 'October last'])
def test_export_requires_login_and_rejects_other_periods(self):
self.assertEqual(self.client.get(reverse('food:export', args=['year'])).status_code, 404)
self.client.logout()
self.assertEqual(self.client.get(reverse('food:export', args=['week'])).status_code, 302)
def test_diary_uses_bounded_queries_for_multiple_rows(self):
UserSettings.objects.create(user=self.user)
for index in range(8):
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH,
product=self.product, product_name_snapshot=f'Food {index}', amount=100, unit=Unit.GRAM)
with self.assertNumQueries(2):
context = diary_context(self.user, date(2026, 10, 3))
self.assertEqual(len(context['meals'][1]['entries']), 8)
+120
View File
@@ -0,0 +1,120 @@
from datetime import date
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit
class RepeatLoggingTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='repeat-one', password='test-password')
self.other = get_user_model().objects.create_user(username='repeat-two', password='test-password')
self.client.force_login(self.user)
self.product = FoodProduct.objects.create(owner=self.user, product_name='Greek yoghurt',
base_unit=Unit.GRAM, energy_kcal_100=Decimal('58'), protein_100=Decimal('6'))
def test_favourite_toggle_is_user_specific_and_htmx_updates(self):
url = reverse('food:toggle-favourite', args=[self.product.pk])
payload = {'date': '2026-10-03', 'meal': 'breakfast', 'tab': 'favourites', 'is_list': '1'}
response = self.client.post(url, payload, HTTP_HX_REQUEST='true')
self.assertContains(response, 'aria-pressed="true"')
self.assertTrue(FoodFavourite.objects.filter(user=self.user, product=self.product).exists())
self.assertFalse(FoodFavourite.objects.filter(user=self.other, product=self.product).exists())
response = self.client.post(url, payload, HTTP_HX_REQUEST='true')
self.assertEqual(response.content, b'')
self.client.force_login(self.other)
self.assertEqual(self.client.post(url, payload).status_code, 404)
def test_recent_products_are_unique_and_ordered_by_last_use(self):
other_product = FoodProduct.objects.create(owner=self.user, product_name='Soup')
for product in (self.product, other_product, self.product):
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH,
product=product, product_name_snapshot=product.product_name, amount=100, unit=Unit.GRAM)
response = self.client.get(reverse('food:add'), {'tab': 'recent'})
self.assertEqual(response.status_code, 200)
html = response.content.decode()
self.assertEqual(html.count('<strong>Greek yoghurt</strong>'), 1)
self.assertLess(html.index('<strong>Greek yoghurt</strong>'), html.index('<strong>Soup</strong>'))
def test_custom_portion_calculation_and_snapshot(self):
portion = FoodPortion.objects.create(user=self.user, product=self.product,
label='My bowl', amount=Decimal('300'), unit=Unit.GRAM, is_default=True)
response = self.client.get(reverse('food:add'), {'product': self.product.pk, 'meal': 'breakfast'})
self.assertContains(response, 'My bowl')
self.assertContains(response, 'value="portion:%s"' % portion.pk)
response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk,
'meal': 'breakfast', 'amount': '100', 'unit': 'g', 'portion': f'portion:{portion.pk}'})
self.assertEqual(response.status_code, 302)
entry = FoodLogEntry.objects.get(user=self.user)
self.assertEqual(entry.amount, Decimal('300'))
self.assertEqual(entry.calories_kcal, Decimal('174'))
self.assertEqual(entry.protein_g, Decimal('18'))
self.assertEqual(entry.portion_label_snapshot, 'My bowl')
portion.label = 'Renamed bowl'
portion.save()
entry.refresh_from_db()
self.assertEqual(entry.portion_label_snapshot, 'My bowl')
def test_save_new_default_portion(self):
old = FoodPortion.objects.create(user=self.user, product=self.product,
label='Old bowl', amount=Decimal('200'), unit=Unit.GRAM, is_default=True)
response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk,
'meal': 'breakfast', 'amount': '250', 'unit': 'g', 'portion': 'custom',
'save_portion': 'on', 'new_portion_label': 'New bowl', 'make_default': 'on'})
self.assertEqual(response.status_code, 302)
old.refresh_from_db()
self.assertFalse(old.is_default)
new = FoodPortion.objects.get(user=self.user, product=self.product, label='New bowl')
self.assertTrue(new.is_default)
self.assertEqual(new.amount, Decimal('250'))
self.assertEqual(FoodLogEntry.objects.get(user=self.user).portion_label_snapshot, 'New bowl')
def test_manual_food_basis_and_optional_nutrients(self):
response = self.client.post(reverse('food:manual'), {'date': '2026-10-03', 'meal': 'dinner',
'product_name': 'Homemade soup', 'brand': '', 'barcode': '', 'basis_amount': '250',
'base_unit': 'ml', 'energy_kcal_100': '150', 'carbohydrates_100': '20',
'protein_100': '5', 'fat_100': '2'})
self.assertEqual(response.status_code, 302)
product = FoodProduct.objects.get(owner=self.user, product_name='Homemade soup')
self.assertEqual(product.source, FoodProduct.Source.MANUAL)
self.assertEqual(product.energy_kcal_100, Decimal('60'))
self.assertEqual(product.carbohydrates_100, Decimal('8'))
self.assertIsNone(product.fibre_100)
response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': product.pk,
'meal': 'dinner', 'amount': '250', 'unit': 'ml', 'portion': 'custom'})
self.assertEqual(response.status_code, 302)
entry = FoodLogEntry.objects.get(user=self.user)
self.assertEqual(entry.calories_kcal, Decimal('150'))
self.assertIsNone(entry.fibre_g)
def test_cannot_use_another_users_portion(self):
other_product = FoodProduct.objects.create(owner=self.other, product_name='Private')
other_portion = FoodPortion.objects.create(user=self.other, product=other_product,
label='Private bowl', amount=300, unit=Unit.GRAM)
response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk,
'meal': 'breakfast', 'amount': '100', 'unit': 'g', 'portion': f'portion:{other_portion.pk}'})
self.assertEqual(response.status_code, 200)
self.assertFalse(FoodLogEntry.objects.filter(user=self.user).exists())
def test_local_search_ranks_exact_and_favourites_first(self):
favourite = FoodProduct.objects.create(owner=self.user, product_name='Greek yoghurt vanilla')
ordinary = FoodProduct.objects.create(owner=self.user, product_name='Vanilla Greek yoghurt')
FoodFavourite.objects.create(user=self.user, product=favourite)
response = self.client.get(reverse('food:add'), {'q': 'Greek yoghurt'})
html = response.content.decode()
self.assertLess(html.index('<strong>Greek yoghurt</strong>'),
html.index('<strong>Greek yoghurt vanilla</strong>'))
self.assertLess(html.index('<strong>Greek yoghurt vanilla</strong>'),
html.index('<strong>Vanilla Greek yoghurt</strong>'))
def test_invalid_custom_portion_stays_on_form_with_htmx(self):
response = self.client.post(reverse('food:add'), {'date': '2026-10-03', 'product': self.product.pk,
'meal': 'breakfast', 'amount': '250', 'unit': 'g', 'portion': 'custom',
'save_portion': 'on'}, HTTP_HX_REQUEST='true')
self.assertContains(response, 'Enter a label for the saved portion')
self.assertContains(response, 'id="food-workspace"')
self.assertNotContains(response, '<!doctype html>')
self.assertNotIn('HX-Push-Url', response)
+2
View File
@@ -14,4 +14,6 @@ urlpatterns = [
path('manual/', views.manual_food, name='manual'),
path('log/<int:pk>/', views.edit_entry, name='edit'),
path('log/<int:pk>/delete/', views.delete_entry, name='delete'),
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
path('export/<str:period>/', views.export_csv, name='export'),
]
+180 -18
View File
@@ -1,25 +1,84 @@
from decimal import Decimal
import calendar
import csv
from datetime import date, timedelta
import logging
import re
from urllib.parse import urlencode
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest
from django.http import Http404, HttpResponse, HttpResponseBadRequest, StreamingHttpResponse
from django.contrib import messages
from django.db.models import Q
from django.db.models import Max
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST
from .forms import FoodLogForm, ManualFoodForm
from .models import FoodLogEntry, FoodProduct, MealType
from .models import FoodFavourite, FoodLogEntry, FoodPortion, FoodProduct, MealType
from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from planner.timezones import localdate_for_user
logger = logging.getLogger(__name__)
EXPORT_FIELDS = (
'date', 'time', 'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot',
'portion_label_snapshot', 'amount', 'unit', 'calories_kcal', 'carbohydrates_g',
'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g', 'source',
)
EXPORT_HEADERS = (
'date', 'time', 'meal', 'product_name', 'brand', 'barcode', 'portion_label',
'amount', 'unit', 'calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g',
'fibre_g', 'sugars_g', 'salt_g', 'source',
)
class _CsvSink:
def write(self, value):
return value
def _csv_value(value):
if value is None:
return ''
if isinstance(value, Decimal):
return format(value.normalize(), 'f')
if isinstance(value, str) and value.lstrip().startswith(('=', '+', '-', '@')):
return "'" + value
return str(value)
@login_required
def export_csv(request, period):
today = localdate_for_user(request.user)
if period == 'week':
first = today - timedelta(days=today.weekday())
last = first + timedelta(days=6)
iso_year, iso_week, _ = today.isocalendar()
filename = f'food-{iso_year}-W{iso_week:02d}.csv'
elif period == 'month':
first = today.replace(day=1)
last = today.replace(day=calendar.monthrange(today.year, today.month)[1])
filename = f'food-{today:%Y-%m}.csv'
else:
raise Http404('Unknown export period.')
rows = (FoodLogEntry.objects.filter(user=request.user, date__range=(first, last))
.order_by('date', 'time', 'pk').values_list(*EXPORT_FIELDS).iterator(chunk_size=500))
writer = csv.writer(_CsvSink())
def output():
yield writer.writerow(EXPORT_HEADERS)
for row in rows:
yield writer.writerow([_csv_value(value) for value in row])
response = StreamingHttpResponse(output(), content_type='text/csv; charset=utf-8')
response['Content-Disposition'] = f'attachment; filename="{filename}"'
return response
def _day(request):
try:
@@ -28,6 +87,34 @@ def _day(request):
return None, HttpResponseBadRequest(str(error))
def _portion_options(form, product):
if not product:
return []
options = []
for value, label in form.fields['portion'].choices:
amount = ''
if value == 'base':
amount = '100'
elif value == 'serving':
amount = str(product.serving_amount)
elif value.startswith('portion:'):
amount = str(form.portions[value.partition(':')[2]].amount)
options.append({'value': value, 'label': label, 'amount': amount})
return options
def _save_custom_portion(form, user, product, entry):
if form.cleaned_data.get('portion') != 'custom' or not form.cleaned_data.get('save_portion'):
return
if form.cleaned_data.get('make_default'):
FoodPortion.objects.filter(user=user, product=product, is_default=True).update(is_default=False)
portion = FoodPortion(user=user, product=product,
label=form.cleaned_data['new_portion_label'].strip(), amount=entry.amount,
unit=entry.unit, is_default=form.cleaned_data.get('make_default', False))
portion.full_clean()
portion.save()
def _save_entry(form, user, day, product):
entry = form.save(commit=False)
entry.user = user
@@ -47,12 +134,15 @@ def _save_entry(form, user, day, product):
setattr(entry, target, (value * factor).quantize(Decimal('0.001')) if value is not None else None)
entry.full_clean()
entry.save()
_save_custom_portion(form, user, product, entry)
return entry
def _diary_response(request, day):
if request.headers.get('HX-Request') == 'true':
return render(request, 'food/partials/diary_content.html', diary_context(request.user, day))
response = render(request, 'food/partials/diary_content.html', diary_context(request.user, day))
response['HX-Push-Url'] = f"{reverse('food:diary')}?date={day.isoformat()}"
return response
return redirect(f"{reverse('food:diary')}?date={day.isoformat()}")
@@ -76,27 +166,94 @@ def add_food(request):
product_id = request.GET.get('product') or request.POST.get('product')
product = get_object_or_404(FoodProduct, pk=product_id, owner=request.user) if product_id else None
query = request.GET.get('q', '').strip()[:100]
tab = request.GET.get('tab', 'recent')
if tab not in ('recent', 'favourites', 'mine'):
tab = 'recent'
tab = request.GET.get('tab', 'overview')
if tab not in ('overview', 'recent', 'favourites', 'mine'):
tab = 'overview'
products = FoodProduct.objects.filter(owner=request.user)
favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True))
recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False)
.values('product_id').annotate(last_used=Max('created_at'))
.order_by('-last_used').values_list('product_id', flat=True)[:30])
recent_rank = {product_id: index for index, product_id in enumerate(recent_ids)}
if query:
products = products.filter(Q(product_name__icontains=query) | Q(brand__icontains=query) | Q(barcode__icontains=query))
if tab == 'favourites':
products = products.filter(favourites__user=request.user).order_by('product_name')
normalized = ' '.join(query.split()).casefold()
for token in normalized.split():
products = products.filter(Q(product_name__icontains=token) | Q(brand__icontains=token) | Q(barcode__icontains=token))
def rank(item):
name = ' '.join(item.product_name.split()).casefold()
return (0 if item.barcode == normalized else 1 if name == normalized else
2 if item.pk in favourite_ids and name.startswith(normalized) else
3 if item.pk in favourite_ids else 4 if item.pk in recent_rank else 5,
recent_rank.get(item.pk, 999), name)
products = sorted(products[:500], key=rank)[:40]
tab = 'mine'
elif tab == 'favourites':
products = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:30])
elif tab == 'mine':
products = products.order_by('product_name')
products = list(products.order_by('product_name')[:40])
elif tab == 'recent':
by_id = products.in_bulk(recent_ids)
products = [by_id[pk] for pk in recent_ids if pk in by_id]
else:
products = products.filter(log_entries__user=request.user).annotate(last_used=Max('log_entries__created_at')).order_by('-last_used')
by_id = products.in_bulk(recent_ids)
favourites = list(products.filter(pk__in=favourite_ids).order_by('product_name')[:20])
recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20]
products = favourites + recents
for item in products:
item.is_favourite = item.pk in favourite_ids
if product:
product.is_favourite = product.pk in favourite_ids
form = FoodLogForm(request.POST or None, product=product, initial={'meal': meal, 'unit': product.base_unit if product else 'g'}) if product else None
if request.method == 'POST':
if not product:
return HttpResponseBadRequest('Choose a product.')
if form.is_valid():
_save_entry(form, request.user, day, product)
with transaction.atomic():
_save_entry(form, request.user, day, product)
return _diary_response(request, day)
return render(request, 'food/add.html', {'day': day, 'meal': meal, 'products': products[:40],
'product': product, 'form': form, 'query': query, 'tab': tab})
portion_options = _portion_options(form, product) if form else []
template = 'food/partials/add_content.html' if request.method == 'POST' and request.headers.get('HX-Request') == 'true' else 'food/add.html'
return render(request, template, {'day': day, 'meal': meal, 'products': products[:40],
'product': product, 'form': form, 'query': query, 'tab': tab,
'favourite_ids': favourite_ids, 'favourites': favourites if not query and tab == 'overview' else [],
'recents': recents if not query and tab == 'overview' else [],
'is_favourite': product.pk in favourite_ids if product else False, 'portion_options': portion_options})
@login_required
@require_POST
def toggle_favourite(request, pk):
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
favourite, created = FoodFavourite.objects.get_or_create(user=request.user, product=product)
if not created:
favourite.delete()
day, error = _day(request)
if error:
return error
meal = request.POST.get('meal') or MealType.BREAKFAST
if meal not in MealType.values:
return HttpResponseBadRequest('Invalid meal.')
if request.headers.get('HX-Request') == 'true':
if request.POST.get('tab') == 'overview' and request.POST.get('is_list') == '1':
favourite_ids = set(FoodFavourite.objects.filter(user=request.user).values_list('product_id', flat=True))
recent_ids = list(FoodLogEntry.objects.filter(user=request.user, product__isnull=False)
.values('product_id').annotate(last_used=Max('created_at'))
.order_by('-last_used').values_list('product_id', flat=True)[:30])
favourites = list(FoodProduct.objects.filter(owner=request.user, pk__in=favourite_ids).order_by('product_name')[:20])
by_id = FoodProduct.objects.filter(owner=request.user).in_bulk(recent_ids)
recents = [by_id[pk] for pk in recent_ids if pk in by_id and pk not in favourite_ids][:20]
for item in favourites + recents:
item.is_favourite = item.pk in favourite_ids
return render(request, 'food/partials/favourite_update.html', {
'product': product, 'is_favourite': created, 'day': day, 'meal': meal,
'tab': 'overview', 'is_list': True, 'favourites': favourites, 'recents': recents,
})
if request.POST.get('tab') == 'favourites' and request.POST.get('is_list') == '1' and not created:
return HttpResponse('')
return render(request, 'food/partials/favourite_button.html', {'product': product,
'is_favourite': created, 'day': day, 'meal': meal,
'tab': request.POST.get('tab'), 'is_list': request.POST.get('is_list') == '1'})
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
@login_required
@@ -180,7 +337,7 @@ def manual_food(request):
barcode = request.GET.get('barcode', '').strip()
if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode):
return HttpResponseBadRequest('Invalid barcode.')
form = ManualFoodForm(request.POST or None, initial={'barcode': barcode})
form = ManualFoodForm(request.POST or None, user=request.user, initial={'barcode': barcode})
if request.method == 'POST' and form.is_valid():
product = form.save(commit=False)
product.owner = request.user
@@ -203,10 +360,15 @@ def edit_entry(request, pk):
factor = updated.amount / original_amount
for field, original in original_nutrients.items():
setattr(updated, field, (original * factor).quantize(Decimal('0.001')) if original is not None else None)
updated.full_clean()
updated.save()
with transaction.atomic():
updated.full_clean()
updated.save()
if product:
_save_custom_portion(form, request.user, product, updated)
return _diary_response(request, entry.date)
return render(request, 'food/edit.html', {'entry': entry, 'form': form})
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)})
@login_required