adding food logging, phase 3

This commit is contained in:
Joren de Graaf
2026-10-03 20:53:54 +02:00
parent fca2ef2acd
commit 03fcbcbafc
8 changed files with 413 additions and 4 deletions
+175
View File
@@ -0,0 +1,175 @@
"""Explicit Open Food Facts reads and user-owned local product caching."""
import json
import logging
import re
from hashlib import sha256
from datetime import timedelta
from decimal import Decimal, InvalidOperation
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from food.models import FoodProduct, Unit
logger = logging.getLogger(__name__)
FIELDS = 'code,product_name,brands,quantity,serving_size,serving_quantity,image_front_small_url,image_front_url,nutriments'
NUTRIENTS = {
'energy-kcal_100g': 'energy_kcal_100',
'carbohydrates_100g': 'carbohydrates_100',
'proteins_100g': 'protein_100',
'fat_100g': 'fat_100',
'saturated-fat_100g': 'saturated_fat_100',
'sugars_100g': 'sugars_100',
'fiber_100g': 'fibre_100',
'salt_100g': 'salt_100',
}
class OpenFoodFactsError(Exception):
pass
class OpenFoodFactsRateLimit(OpenFoodFactsError):
pass
def normalise_query(query):
return ' '.join(query.split()).casefold()
def _decimal(value):
try:
number = Decimal(str(value))
if not number.is_finite() or number < 0:
return None
return number.quantize(Decimal('0.001'))
except (InvalidOperation, TypeError, ValueError):
return None
def map_product(data):
"""Map only trusted display fields; unknown nutrients remain NULL."""
if not isinstance(data, dict):
return None
code = str(data.get('code') or '').strip()
name = str(data.get('product_name') or '').strip()
if not re.fullmatch(r'[0-9]{1,64}', code) or not name:
return None
nutriments = data.get('nutriments') or {}
if not isinstance(nutriments, dict):
nutriments = {}
values = {field: _decimal(nutriments.get(key)) for key, field in NUTRIENTS.items()}
serving_text = str(data.get('serving_size') or '')[:100]
match = re.search(r'(?i)(\d+(?:[.,]\d+)?)\s*(g|ml)\b', serving_text)
serving_amount = _decimal(match.group(1).replace(',', '.')) if match else None
serving_unit = match.group(2).lower() if match else ''
return {'barcode': code[:64], 'product_name': name[:255], 'brand': str(data.get('brands') or '')[:255],
'image_url': str(data.get('image_front_url') or data.get('image_front_small_url') or '')[:200],
'package_quantity': str(data.get('quantity') or '')[:100], 'serving_size_text': serving_text,
'serving_amount': serving_amount, 'serving_unit': serving_unit,
'base_unit': Unit.MILLILITRE if serving_unit == 'ml' else Unit.GRAM, **values}
def _rate_limit(user_id, kind, limit):
"""Simple per-user, per-minute guard; a shared cache backend is advised in production."""
key = f'off:limit:{kind}:{user_id}:{timezone.now():%Y%m%d%H%M}'
cache.add(key, 0, 70)
try:
count = cache.incr(key)
except ValueError:
cache.set(key, 1, 70)
count = 1
if count > limit:
raise OpenFoodFactsRateLimit('Open Food Facts request limit reached. Try again in a minute.')
class OpenFoodFactsClient:
def _get_json(self, url, params=None):
if not settings.OPENFOODFACTS_ENABLED:
raise OpenFoodFactsError('Open Food Facts is unavailable.')
if params:
url = f'{url}?{urlencode(params)}'
request = Request(url, headers={'User-Agent': settings.OPENFOODFACTS_USER_AGENT, 'Accept': 'application/json'})
try:
with urlopen(request, timeout=settings.OPENFOODFACTS_TIMEOUT_SECONDS) as response:
data = json.load(response)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as error:
logger.warning('Open Food Facts request failed: %s', error)
raise OpenFoodFactsError('Open Food Facts is temporarily unavailable.') from error
if not isinstance(data, dict):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return data
def get_product(self, barcode):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
data = self._get_json(settings.OPENFOODFACTS_PRODUCT_URL.format(barcode=barcode), {'fields': FIELDS})
return data.get('product') if data.get('status') == 1 else None
def search(self, query, page=1):
query = normalise_query(query)
if not query or len(query) > 100 or page < 1 or page > 20:
raise ValueError('Enter a search query and valid page.')
data = self._get_json(settings.OPENFOODFACTS_SEARCH_URL, {'action': 'process', 'search_simple': 1,
'json': 1, 'search_terms': query, 'page': page, 'page_size': 20, 'fields': FIELDS})
products = data.get('products')
if not isinstance(products, list):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return [mapped for item in products if (mapped := map_product(item))]
def cached_product(user, barcode, *, refresh=False):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
if product and (product.source == FoodProduct.Source.MANUAL or
(not refresh and product.fetched_at and product.fetched_at >= timezone.now() - timedelta(days=7))):
return product
if not settings.OPENFOODFACTS_ENABLED:
return product
_rate_limit(user.pk, 'product', 10)
try:
data = OpenFoodFactsClient().get_product(barcode)
except OpenFoodFactsError:
if product:
return product
raise
mapped = map_product(data)
if not mapped:
return product
mapped['source'] = FoodProduct.Source.OPEN_FOOD_FACTS
mapped['fetched_at'] = timezone.now()
nutrients = data.get('nutriments') if isinstance(data.get('nutriments'), dict) else {}
mapped['raw_data'] = {'code': barcode, 'product_name': mapped['product_name'],
'nutriments': {key: nutrients.get(key) for key in NUTRIENTS}}
product, _ = FoodProduct.objects.update_or_create(owner=user, barcode=barcode, defaults=mapped)
return product
def cached_search(user, query, page=1):
normalized = normalise_query(query)
if not normalized or len(normalized) > 100 or page < 1 or page > 20:
raise ValueError('Enter a search query and valid page.')
digest = sha256(normalized.encode()).hexdigest()
key = f'off:search:{digest}:{page}'
result = cache.get(key)
if result is not None:
return result
_rate_limit(user.pk, 'search', 5)
_rate_limit('all', 'search', 8)
lock_key = f'{key}:lock'
if not cache.add(lock_key, True, 20):
result = cache.get(key)
if result is not None:
return result
raise OpenFoodFactsError('This search is already running. Try again shortly.')
try:
result = OpenFoodFactsClient().search(normalized, page)
cache.set(key, result, 24 * 60 * 60)
return result
finally:
cache.delete(lock_key)
+1
View File
@@ -1,2 +1,3 @@
.food-page{max-width:1180px;margin:0 auto;padding:1.5rem 0 4rem}.food-heading,.food-meal-heading{display:flex;justify-content:space-between;align-items:center;gap:1rem}.food-heading nav{display:flex;gap:.5rem;align-items:center}.food-heading nav a,.food-add-meal{display:inline-flex;align-items:center;justify-content:center;min-width:44px;min-height:44px;border:1px solid currentColor;border-radius:50%;text-decoration:none}.food-layout{display:grid;grid-template-columns:minmax(0,1fr) minmax(290px,340px);gap:2rem;align-items:start}.food-sidebar{position:sticky;top:1rem}.food-card{background:var(--surface,#222);border:1px solid var(--border,#555);border-radius:1.2rem;padding:1.2rem;margin-bottom:1rem}.food-card h2,.food-card h3{margin:.1rem 0 .5rem}.food-remaining{font-size:1.45rem;font-weight:700}.food-progress{height:.65rem;background:#7776;border-radius:2rem;overflow:hidden}.food-progress span{display:block;height:100%;background:#62bd70;border-radius:inherit}.food-macros{display:grid;gap:.7rem}.food-macro{display:flex;align-items:center;gap:1rem}.food-macro p{margin:.15rem 0}.food-ring{--accent:#d45b8b;flex:none;width:74px;height:74px;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--accent) var(--progress,0%),#7776 0)}.food-ring span{display:grid;place-items:center;width:60px;height:60px;background:var(--surface,#222);border-radius:50%;font-weight:700}.food-macro--blue{--accent:#53a9e7}.food-macro--orange{--accent:#e87952}.food-meal{margin-bottom:1.5rem}.food-meal-heading h2{margin:0}.food-meal-heading p{margin:.1rem 0;color:#62bd70}.food-add-meal{color:#62bd70;font-size:1.8rem}.food-entry-list,.food-product-list{list-style:none;margin:.8rem 0;padding:0}.food-entry,.food-product-list li{background:var(--surface,#222);border:1px solid var(--border,#555);padding:1rem;border-radius:1rem;margin:.4rem 0}.food-entry{display:flex;align-items:center;justify-content:space-between;gap:1rem}.food-entry-main{display:flex;align-items:center;gap:.8rem;min-width:0}.food-entry-main img{width:64px;height:64px;object-fit:contain;background:white;border-radius:.6rem}.food-entry-main strong,.food-entry-main span,.food-entry-main small{display:block}.food-entry-main small,.food-entry-main span,.food-empty{opacity:.75}.food-form-page{max-width:620px;margin:1.5rem auto 4rem}.food-form-page .food-card{margin-top:1rem}.food-search{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center}.food-search input{min-width:180px;flex:1}.food-product-list a{display:block;min-height:44px;align-content:center}.food-form-page details dl{display:grid;grid-template-columns:1fr 1fr;gap:.4rem}.food-form-page details dd{margin:0;text-align:right}@media(max-width:760px){.food-layout{display:flex;flex-direction:column-reverse;gap:1rem}.food-sidebar{position:static;width:100%}.food-macros{grid-template-columns:repeat(3,minmax(0,1fr));gap:.4rem}.food-macro{display:block;padding:.65rem;text-align:center}.food-ring{margin:auto;width:58px;height:58px}.food-ring span{width:46px;height:46px;font-size:.8rem}.food-macro h3{font-size:.9rem;overflow-wrap:anywhere}.food-macro p{font-size:.8rem}.food-heading h1{font-size:1.5rem}.food-page{padding-top:.5rem}}@media(max-width:400px){.food-macros{grid-template-columns:1fr}.food-macro{display:flex;text-align:left}.food-ring{margin:0}}@media(prefers-reduced-motion:reduce){.food-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
.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}
+47 -1
View File
@@ -1,3 +1,49 @@
{% extends 'planner/base.html' %}{% load static %}
{% 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></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 }}"><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><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 }}">{{ item.product_name }}{% if item.brand %} · {{ item.brand }}{% endif %}</a></li>{% empty %}<li>No local foods yet.</li>{% endfor %}</ul><a class="button" href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">Create a food manually</a>{% endif %}</div>{% 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 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>
{% endblock %}
@@ -0,0 +1,12 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Search Open Food Facts · 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 }}">← Saved foods</a>
<h1>Search Open Food Facts</h1>
<p>Search the external catalogue only when you press the button. Saved foods remain available if it is offline.</p>
<form method="post" class="food-search">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><label for="external-query">Product name</label><input id="external-query" type="search" name="q" value="{{ query }}" required><button class="button" type="submit">Search Open Food Facts</button></form>
{% if notice %}<p role="status">{{ notice }} Recent, favourite, and saved products are still available.</p>{% endif %}
{% if results %}<ul class="food-product-list">{% for item in results %}<li><form method="post" action="{% url 'food:import-product' %}">{% csrf_token %}<input type="hidden" name="date" value="{{ day|date:'Y-m-d' }}"><input type="hidden" name="meal" value="{{ meal }}"><input type="hidden" name="barcode" value="{{ item.barcode }}"><button class="food-result-button" type="submit">{% 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></button></form></li>{% endfor %}</ul>{% elif request.method == 'POST' and not notice %}<p>No matching products found. You can <a href="{% url 'food:manual' %}?date={{ day|date:'Y-m-d' }}&amp;meal={{ meal }}">create a food manually</a>.</p>{% endif %}
<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
</div>{% endblock %}
+102
View File
@@ -0,0 +1,102 @@
from datetime import timedelta
from decimal import Decimal
from unittest.mock import patch
from urllib.error import URLError
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from .models import FoodProduct
from .services.openfoodfacts import (
OpenFoodFactsClient, OpenFoodFactsError, OpenFoodFactsRateLimit,
cached_product, cached_search, map_product, normalise_query,
)
SAMPLE = {'code': '1234567890123', 'product_name': 'Greek yoghurt', 'brands': 'Lidl',
'serving_size': '300 g', 'nutriments': {'energy-kcal_100g': 58, 'proteins_100g': 6}}
class OpenFoodFactsTests(TestCase):
def setUp(self):
cache.clear()
self.user = get_user_model().objects.create_user(username='off-user', password='test-password')
self.client.force_login(self.user)
def test_query_normalisation_and_missing_nutrients(self):
self.assertEqual(normalise_query(' Griekse Yoghurt '), 'griekse yoghurt')
mapped = map_product(SAMPLE)
self.assertEqual(mapped['serving_amount'], Decimal('300.000'))
self.assertEqual(mapped['energy_kcal_100'], Decimal('58.000'))
self.assertIsNone(mapped['fat_100'])
@patch.object(OpenFoodFactsClient, 'get_product')
def test_fresh_cached_barcode_avoids_http(self, get_product):
product = FoodProduct.objects.create(owner=self.user, barcode=SAMPLE['code'],
product_name='Saved yoghurt', source='openfoodfacts', fetched_at=timezone.now())
self.assertEqual(cached_product(self.user, SAMPLE['code']), product)
get_product.assert_not_called()
@patch.object(OpenFoodFactsClient, 'get_product', return_value=SAMPLE)
def test_stale_barcode_refreshes_and_preserves_null(self, get_product):
product = FoodProduct.objects.create(owner=self.user, barcode=SAMPLE['code'],
product_name='Old yoghurt', source='openfoodfacts', fetched_at=timezone.now() - timedelta(days=8))
refreshed = cached_product(self.user, SAMPLE['code'])
self.assertEqual(refreshed.pk, product.pk)
self.assertEqual(refreshed.product_name, 'Greek yoghurt')
self.assertIsNone(refreshed.fat_100)
get_product.assert_called_once_with(SAMPLE['code'])
@patch.object(OpenFoodFactsClient, 'search', return_value=[map_product(SAMPLE)])
def test_explicit_search_cache_and_local_typing(self, search):
response = self.client.get(reverse('food:add'), {'q': 'Greek'})
self.assertEqual(response.status_code, 200)
search.assert_not_called()
results = cached_search(self.user, ' Griekse Yoghurt ')
self.assertEqual(cached_search(self.user, 'griekse yoghurt'), results)
search.assert_called_once_with('griekse yoghurt', 1)
response = self.client.post(reverse('food:external-search'), {'q': 'griekse yoghurt',
'meal': 'breakfast', 'date': '2026-10-03'})
self.assertContains(response, 'Greek yoghurt')
search.assert_called_once()
@patch.object(OpenFoodFactsClient, 'search', side_effect=OpenFoodFactsError('Open Food Facts is temporarily unavailable.'))
def test_timeout_is_graceful(self, search):
response = self.client.post(reverse('food:external-search'), {'q': 'yoghurt',
'meal': 'breakfast', 'date': '2026-10-03'})
self.assertContains(response, 'Recent, favourite, and saved products are still available.')
self.assertEqual(response.status_code, 200)
@patch.object(OpenFoodFactsClient, 'search', return_value=[])
def test_search_rate_limit(self, search):
for index in range(5):
cached_search(self.user, f'query {index}')
with self.assertRaises(OpenFoodFactsRateLimit):
cached_search(self.user, 'sixth query')
self.assertEqual(search.call_count, 5)
@patch.object(OpenFoodFactsClient, 'get_product', return_value=SAMPLE)
def test_import_then_local_reuse(self, get_product):
response = self.client.post(reverse('food:import-product'), {'barcode': SAMPLE['code'],
'meal': 'dinner', 'date': '2026-10-03'})
self.assertEqual(response.status_code, 302)
self.assertIn('meal=dinner', response['Location'])
self.assertEqual(FoodProduct.objects.filter(owner=self.user).count(), 1)
self.client.post(reverse('food:import-product'), {'barcode': SAMPLE['code'],
'meal': 'dinner', 'date': '2026-10-03'})
get_product.assert_called_once()
@patch.object(OpenFoodFactsClient, 'get_product', side_effect=OpenFoodFactsError('Open Food Facts is temporarily unavailable.'))
def test_import_failure_keeps_local_flow_available(self, get_product):
response = self.client.post(reverse('food:import-product'), {'barcode': SAMPLE['code'],
'meal': 'dinner', 'date': '2026-10-03'}, follow=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, 'saved products are still available')
@patch('food.services.openfoodfacts.urlopen', side_effect=URLError('timeout'))
def test_http_timeout_raises_service_error(self, urlopen):
with self.assertRaises(OpenFoodFactsError):
OpenFoodFactsClient().get_product(SAMPLE['code'])
+2
View File
@@ -7,6 +7,8 @@ app_name = 'food'
urlpatterns = [
path('', views.diary, name='diary'),
path('add/', views.add_food, name='add'),
path('search/openfoodfacts/', views.external_search, name='external-search'),
path('import/openfoodfacts/', views.import_product, name='import-product'),
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'),
+67 -3
View File
@@ -1,7 +1,11 @@
from decimal import Decimal
import logging
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest
from django.contrib import messages
from django.db.models import Q
from django.db.models import Max
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
@@ -9,6 +13,10 @@ from django.views.decorators.http import require_http_methods, require_POST
from .forms import FoodLogForm, ManualFoodForm
from .models import FoodLogEntry, FoodProduct, MealType
from .services.diary import diary_context, selected_date
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
logger = logging.getLogger(__name__)
def _day(request):
@@ -66,9 +74,18 @@ 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]
products = FoodProduct.objects.filter(owner=request.user).order_by('product_name')
tab = request.GET.get('tab', 'recent')
if tab not in ('recent', 'favourites', 'mine'):
tab = 'recent'
products = FoodProduct.objects.filter(owner=request.user)
if query:
products = products.filter(product_name__icontains=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')
elif tab == 'mine':
products = products.order_by('product_name')
else:
products = products.filter(log_entries__user=request.user).annotate(last_used=Max('log_entries__created_at')).order_by('-last_used')
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:
@@ -77,7 +94,54 @@ def add_food(request):
_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})
'product': product, 'form': form, 'query': query, 'tab': tab})
@login_required
@require_http_methods(['GET', 'POST'])
def external_search(request):
day, error = _day(request)
if error:
return error
meal = request.GET.get('meal') or request.POST.get('meal') or MealType.BREAKFAST
if meal not in MealType.values:
return HttpResponseBadRequest('Invalid meal.')
query = (request.GET.get('q') or request.POST.get('q') or '').strip()[:100]
try:
page = int(request.GET.get('page', '1'))
except ValueError:
return HttpResponseBadRequest('Invalid page.')
results = []
notice = ''
if request.method == 'POST':
try:
results = cached_search(request.user, query, page)
except (OpenFoodFactsError, ValueError) as error:
logger.info('Food external search unavailable: %s', error)
notice = str(error)
return render(request, 'food/external_search.html', {'day': day, 'meal': meal, 'query': query,
'results': results, 'notice': notice, 'page': page})
@login_required
@require_POST
def import_product(request):
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.')
barcode = request.POST.get('barcode', '').strip()
try:
product = cached_product(request.user, barcode)
except (OpenFoodFactsError, ValueError) as error:
messages.warning(request, f'{error} Recent, favourite, and saved products are still available.')
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}")
if not product:
messages.warning(request, 'Product not found. You can create it manually.')
return redirect(f"{reverse('food:manual')}?date={day}&meal={meal}")
return redirect(f"{reverse('food:add')}?date={day}&meal={meal}&product={product.pk}")
@login_required
+7
View File
@@ -130,6 +130,13 @@ VITE_DEV_SERVER = os.environ.get('VITE_DEV_SERVER', 'http://localhost:5173')
VITE_USE_DEV_SERVER = os.environ.get('VITE_USE_DEV_SERVER', str(DEBUG)).lower() in {'1', 'true', 'yes'}
VITE_MANIFEST_PATH = BASE_DIR / 'planner' / 'static' / 'planner' / 'dist' / '.vite' / 'manifest.json'
# Open Food Facts is queried only by explicit food search or product lookup.
OPENFOODFACTS_ENABLED = os.environ.get('OPENFOODFACTS_ENABLED', 'true').lower() in {'1', 'true', 'yes'}
OPENFOODFACTS_PRODUCT_URL = os.environ.get('OPENFOODFACTS_PRODUCT_URL', 'https://world.openfoodfacts.org/api/v2/product/{barcode}.json')
OPENFOODFACTS_SEARCH_URL = os.environ.get('OPENFOODFACTS_SEARCH_URL', 'https://world.openfoodfacts.org/cgi/search.pl')
OPENFOODFACTS_USER_AGENT = os.environ.get('OPENFOODFACTS_USER_AGENT', 'Tasknest/1.0 (https://tasksnest.jorendegraaf.eu)')
OPENFOODFACTS_TIMEOUT_SECONDS = float(os.environ.get('OPENFOODFACTS_TIMEOUT_SECONDS', '6'))
# Optional Gitea contribution grid on the task dashboard. Read only these
# values from the repository's ignored .env file; the process environment wins.
def _gitea_env(name, default=''):