latest changes
This commit is contained in:
@@ -19,6 +19,7 @@ from django.utils.dateparse import parse_date, parse_time
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
|
||||
from planner.models import UserSettings, WaterIntakeEntry
|
||||
from planner.demo_policy import is_demo_user
|
||||
from planner.timezones import localdate_for_user, timezone_for_user
|
||||
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
|
||||
InventoryCategory, InventoryLocation, KitchenInventoryItem,
|
||||
@@ -52,6 +53,8 @@ def token_value():
|
||||
|
||||
|
||||
def create_token(user, name, scopes, expires_at=None):
|
||||
if is_demo_user(user):
|
||||
raise ValueError('API tokens are unavailable for demo accounts.')
|
||||
prefix, value = token_value()
|
||||
token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix,
|
||||
token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at)
|
||||
@@ -74,6 +77,8 @@ def _authenticate(request):
|
||||
return None, error('revoked_token', 'API token has been revoked.', 401)
|
||||
if token.expires_at and token.expires_at <= timezone.now():
|
||||
return None, error('expired_token', 'API token has expired.', 401)
|
||||
if is_demo_user(token.user):
|
||||
return None, error('demo_token_forbidden', 'Demo account tokens are disabled.', 403)
|
||||
PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
|
||||
return token, None
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ from . import api, api_schema
|
||||
from recipes import api as recipe_api
|
||||
from stress import api as stress_api
|
||||
from dreams import api as dream_api
|
||||
from groceries import api as grocery_api
|
||||
|
||||
urlpatterns = [
|
||||
path('auth/whoami/', api.whoami),
|
||||
@@ -34,6 +35,9 @@ urlpatterns = [
|
||||
path('hydration/manual/', api.hydration_log),
|
||||
path('hydration/manual/<uuid:identifier>/', api.hydration_manual_entry),
|
||||
path('hydration/settings/', api.hydration_settings),
|
||||
path('groceries/', grocery_api.collection),
|
||||
path('groceries/<uuid:identifier>/', grocery_api.item),
|
||||
path('groceries/recipe/<uuid:identifier>/', grocery_api.recipe_import),
|
||||
path('recipes/', recipe_api.recipe_search),
|
||||
path('recipes/cook-later/', recipe_api.recipe_cook_later_collection),
|
||||
path('recipes/cook-later/<uuid:identifier>/', recipe_api.recipe_cook_later_item),
|
||||
|
||||
+28
-25
@@ -7,15 +7,16 @@ from .models import FoodLogEntry, FoodPortion, FoodProduct, KitchenInventoryItem
|
||||
|
||||
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')
|
||||
initial=100, required=False, 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')
|
||||
fields = ('product_name', 'brand', 'barcode', 'base_unit', 'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
labels = {
|
||||
'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',
|
||||
'saturated_fat_100': 'Saturated fat for base quantity (optional)',
|
||||
'fibre_100': 'Fibre for base quantity (optional)',
|
||||
'sugars_100': 'Sugars for base quantity (optional)',
|
||||
'salt_100': 'Salt for base quantity (optional)',
|
||||
@@ -25,14 +26,21 @@ class ManualFoodForm(forms.ModelForm):
|
||||
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
|
||||
self.fields['base_unit'].required = False
|
||||
if self.instance.pk:
|
||||
self.fields['base_unit'].disabled = True
|
||||
|
||||
def clean_base_unit(self):
|
||||
return self.cleaned_data['base_unit'] or self.instance.base_unit or 'g'
|
||||
|
||||
def clean_basis_amount(self):
|
||||
return self.cleaned_data['basis_amount'] or Decimal('100')
|
||||
|
||||
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():
|
||||
if barcode and self.user and FoodProduct.objects.filter(owner=self.user, barcode=barcode).exclude(pk=self.instance.pk).exists():
|
||||
raise forms.ValidationError('This barcode is already saved in your foods.')
|
||||
return barcode
|
||||
|
||||
@@ -42,7 +50,7 @@ class ManualFoodForm(forms.ModelForm):
|
||||
if basis:
|
||||
factor = Decimal('100') / basis
|
||||
for name in ('energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
|
||||
'fibre_100', 'sugars_100', 'salt_100'):
|
||||
'saturated_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.')
|
||||
@@ -52,7 +60,7 @@ class ManualFoodForm(forms.ModelForm):
|
||||
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'):
|
||||
'saturated_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:
|
||||
@@ -162,9 +170,15 @@ class FoodLogForm(forms.ModelForm):
|
||||
|
||||
|
||||
class FoodLogEditForm(FoodLogForm):
|
||||
edit_nutrition = forms.BooleanField(required=False, label='Use these nutrition values for this entry')
|
||||
|
||||
class Meta(FoodLogForm.Meta):
|
||||
fields = FoodLogForm.Meta.fields + ('quantity',)
|
||||
labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)'}
|
||||
fields = FoodLogForm.Meta.fields + ('quantity', 'calories_kcal', 'carbohydrates_g',
|
||||
'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
|
||||
labels = {**FoodLogForm.Meta.labels, 'quantity': 'Quantity (portions)',
|
||||
'calories_kcal': 'Calories (kcal)', 'carbohydrates_g': 'Carbohydrates (g)',
|
||||
'protein_g': 'Protein (g)', 'fat_g': 'Fat (g)', 'fibre_g': 'Fibre (g)',
|
||||
'sugars_g': 'Sugars (g)', 'salt_g': 'Salt (g)'}
|
||||
widgets = {**FoodLogForm.Meta.widgets,
|
||||
'quantity': forms.NumberInput(attrs={'min': '0.01', 'step': '0.01'})}
|
||||
|
||||
@@ -234,19 +248,8 @@ class InventoryItemForm(forms.ModelForm):
|
||||
return ' '.join(self.cleaned_data['category_name'].split())
|
||||
|
||||
|
||||
class InventoryManualProductForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = FoodProduct
|
||||
fields = ('product_name', 'brand', 'barcode', 'package_quantity')
|
||||
|
||||
def __init__(self, *args, user=None, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.user = user
|
||||
|
||||
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 products.')
|
||||
return barcode
|
||||
class InventoryManualProductForm(ManualFoodForm):
|
||||
class Meta(ManualFoodForm.Meta):
|
||||
fields = ('product_name', 'brand', 'barcode', 'package_quantity', 'base_unit',
|
||||
'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
|
||||
'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100')
|
||||
|
||||
@@ -147,6 +147,7 @@ def cached_product(user, barcode, *, refresh=False):
|
||||
raise ValueError('Enter a numeric barcode.')
|
||||
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
|
||||
if product and (product.source == FoodProduct.Source.MANUAL or
|
||||
(isinstance(product.raw_data, dict) and product.raw_data.get('manual_nutrition_override')) or
|
||||
(not refresh and product.fetched_at and product.fetched_at >= timezone.now() - timedelta(days=7))):
|
||||
return product
|
||||
if not settings.OPENFOODFACTS_ENABLED:
|
||||
|
||||
@@ -105,3 +105,6 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
|
||||
.food-ring-laps{font-size:.7rem}
|
||||
.food-macro--pink{--accent:#d45b8b}
|
||||
.food-macro .food-ring{--accent:inherit}
|
||||
|
||||
/* Shared product and entry nutrition forms. */
|
||||
.product-form{display:grid;gap:1rem}.product-form .form-field,.entry-nutrition-fields .form-field{display:grid;gap:.3rem}.nutrition-fields{min-width:0;margin:0;padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.nutrition-fields legend{padding:0 .35rem;font-weight:700}.nutrition-fields p,.entry-nutrition-fields p{margin:.2rem 0 1rem;line-height:1.45;color:var(--food-muted)}.nutrition-fields>details,.entry-nutrition-fields{margin-top:1rem}.nutrition-fields summary,.entry-nutrition-fields summary{cursor:pointer;font-weight:700;min-height:44px;align-content:center}.nutrition-field-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.85rem}.nutrition-field-grid input{width:100%;min-width:0}.nutrition-fields .form-field{margin-bottom:.8rem}.entry-nutrition-fields{padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]){display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]) small{flex-basis:100%}@media(max-width:520px){.nutrition-field-grid{grid-template-columns:1fr}}
|
||||
|
||||
@@ -1,6 +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' %}">
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition">
|
||||
{% include 'food/partials/edit_content.html' %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261012-actions">
|
||||
<div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Add to inventory</h1>
|
||||
{% if product %}
|
||||
<section class="food-card inventory-product">{% if product.image_url %}<img src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}{% if product.package_quantity %}<p>{{ product.package_quantity }}</p>{% endif %}{% if off_categories %}<p><small>Open Food Facts: {{ off_categories }}</small></p>{% endif %}</div></section>
|
||||
<section class="food-card inventory-product">{% if product.image_url %}<img src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}{% if product.package_quantity %}<p>{{ product.package_quantity }}</p>{% endif %}{% if off_categories %}<p><small>Open Food Facts: {{ off_categories }}</small></p>{% endif %}<p><a href="{% url 'food:product-edit' product.pk %}">View or edit product nutrition</a></p></div></section>
|
||||
{% if existing %}<section class="food-card"><h2>Already in inventory</h2>{% for item in existing %}<div class="inventory-existing"><span>{{ item.location.name }} · Quantity {{ item.quantity }}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</span><form method="post" action="{% url 'food:inventory-add-one' item.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">+1 existing item</button></form></div>{% endfor %}<p>Use the form below to add this product separately.</p></section>{% endif %}
|
||||
<form class="food-card inventory-form" method="post">{% csrf_token %}<input type="hidden" name="product" value="{{ product.pk }}">{{ form.non_field_errors }}
|
||||
{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Edit inventory item · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><p>This form changes stock for this package. <a href="{% url 'food:product-edit' item.product.pk %}">View or edit product nutrition</a> for future food logs.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Create inventory product · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page"><a href="{% url 'food:inventory-add' %}">← Add item</a><h1>Create product</h1><p>Save a product to the shared food catalogue. Nutrition can be added later.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{% for field in form %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endfor %}<button class="button" type="submit">Continue to inventory</button></form></div>{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:inventory-add' %}">← Add item</a><h1>Create product</h1><p>Save a product for both Kitchen Inventory and Food Diary. Package size describes stock; nutrition is entered separately for the chosen basis.</p><form method="post" class="food-card product-form">{% csrf_token %}{{ form.non_field_errors }}
|
||||
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' or field.name == 'package_quantity' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
|
||||
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Continue to inventory</button></form></div>{% endblock %}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
</form>
|
||||
{% for card in cards %}<article class="food-card inventory-product-card">
|
||||
<div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining</strong> · {{ card.packages|length }} package{{ card.packages|length|pluralize }}</p></div></div>
|
||||
<p><a href="{% url 'food:product-edit' card.product.pk %}">View or edit product nutrition</a></p>
|
||||
<details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Pack {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details>
|
||||
<details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{{ unit }}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Pack {{ forloop.counter }} · {% if item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details>
|
||||
</article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
{% 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' }}&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 %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:add' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">← Back to foods</a><h1>Create a food</h1><p>Save nutrition once, then choose how much to log. You can correct this product later; existing diary entries keep their recorded values.</p><form method="post" class="food-card product-form">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}">{{ form.non_field_errors }}
|
||||
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
|
||||
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Save food</button></form></div>{% endblock %}
|
||||
|
||||
@@ -12,11 +12,13 @@
|
||||
<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>Saturated fat</dt><dd>{{ product.saturated_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 %}
|
||||
<p><a href="{% url 'food:product-edit' product.pk %}">Edit product nutrition</a></p>
|
||||
</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 }}"><input type="hidden" name="submission_id" value="{{ submission_id }}">
|
||||
@@ -50,11 +52,11 @@
|
||||
<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' }}&meal={{ meal }}">Create a food manually</a>
|
||||
<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Scan barcode</a>
|
||||
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}&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>
|
||||
{% if not is_demo_account %}<a class="button" href="{% url 'food:scanner' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}">Scan barcode</a>
|
||||
<a class="button button--secondary" href="{% url 'food:external-search' %}?date={{ day|date:'Y-m-d' }}&meal={{ meal }}&q={{ query|urlencode }}">Search Open Food Facts</a>{% endif %}</div>
|
||||
{% if not is_demo_account %}<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>{% endif %}
|
||||
{% if not is_demo_account %}<p class="food-attribution">External product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>{% endif %}
|
||||
{% 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' }}&meal={{ meal }}">Barcode</a></nav>{% endif %}
|
||||
{% if not product and not is_demo_account %}<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' }}&meal={{ meal }}">Barcode</a></nav>{% endif %}
|
||||
|
||||
@@ -9,6 +9,21 @@
|
||||
<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>
|
||||
<details class="entry-nutrition-fields" {% if form.edit_nutrition.value or form.calories_kcal.errors or form.carbohydrates_g.errors or form.protein_g.errors or form.fat_g.errors or form.fibre_g.errors or form.sugars_g.errors or form.salt_g.errors %}open{% endif %}>
|
||||
<summary>Correct nutrition for this entry</summary>
|
||||
<p>Values are for one logged portion ({{ entry.amount|floatformat:-3 }} {{ entry.unit }}), before the quantity multiplier. Leave a value blank if unknown. This does not change the saved product.</p>
|
||||
<div class="form-field">{{ form.edit_nutrition.label_tag }}{{ form.edit_nutrition }}{{ form.edit_nutrition.errors }}<small>Without this selection, nutrition scales automatically when the portion amount changes.</small></div>
|
||||
<div class="nutrition-field-grid">
|
||||
<div class="form-field">{{ form.calories_kcal.label_tag }}{{ form.calories_kcal }}{{ form.calories_kcal.errors }}</div>
|
||||
<div class="form-field">{{ form.carbohydrates_g.label_tag }}{{ form.carbohydrates_g }}{{ form.carbohydrates_g.errors }}</div>
|
||||
<div class="form-field">{{ form.protein_g.label_tag }}{{ form.protein_g }}{{ form.protein_g.errors }}</div>
|
||||
<div class="form-field">{{ form.fat_g.label_tag }}{{ form.fat_g }}{{ form.fat_g.errors }}</div>
|
||||
<div class="form-field">{{ form.fibre_g.label_tag }}{{ form.fibre_g }}{{ form.fibre_g.errors }}</div>
|
||||
<div class="form-field">{{ form.sugars_g.label_tag }}{{ form.sugars_g }}{{ form.sugars_g.errors }}</div>
|
||||
<div class="form-field">{{ form.salt_g.label_tag }}{{ form.salt_g }}{{ form.salt_g.errors }}</div>
|
||||
</div>
|
||||
</details>
|
||||
{% if product %}<p><a href="{% url 'food:product-edit' product.pk %}">Edit saved product nutrition for future logs</a></p>{% endif %}
|
||||
<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>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<div class="food-actions inventory-product-actions">
|
||||
<a class="button" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a>
|
||||
<a class="button button--secondary" href="{% url 'food:inventory-external' %}?q={{ query|urlencode }}">Search Open Food Facts</a>
|
||||
{% if not is_demo_account %}<a class="button" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a>
|
||||
<a class="button button--secondary" href="{% url 'food:inventory-external' %}?q={{ query|urlencode }}">Search Open Food Facts</a>{% endif %}
|
||||
<a class="button button--secondary" href="{% url 'food:inventory-manual' %}">Create manual product</a>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<fieldset class="nutrition-fields">
|
||||
<legend>Nutrition</legend>
|
||||
<p>Enter values for the basis amount and unit below. Leave a value blank when it is unknown; zero means the label says zero.</p>
|
||||
<div class="form-field">{{ form.basis_amount.label_tag }}{{ form.basis_amount }}{{ form.basis_amount.errors }}</div>
|
||||
<div class="form-field">{{ form.base_unit.label_tag }}{{ form.base_unit }}{{ form.base_unit.errors }}{% if form.base_unit.field.disabled %}<small>The nutrition unit is fixed for an existing product.</small>{% endif %}</div>
|
||||
<div class="nutrition-field-grid">
|
||||
<div class="form-field">{{ form.energy_kcal_100.label_tag }}{{ form.energy_kcal_100 }}{{ form.energy_kcal_100.errors }}</div>
|
||||
<div class="form-field">{{ form.carbohydrates_100.label_tag }}{{ form.carbohydrates_100 }}{{ form.carbohydrates_100.errors }}</div>
|
||||
<div class="form-field">{{ form.protein_100.label_tag }}{{ form.protein_100 }}{{ form.protein_100.errors }}</div>
|
||||
<div class="form-field">{{ form.fat_100.label_tag }}{{ form.fat_100 }}{{ form.fat_100.errors }}</div>
|
||||
</div>
|
||||
<details {% if form.saturated_fat_100.errors or form.fibre_100.errors or form.sugars_100.errors or form.salt_100.errors %}open{% endif %}>
|
||||
<summary>More nutrients</summary>
|
||||
<div class="nutrition-field-grid">
|
||||
<div class="form-field">{{ form.saturated_fat_100.label_tag }}{{ form.saturated_fat_100 }}{{ form.saturated_fat_100.errors }}</div>
|
||||
<div class="form-field">{{ form.fibre_100.label_tag }}{{ form.fibre_100 }}{{ form.fibre_100.errors }}</div>
|
||||
<div class="form-field">{{ form.sugars_100.label_tag }}{{ form.sugars_100 }}{{ form.sugars_100.errors }}</div>
|
||||
<div class="form-field">{{ form.salt_100.label_tag }}{{ form.salt_100 }}{{ form.salt_100.errors }}</div>
|
||||
</div>
|
||||
</details>
|
||||
</fieldset>
|
||||
@@ -0,0 +1,5 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Edit product nutrition · Tasknest{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261021-nutrition"><div class="food-form-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ product.product_name }}</h1><p>Changes to this product affect future food logs. Existing Food Diary entries keep their recorded nutrition; edit an entry to correct its own values.</p>{% if product.source == 'openfoodfacts' %}<p>Imported from Open Food Facts{% if product.raw_data.manual_nutrition_override %}; nutrition has been corrected manually{% endif %}.</p>{% endif %}<form method="post" class="food-card product-form">{% csrf_token %}{{ form.non_field_errors }}
|
||||
{% for field in form %}{% if field.name == 'product_name' or field.name == 'brand' or field.name == 'barcode' %}<div class="form-field">{{ field.label_tag }}{{ field }}{{ field.errors }}</div>{% endif %}{% endfor %}
|
||||
{% include 'food/partials/product_nutrition_fields.html' %}<button class="button" type="submit">Save product</button></form><p><a href="{% url 'food:inventory' %}">Kitchen Inventory</a> · <a href="{% url 'food:add' %}?product={{ product.pk }}">Log this food</a></p></div>{% endblock %}
|
||||
@@ -0,0 +1,136 @@
|
||||
from decimal import Decimal
|
||||
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
|
||||
from .services.logging import apply_product_snapshot
|
||||
from .services.openfoodfacts import cached_product
|
||||
|
||||
|
||||
class NutritionUiTests(TestCase):
|
||||
def setUp(self):
|
||||
self.user = get_user_model().objects.create_user('nutrition-ui', password='test')
|
||||
self.other = get_user_model().objects.create_user('nutrition-other', password='test')
|
||||
self.client.force_login(self.user)
|
||||
|
||||
def test_inventory_product_creation_preserves_unknown_and_zero(self):
|
||||
response = self.client.post(reverse('food:inventory-manual'), {
|
||||
'product_name': 'Lentils', 'brand': '', 'barcode': '', 'package_quantity': '250 g',
|
||||
'base_unit': 'g', 'basis_amount': '250', 'energy_kcal_100': '300',
|
||||
'carbohydrates_100': '45', 'protein_100': '', 'fat_100': '',
|
||||
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '0', 'salt_100': '',
|
||||
})
|
||||
product = FoodProduct.objects.get(owner=self.user)
|
||||
self.assertRedirects(response, f"{reverse('food:inventory-add')}?product={product.pk}",
|
||||
fetch_redirect_response=False)
|
||||
self.assertEqual(product.energy_kcal_100, Decimal('120.000'))
|
||||
self.assertEqual(product.carbohydrates_100, Decimal('18.000'))
|
||||
self.assertEqual(product.sugars_100, Decimal('0.000'))
|
||||
self.assertIsNone(product.protein_100)
|
||||
self.assertIsNone(product.salt_100)
|
||||
self.assertEqual(product.package_amount, Decimal('250'))
|
||||
|
||||
def test_diary_manual_creation_allows_unknown_nutrients(self):
|
||||
response = self.client.post(reverse('food:manual'), {
|
||||
'product_name': 'Oat drink', 'brand': '', 'barcode': '',
|
||||
'base_unit': 'ml', 'basis_amount': '200', 'energy_kcal_100': '80',
|
||||
'carbohydrates_100': '', 'protein_100': '0', 'fat_100': '',
|
||||
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '', 'salt_100': '',
|
||||
'meal': 'breakfast',
|
||||
})
|
||||
product = FoodProduct.objects.get(owner=self.user, product_name='Oat drink')
|
||||
self.assertEqual(response.status_code, 302)
|
||||
self.assertEqual(product.base_unit, 'ml')
|
||||
self.assertEqual(product.energy_kcal_100, Decimal('40.000'))
|
||||
self.assertEqual(product.protein_100, Decimal('0.000'))
|
||||
self.assertIsNone(product.carbohydrates_100)
|
||||
|
||||
def test_invalid_product_keeps_entered_nutrition(self):
|
||||
response = self.client.post(reverse('food:inventory-manual'), {
|
||||
'product_name': 'Oats', 'brand': '', 'barcode': 'invalid',
|
||||
'package_quantity': '250 g', 'base_unit': 'g', 'basis_amount': '250',
|
||||
'energy_kcal_100': '300', 'protein_100': '0',
|
||||
})
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, 'Enter a numeric barcode.')
|
||||
self.assertContains(response, 'value="300"')
|
||||
self.assertFalse(FoodProduct.objects.filter(owner=self.user, product_name='Oats').exists())
|
||||
|
||||
def test_product_edit_changes_future_logs_without_rewriting_old_entries(self):
|
||||
product = FoodProduct.objects.create(owner=self.user, product_name='Oats',
|
||||
energy_kcal_100=Decimal('100'), protein_100=Decimal('10'))
|
||||
old = FoodLogEntry(user=self.user, date='2026-10-21', meal='breakfast',
|
||||
amount=Decimal('100'), unit='g')
|
||||
apply_product_snapshot(old, product)
|
||||
old.save()
|
||||
response = self.client.post(reverse('food:product-edit', args=[product.pk]), {
|
||||
'product_name': 'Oats', 'brand': '', 'barcode': '', 'base_unit': 'g',
|
||||
'basis_amount': '100', 'energy_kcal_100': '150', 'protein_100': '12',
|
||||
'carbohydrates_100': '', 'fat_100': '', 'saturated_fat_100': '',
|
||||
'fibre_100': '3', 'sugars_100': '', 'salt_100': '',
|
||||
})
|
||||
self.assertRedirects(response, reverse('food:product-edit', args=[product.pk]),
|
||||
fetch_redirect_response=False)
|
||||
product.refresh_from_db()
|
||||
old.refresh_from_db()
|
||||
self.assertEqual(product.energy_kcal_100, Decimal('150.000'))
|
||||
self.assertEqual(product.fibre_100, Decimal('3.000'))
|
||||
self.assertEqual(old.calories_kcal, Decimal('100.000'))
|
||||
self.assertEqual(old.protein_g, Decimal('10.000'))
|
||||
new = FoodLogEntry(user=self.user, date='2026-10-21', meal='lunch',
|
||||
amount=Decimal('100'), unit='g')
|
||||
apply_product_snapshot(new, product)
|
||||
self.assertEqual(new.calories_kcal, Decimal('150.000'))
|
||||
self.assertEqual(new.fibre_g, Decimal('3.000'))
|
||||
self.assertEqual(self.client.get(reverse('food:product-edit', args=[
|
||||
FoodProduct.objects.create(owner=self.other, product_name='Private').pk])).status_code, 404)
|
||||
|
||||
def test_entry_only_correction_and_later_portion_scaling(self):
|
||||
product = FoodProduct.objects.create(owner=self.user, product_name='Soup',
|
||||
energy_kcal_100=Decimal('100'), sugars_100=None)
|
||||
entry = FoodLogEntry(user=self.user, date='2026-10-21', meal='lunch',
|
||||
amount=Decimal('100'), unit='g')
|
||||
apply_product_snapshot(entry, product)
|
||||
entry.save()
|
||||
url = reverse('food:edit', args=[entry.pk])
|
||||
response = self.client.post(url, {
|
||||
'meal': 'lunch', 'portion': 'custom', 'portion_count': '1',
|
||||
'amount': '100', 'unit': 'g', 'quantity': '1', 'edit_nutrition': 'on',
|
||||
'calories_kcal': '125', 'carbohydrates_g': '', 'protein_g': '',
|
||||
'fat_g': '', 'fibre_g': '', 'sugars_g': '0', 'salt_g': '',
|
||||
})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
entry.refresh_from_db()
|
||||
product.refresh_from_db()
|
||||
self.assertEqual(entry.calories_kcal, Decimal('125.000'))
|
||||
self.assertEqual(entry.sugars_g, Decimal('0.000'))
|
||||
self.assertIsNone(entry.salt_g)
|
||||
self.assertEqual(product.energy_kcal_100, Decimal('100'))
|
||||
response = self.client.post(url, {'meal': 'lunch', 'portion': 'custom',
|
||||
'portion_count': '1', 'amount': '200', 'unit': 'g', 'quantity': '1'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
entry.refresh_from_db()
|
||||
self.assertEqual(entry.calories_kcal, Decimal('250.000'))
|
||||
self.assertEqual(entry.sugars_g, Decimal('0.000'))
|
||||
self.assertIsNone(entry.salt_g)
|
||||
|
||||
@patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product')
|
||||
def test_corrected_import_is_not_refreshed_over_manual_nutrition(self, get_product):
|
||||
product = FoodProduct.objects.create(owner=self.user, product_name='Imported soup',
|
||||
barcode='123456789', source=FoodProduct.Source.OPEN_FOOD_FACTS,
|
||||
energy_kcal_100=Decimal('100'), raw_data={'code': '123456789'})
|
||||
response = self.client.post(reverse('food:product-edit', args=[product.pk]), {
|
||||
'product_name': 'Imported soup', 'brand': '', 'barcode': '123456789',
|
||||
'base_unit': 'g', 'basis_amount': '100', 'energy_kcal_100': '120',
|
||||
'carbohydrates_100': '', 'protein_100': '', 'fat_100': '',
|
||||
'saturated_fat_100': '', 'fibre_100': '', 'sugars_100': '', 'salt_100': '',
|
||||
})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
product.refresh_from_db()
|
||||
self.assertTrue(product.raw_data['manual_nutrition_override'])
|
||||
self.assertEqual(cached_product(self.user, product.barcode, refresh=True).energy_kcal_100,
|
||||
Decimal('120.000'))
|
||||
get_product.assert_not_called()
|
||||
@@ -32,5 +32,6 @@ urlpatterns = [
|
||||
path('attachments/<uuid:identifier>/file/', views.attachment_file, name='attachment-file'),
|
||||
path('product/<int:pk>/favourite/', views.toggle_favourite, name='toggle-favourite'),
|
||||
path('product/<int:pk>/hydration/', views.product_hydration, name='product-hydration'),
|
||||
path('product/<int:pk>/edit/', views.edit_product, name='product-edit'),
|
||||
path('export/<str:period>/', views.export_csv, name='export'),
|
||||
]
|
||||
|
||||
+23
-1
@@ -421,7 +421,11 @@ def edit_entry(request, pk):
|
||||
updated = form.save(commit=False)
|
||||
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)
|
||||
if form.cleaned_data['edit_nutrition']:
|
||||
value = form.cleaned_data[field]
|
||||
else:
|
||||
value = (original * factor).quantize(Decimal('0.001')) if original is not None else None
|
||||
setattr(updated, field, value)
|
||||
with transaction.atomic():
|
||||
sync_food_hydration(updated)
|
||||
updated.full_clean()
|
||||
@@ -441,6 +445,24 @@ def edit_entry(request, pk):
|
||||
'portion_options': _portion_options(form, product)})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def edit_product(request, pk):
|
||||
product = get_object_or_404(FoodProduct, pk=pk, owner=request.user)
|
||||
form = ManualFoodForm(request.POST or None, instance=product, user=request.user)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
product = form.save(commit=False)
|
||||
nutrition_fields = {'energy_kcal_100', 'carbohydrates_100', 'protein_100',
|
||||
'fat_100', 'saturated_fat_100', 'fibre_100', 'sugars_100', 'salt_100'}
|
||||
if product.source == FoodProduct.Source.OPEN_FOOD_FACTS and nutrition_fields.intersection(form.changed_data):
|
||||
product.raw_data = {**(product.raw_data if isinstance(product.raw_data, dict) else {}),
|
||||
'manual_nutrition_override': True}
|
||||
product.save()
|
||||
messages.success(request, 'Product saved. Existing diary entries keep their recorded nutrition.')
|
||||
return redirect('food:product-edit', pk=product.pk)
|
||||
return render(request, 'food/product_edit.html', {'form': form, 'product': product})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def delete_entry(request, pk):
|
||||
|
||||
Reference in New Issue
Block a user