food logger context tips
This commit is contained in:
+198
-4
@@ -23,6 +23,9 @@ from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, Food
|
||||
InventoryCategory, InventoryLocation, KitchenInventoryItem,
|
||||
MealType, PersonalAccessToken, Unit)
|
||||
from .services.logging import apply_product_snapshot
|
||||
from .services.openfoodfacts import OpenFoodFactsError
|
||||
from .services.product_resolution import (create_manual, external_matches, import_off,
|
||||
local_matches, match_data)
|
||||
|
||||
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'}
|
||||
NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
|
||||
@@ -183,6 +186,8 @@ def _product_data(product):
|
||||
if isinstance(data[name], Decimal):
|
||||
data[name] = str(data[name])
|
||||
data['id'] = str(product.api_id)
|
||||
data['package_amount'] = str(product.package_amount) if product.package_amount is not None else None
|
||||
data['package_unit'] = product.package_unit or None
|
||||
data['portions'] = [{'label': p.label, 'amount': str(p.amount), 'unit': p.unit,
|
||||
'is_default': p.is_default} for p in product.portions.all()]
|
||||
return data
|
||||
@@ -194,6 +199,7 @@ def _inventory_data(item):
|
||||
'barcode': item.product.barcode, 'quantity': item.quantity,
|
||||
'location': item.location.name, 'category': item.category.name if item.category else None,
|
||||
'notes': item.notes, 'opened': item.opened,
|
||||
'remaining_amount': str(item.remaining_amount) if item.remaining_amount is not None else None,
|
||||
'best_before': item.best_before.isoformat() if item.best_before else None,
|
||||
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
|
||||
|
||||
@@ -233,11 +239,17 @@ def today(request):
|
||||
.select_related('product').prefetch_related('attachments'))
|
||||
meals = {meal: [_entry_data(e) for e in entries if e.meal == meal] for meal in MealType.values}
|
||||
totals = {name: str(sum((getattr(e, name) or Decimal('0') for e in entries), Decimal('0')))
|
||||
for name in NUTRIENTS}
|
||||
for name in NUTRIENTS if name != 'fibre_g'}
|
||||
fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None]
|
||||
fibre_incomplete = len(fibre_values) != len(entries)
|
||||
totals['fibre_g'] = str(sum(fibre_values, Decimal('0'))) if fibre_values or not entries else None
|
||||
goals = UserSettings.objects.filter(user=request.api_user).first()
|
||||
goal_data = {name: str(getattr(goals, name)) if goals and getattr(goals, name) is not None else None
|
||||
for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g')}
|
||||
return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals, 'goals': goal_data})
|
||||
for name in ('daily_calorie_goal', 'carbohydrate_goal_g', 'protein_goal_g', 'fat_goal_g', 'fibre_goal_g')}
|
||||
if goals is None:
|
||||
goal_data['fibre_goal_g'] = '40.0'
|
||||
return JsonResponse({'date': day.isoformat(), 'meals': meals, 'totals': totals,
|
||||
'fibre_incomplete': fibre_incomplete, 'goals': goal_data})
|
||||
|
||||
|
||||
@api_view(None, ('GET',))
|
||||
@@ -258,6 +270,185 @@ def products(request):
|
||||
return JsonResponse(page)
|
||||
|
||||
|
||||
@api_view('food:read', ('GET',))
|
||||
def product_lookup(request):
|
||||
query = request.GET.get('query', '').strip()
|
||||
brand = request.GET.get('brand', '').strip()
|
||||
barcode = request.GET.get('barcode', '').strip()
|
||||
package_value = request.GET.get('package_quantity')
|
||||
package_unit = request.GET.get('package_unit', '')
|
||||
if package_value is not None:
|
||||
from .services.product_resolution import _amount
|
||||
package_amount = _amount(package_value, 'package_quantity')
|
||||
else:
|
||||
package_amount = None
|
||||
if (package_amount is None) != (not package_unit) or package_unit not in ('', 'g', 'ml'):
|
||||
raise ValueError('Package quantity and unit must be supplied together.')
|
||||
if len(query) > 100 or len(brand) > 255 or (barcode and (not barcode.isascii() or not barcode.isdigit() or len(barcode) > 64)):
|
||||
raise ValueError('Invalid product search.')
|
||||
if not query and not barcode:
|
||||
raise ValueError('Provide a query or barcode.')
|
||||
try:
|
||||
limit = int(request.GET.get('limit', 10))
|
||||
except ValueError:
|
||||
raise ValueError('Invalid limit.') from None
|
||||
if not 1 <= limit <= 20:
|
||||
raise ValueError('Limit must be between 1 and 20.')
|
||||
local = local_matches(request.api_user, query, brand, barcode, package_amount, package_unit,
|
||||
limit, include_partial=True)
|
||||
if barcode and local and local[0]['confidence'] == 'exact_barcode':
|
||||
return JsonResponse({'matches': local, 'external_error': None})
|
||||
matches = list(local)
|
||||
external_error = None
|
||||
if request.GET.get('include_open_food_facts', 'true').lower() in ('true', 'false'):
|
||||
include_off = request.GET.get('include_open_food_facts', 'true').lower() == 'true'
|
||||
else:
|
||||
raise ValueError('include_open_food_facts must be true or false.')
|
||||
if include_off and len(matches) < limit and not any(m['confidence'] in ('exact_barcode', 'exact_details') for m in matches):
|
||||
try:
|
||||
matches.extend(external_matches(request.api_user, query, barcode, brand, package_amount,
|
||||
package_unit, limit-len(matches)))
|
||||
except OpenFoodFactsError as exc:
|
||||
external_error = str(exc)
|
||||
return JsonResponse({'matches': matches[:limit], 'external_error': external_error})
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def product_create(request):
|
||||
data = _json(request)
|
||||
def create():
|
||||
product, status, candidates = create_manual(request.api_user, data)
|
||||
if status == 'needs_review':
|
||||
return JsonResponse({'status': status, 'candidates': candidates})
|
||||
return JsonResponse({'status': status, 'product_id': str(product.api_id), 'product': _product_data(product)},
|
||||
status=201 if status == 'created' else 200)
|
||||
return _idempotent(request, data, create)
|
||||
|
||||
|
||||
@api_view('food:write', ('POST',))
|
||||
def product_import(request):
|
||||
data = _json(request)
|
||||
if set(data) != {'barcode'}:
|
||||
raise ValueError('Provide an Open Food Facts barcode.')
|
||||
def create():
|
||||
existing = FoodProduct.objects.filter(owner=request.api_user, barcode=data['barcode']).first()
|
||||
try:
|
||||
product = import_off(request.api_user, data['barcode'])
|
||||
except OpenFoodFactsError as exc:
|
||||
return error('external_unavailable', str(exc), 503)
|
||||
if product is None:
|
||||
return error('external_product_not_found', 'Open Food Facts product not found.', 404)
|
||||
return JsonResponse({'status': 'reused' if existing else 'imported',
|
||||
'product_id': str(product.api_id), 'product': _product_data(product)},
|
||||
status=200 if existing else 201)
|
||||
return _idempotent(request, data, create)
|
||||
|
||||
|
||||
@api_view({'POST': 'inventory:write'}, ('POST',))
|
||||
def inventory_import_groceries(request):
|
||||
if 'food:write' not in request.api_token.scopes:
|
||||
return error('insufficient_scope', 'Missing food:write scope.', 403)
|
||||
if not request.headers.get('Idempotency-Key'):
|
||||
return error('idempotency_key_required', 'Provide an Idempotency-Key for a grocery import.')
|
||||
data = _json(request)
|
||||
if set(data) - {'items', 'create_missing_products'} or not isinstance(data.get('items'), list) or not 1 <= len(data['items']) <= 20:
|
||||
raise ValueError('Provide between 1 and 20 grocery items.')
|
||||
create_missing = data.get('create_missing_products', False)
|
||||
if not isinstance(create_missing, bool):
|
||||
raise ValueError('create_missing_products must be a boolean.')
|
||||
|
||||
def create():
|
||||
results = []
|
||||
for index, raw in enumerate(data['items']):
|
||||
if not isinstance(raw, dict):
|
||||
results.append({'index': index, 'status': 'skipped', 'reason': 'Item must be an object.'})
|
||||
continue
|
||||
try:
|
||||
with transaction.atomic():
|
||||
result = _import_one_grocery(request, raw, create_missing)
|
||||
except (ValueError, ValidationError) as exc:
|
||||
result = {'status': 'skipped', 'reason': str(exc)}
|
||||
except OpenFoodFactsError as exc:
|
||||
result = {'status': 'skipped', 'reason': str(exc)}
|
||||
results.append({'index': index, 'name': raw.get('name'), **result})
|
||||
added = sum(row['status'] == 'added' for row in results)
|
||||
review = sum(row['status'] == 'needs_review' for row in results)
|
||||
return JsonResponse({'status': 'success' if added == len(results) else 'partial_success' if added else 'no_items_added',
|
||||
'created': added, 'skipped': len(results)-added-review, 'needs_review': review,
|
||||
'items': results})
|
||||
return _idempotent(request, data, create)
|
||||
|
||||
|
||||
def _import_one_grocery(request, raw, create_missing):
|
||||
allowed = {'product_id', 'name', 'brand', 'barcode', 'quantity', 'package_quantity', 'package_unit',
|
||||
'nutrition_per_100', 'location', 'category', 'notes', 'opened', 'best_before'}
|
||||
if set(raw) - allowed:
|
||||
raise ValueError('Unknown grocery fields.')
|
||||
if len(str(raw.get('notes', ''))) > 2000:
|
||||
raise ValueError('Notes are too long.')
|
||||
product = None
|
||||
product_status = 'reused'
|
||||
if raw.get('product_id'):
|
||||
if any(raw.get(key) is not None for key in ('name', 'brand', 'barcode', 'package_quantity',
|
||||
'package_unit', 'nutrition_per_100')):
|
||||
raise ValueError('Provide product_id or product details, not both.')
|
||||
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(raw['product_id'])).first()
|
||||
if not product:
|
||||
raise ValueError('Product not found.')
|
||||
else:
|
||||
name, brand, barcode = raw.get('name', ''), raw.get('brand', ''), raw.get('barcode', '')
|
||||
if not isinstance(name, str) or not isinstance(brand, str) or not isinstance(barcode, str) or not name.strip():
|
||||
raise ValueError('A product name is required.')
|
||||
if len(name) > 255 or len(brand) > 255 or len(barcode) > 64:
|
||||
raise ValueError('Product details are too long.')
|
||||
amount = raw.get('package_quantity')
|
||||
if amount is not None:
|
||||
from .services.product_resolution import _amount
|
||||
amount = _amount(amount, 'package_quantity')
|
||||
unit = raw.get('package_unit') or ''
|
||||
if (amount is None) != (not unit) or unit not in ('', 'g', 'ml'):
|
||||
raise ValueError('Package quantity and unit must be supplied together.')
|
||||
local = local_matches(request.api_user, name.strip(), brand.strip(), barcode.strip(), amount, unit)
|
||||
exact = [m for m in local if m['confidence'] == 'exact_barcode' or
|
||||
(not barcode and m['confidence'] == 'exact_details')]
|
||||
if len(exact) == 1:
|
||||
product = FoodProduct.objects.get(owner=request.api_user, api_id=exact[0]['product_id'])
|
||||
elif local:
|
||||
return {'status': 'needs_review', 'reason': 'Multiple or uncertain local matches.', 'candidates': local}
|
||||
elif barcode:
|
||||
try:
|
||||
product = import_off(request.api_user, barcode)
|
||||
except OpenFoodFactsError:
|
||||
product = None
|
||||
if product:
|
||||
product_status = 'imported'
|
||||
if product is None and not barcode and name.strip() and brand.strip() and amount is not None:
|
||||
try:
|
||||
matches = external_matches(request.api_user, name.strip(), brand=brand.strip(), amount=amount, unit=unit)
|
||||
except OpenFoodFactsError:
|
||||
matches = []
|
||||
exact = [m for m in matches if m['confidence'] == 'exact_details']
|
||||
if len(exact) == 1:
|
||||
product = import_off(request.api_user, exact[0]['barcode'])
|
||||
product_status = 'imported'
|
||||
elif matches:
|
||||
return {'status': 'needs_review', 'reason': 'Open Food Facts matches require selection.', 'candidates': matches}
|
||||
if product is None:
|
||||
if not create_missing:
|
||||
return {'status': 'needs_review', 'reason': 'No confirmed product. Select or create one.'}
|
||||
product, product_status, candidates = create_manual(request.api_user, {
|
||||
key: raw[key] for key in ('name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100') if key in raw})
|
||||
if product is None:
|
||||
return {'status': 'needs_review', 'reason': 'Possible duplicate product.', 'candidates': candidates}
|
||||
inventory_data = {key: raw[key] for key in ('quantity', 'location', 'category', 'notes', 'opened', 'best_before') if key in raw}
|
||||
inventory_data['product_id'] = str(product.api_id)
|
||||
item, failure = _save_inventory(request, inventory_data)
|
||||
if failure:
|
||||
raise ValueError('Unable to add inventory item.')
|
||||
return {'status': 'added', 'product_id': str(product.api_id), 'product_status': product_status,
|
||||
'inventory_item_id': str(item.api_id), 'quantity_incremented': False}
|
||||
|
||||
|
||||
def _save_entry(request, data, entry=None):
|
||||
creating = entry is None
|
||||
if creating:
|
||||
@@ -358,7 +549,7 @@ def inventory_list(request):
|
||||
def _save_inventory(request, data, item=None):
|
||||
if item is None:
|
||||
item = KitchenInventoryItem(user=request.api_user)
|
||||
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before'}
|
||||
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount'}
|
||||
if set(data) - allowed:
|
||||
raise ValueError('Unknown inventory fields.')
|
||||
if 'product_id' in data:
|
||||
@@ -387,6 +578,9 @@ def _save_inventory(request, data, item=None):
|
||||
if not isinstance(data['opened'], bool):
|
||||
raise ValueError('opened must be a boolean.')
|
||||
item.opened = data['opened']
|
||||
if 'remaining_amount' in data:
|
||||
item.remaining_amount = (_decimal(data['remaining_amount'], 'remaining_amount')
|
||||
if data['remaining_amount'] is not None else None)
|
||||
if 'best_before' in data:
|
||||
item.best_before = _date(data['best_before'], request.api_user) if data['best_before'] else None
|
||||
if not item.product_id or not item.location_id:
|
||||
|
||||
@@ -36,6 +36,17 @@ INVENTORY = {'type': 'object', 'properties': {
|
||||
'product_id': {'type': 'string', 'format': 'uuid'}, 'quantity': {'type': 'integer', 'minimum': 1},
|
||||
'location': {'type': 'string'}, 'category': {'type': 'string'}, 'notes': {'type': 'string'},
|
||||
'opened': {'type': 'boolean'}, 'best_before': {'type': ['string', 'null'], 'format': 'date'},
|
||||
'remaining_amount': {'type': ['string', 'null'], 'description': 'Only for one opened package with known size'},
|
||||
}}
|
||||
PRODUCT = {'type': 'object', 'required': ['name'], 'properties': {
|
||||
'name': {'type': 'string', 'maxLength': 255}, 'brand': {'type': 'string', 'maxLength': 255},
|
||||
'barcode': {'type': ['string', 'null']}, 'package_quantity': {'type': ['string', 'number', 'null']},
|
||||
'package_unit': {'type': ['string', 'null'], 'enum': ['g', 'ml', None]},
|
||||
'nutrition_per_100': {'type': ['object', 'null']}, 'source': {'type': 'string', 'enum': ['manual']},
|
||||
}}
|
||||
GROCERIES = {'type': 'object', 'required': ['items'], 'properties': {
|
||||
'items': {'type': 'array', 'minItems': 1, 'maxItems': 20, 'items': {'type': 'object'}},
|
||||
'create_missing_products': {'type': 'boolean'},
|
||||
}}
|
||||
UPLOAD = {'type': 'object', 'required': ['image'], 'properties': {
|
||||
'image': {'type': 'string', 'format': 'binary'}, 'caption': {'type': 'string'},
|
||||
@@ -51,6 +62,10 @@ def schema(request):
|
||||
'paths': {
|
||||
'/food/today/': {'get': operation('Food log for an optional local calendar date, defaulting to today', 'food:read')},
|
||||
'/food/products/': {'get': operation('Search own food products', 'food:read')},
|
||||
'/food/products/lookup/': {'get': operation('Look up local and optional Open Food Facts product candidates', 'food:read')},
|
||||
'/food/products/create/': {'post': operation('Create or reuse an owned manual food product', 'food:write', PRODUCT)},
|
||||
'/food/products/import/': {'post': operation('Import a selected Open Food Facts barcode', 'food:write',
|
||||
{'type': 'object', 'required': ['barcode'], 'properties': {'barcode': {'type': 'string'}}})},
|
||||
'/food/log/': {'post': operation('Create food log entry', 'food:write', ENTRY)},
|
||||
'/food/log/{id}/': {
|
||||
'get': operation('Read own entry', 'food:read'),
|
||||
@@ -64,6 +79,8 @@ def schema(request):
|
||||
'get': operation('Search own inventory', 'inventory:read'),
|
||||
'post': operation('Create inventory item', 'inventory:write', INVENTORY),
|
||||
},
|
||||
'/kitchen/import-groceries/': {'post': operation('Import up to 20 groceries with per-item results',
|
||||
'inventory:write + food:write', GROCERIES)},
|
||||
'/kitchen/items/{id}/': {
|
||||
'get': operation('Read own inventory item', 'inventory:read'),
|
||||
'patch': operation('Update own inventory item', 'inventory:write', INVENTORY),
|
||||
@@ -82,6 +99,16 @@ def schema(request):
|
||||
'description': 'Local calendar date; defaults to today in the user time zone.',
|
||||
'schema': {'type': 'string', 'format': 'date'},
|
||||
}]
|
||||
document['paths']['/food/products/lookup/']['get']['parameters'] = [
|
||||
{'name': name, 'in': 'query', 'required': False, 'schema': schema} for name, schema in (
|
||||
('query', {'type': 'string'}), ('barcode', {'type': 'string'}), ('brand', {'type': 'string'}),
|
||||
('package_quantity', {'type': 'number'}), ('package_unit', {'type': 'string', 'enum': ['g', 'ml']}),
|
||||
('limit', {'type': 'integer', 'minimum': 1, 'maximum': 20}),
|
||||
('include_open_food_facts', {'type': 'boolean'}))]
|
||||
document['paths']['/kitchen/import-groceries/']['post']['parameters'] = [{
|
||||
'name': 'Idempotency-Key', 'in': 'header', 'required': True,
|
||||
'schema': {'type': 'string', 'maxLength': 128},
|
||||
}]
|
||||
document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = {
|
||||
'description': 'Owned image bytes',
|
||||
'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}}
|
||||
|
||||
@@ -6,11 +6,15 @@ urlpatterns = [
|
||||
path('schema/', api_schema.schema),
|
||||
path('food/today/', api.today),
|
||||
path('food/products/', api.products),
|
||||
path('food/products/lookup/', api.product_lookup),
|
||||
path('food/products/create/', api.product_create),
|
||||
path('food/products/import/', api.product_import),
|
||||
path('food/log/', api.log_create),
|
||||
path('food/log/<uuid:identifier>/', api.log_item),
|
||||
path('food/log/<uuid:identifier>/attachments/', api.attachment_create),
|
||||
path('food/attachments/<uuid:identifier>/file/', api.attachment_file),
|
||||
path('food/attachments/<uuid:identifier>/', api.attachment_delete),
|
||||
path('kitchen/items/', api.inventory_collection),
|
||||
path('kitchen/import-groceries/', api.inventory_import_groceries),
|
||||
path('kitchen/items/<uuid:identifier>/', api.inventory_item),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import re
|
||||
from decimal import Decimal
|
||||
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
def backfill_package_size(apps, schema_editor):
|
||||
Product = apps.get_model('food', 'FoodProduct')
|
||||
for product in Product.objects.filter(package_amount__isnull=True).exclude(package_quantity='').iterator():
|
||||
match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', product.package_quantity, re.IGNORECASE)
|
||||
if not match:
|
||||
continue
|
||||
amount = Decimal(match.group(1).replace(',', '.'))
|
||||
unit = match.group(2).lower()
|
||||
if unit in ('kg', 'l'):
|
||||
amount *= 1000
|
||||
unit = 'g' if unit == 'kg' else 'ml'
|
||||
if 0 < amount <= Decimal('9999999.999'):
|
||||
Product.objects.filter(pk=product.pk).update(package_amount=amount, package_unit=unit)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
dependencies = [('food', '0004_foodlogentry_api_id_foodlogentry_created_via_and_more')]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(model_name='foodproduct', name='package_amount',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True,
|
||||
validators=[MinValueValidator(0.001)])),
|
||||
migrations.AddField(model_name='foodproduct', name='package_unit',
|
||||
field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2)),
|
||||
migrations.AddField(model_name='kitcheninventoryitem', name='remaining_amount',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True,
|
||||
validators=[MinValueValidator(0)])),
|
||||
migrations.RunPython(backfill_package_size, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -35,6 +35,8 @@ class FoodProduct(models.Model):
|
||||
brand = models.CharField(max_length=255, blank=True)
|
||||
image_url = models.URLField(blank=True)
|
||||
package_quantity = models.CharField(max_length=100, blank=True)
|
||||
package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
||||
package_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True)
|
||||
serving_size_text = models.CharField(max_length=100, blank=True)
|
||||
serving_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
|
||||
serving_unit = models.CharField(max_length=2, choices=Unit.choices, blank=True)
|
||||
@@ -169,6 +171,7 @@ class KitchenInventoryItem(models.Model):
|
||||
category = models.ForeignKey(InventoryCategory, on_delete=models.PROTECT, null=True, blank=True)
|
||||
notes = models.TextField(blank=True)
|
||||
opened = models.BooleanField(default=False)
|
||||
remaining_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
|
||||
best_before = models.DateField(null=True, blank=True)
|
||||
archived_at = models.DateTimeField(null=True, blank=True)
|
||||
added_at = models.DateTimeField(auto_now_add=True)
|
||||
@@ -176,6 +179,10 @@ class KitchenInventoryItem(models.Model):
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if self.remaining_amount is not None and (not self.product_id or self.quantity != 1 or not self.opened or
|
||||
not self.product.package_amount or
|
||||
self.remaining_amount > self.product.package_amount):
|
||||
raise ValidationError({'remaining_amount': 'Remaining contents require one opened package with a known package size.'})
|
||||
if self.user_id and self.product_id and self.product.owner_id != self.user_id:
|
||||
raise ValidationError({'product': 'Choose one of your own products.'})
|
||||
if self.user_id and self.location_id and self.location.user_id != self.user_id:
|
||||
|
||||
@@ -5,6 +5,7 @@ from django.utils import timezone
|
||||
from django.utils.dateparse import parse_date
|
||||
|
||||
from food.models import FoodLogEntry, MealType
|
||||
from food.services.nutrient_help import nutrient_guidance
|
||||
from planner.models import UserSettings
|
||||
from planner.timezones import localdate_for_user
|
||||
|
||||
@@ -22,12 +23,15 @@ def selected_date(request):
|
||||
return day
|
||||
|
||||
|
||||
def diary_context(user, day):
|
||||
def diary_context(user, day, language='en'):
|
||||
goals, _ = UserSettings.objects.get_or_create(user=user)
|
||||
entries = list(FoodLogEntry.objects.filter(user=user, date=day).select_related('product')
|
||||
.prefetch_related('attachments').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')}
|
||||
fibre_values = [entry.fibre_g for entry in entries if entry.fibre_g is not None]
|
||||
fibre_incomplete = len(fibre_values) != len(entries)
|
||||
totals['fibre_g'] = sum(fibre_values, ZERO) if fibre_values or not entries else None
|
||||
meals = []
|
||||
for key, label in MealType.choices:
|
||||
items = [entry for entry in entries if entry.meal == key]
|
||||
@@ -35,16 +39,22 @@ def diary_context(user, day):
|
||||
'calories': sum((entry.calories_kcal or ZERO for entry in items), ZERO)})
|
||||
macros = []
|
||||
for label, name, goal, color in (
|
||||
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
|
||||
('Protein', 'protein_g', goals.protein_goal_g, 'blue'),
|
||||
('Carbohydrates', 'carbohydrates_g', goals.carbohydrate_goal_g, 'pink'),
|
||||
('Fat', 'fat_g', goals.fat_goal_g, 'orange'),
|
||||
('Fibre', 'fibre_g', goals.fibre_goal_g, 'green'),
|
||||
):
|
||||
eaten = totals[name]
|
||||
macros.append({'label': label, 'eaten': eaten, 'goal': goal, 'remaining': goal - eaten if goal is not None else None,
|
||||
'percent': min(100, int(eaten * 100 / goal)) if goal else None, 'color': color})
|
||||
incomplete = name == 'fibre_g' and fibre_incomplete
|
||||
macros.append({'label': label, 'slug': name, 'guidance': nutrient_guidance(name, language),
|
||||
'eaten': eaten, 'goal': goal,
|
||||
'remaining': goal - eaten if goal is not None and eaten is not None and not incomplete else None,
|
||||
'percent': min(100, int(eaten * 100 / goal)) if goal and eaten is not None else None,
|
||||
'color': color, 'incomplete': incomplete})
|
||||
calorie_goal = goals.daily_calorie_goal
|
||||
calories = totals['calories_kcal']
|
||||
return {'day': day, 'previous_day': day - timedelta(days=1), 'next_day': day + timedelta(days=1),
|
||||
'meals': meals, 'totals': totals, 'macros': macros, 'calorie_goal': calorie_goal,
|
||||
'meals': meals, 'totals': totals, 'macros': macros, 'help_language': language,
|
||||
'calorie_goal': calorie_goal,
|
||||
'calorie_remaining': Decimal(calorie_goal) - calories if calorie_goal is not None else None,
|
||||
'calorie_percent': min(100, int(calories * 100 / calorie_goal)) if calorie_goal else 0}
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Static, bilingual guidance for the food diary nutrient cards."""
|
||||
|
||||
GUIDANCE = {
|
||||
'protein_g': {
|
||||
'en': ('Helps build and maintain muscles and supports recovery.', [
|
||||
('Poultry', 'chicken breast, turkey'), ('Fish', 'tuna, salmon, cod'),
|
||||
('Eggs', ''), ('Dairy', 'skyr, quark (kwark), cottage cheese'),
|
||||
('Legumes', 'lentils, chickpeas, beans'),
|
||||
('Plant proteins', 'tofu, tempeh, edamame')], ''),
|
||||
'nl': ('Helpt spieren opbouwen en behouden en ondersteunt herstel.', [
|
||||
('Gevogelte', 'kipfilet, kalkoen'), ('Vis', 'tonijn, zalm, kabeljauw'),
|
||||
('Eieren', ''), ('Zuivel', 'skyr, kwark, hüttenkäse'),
|
||||
('Peulvruchten', 'linzen, kikkererwten, bonen'),
|
||||
('Plantaardige eiwitten', 'tofu, tempeh, edamame')], ''),
|
||||
},
|
||||
'carbohydrates_g': {
|
||||
'en': ('Provide energy for your brain, muscles and everyday activity.', [
|
||||
('Whole grains', 'oats, wholemeal bread, brown rice'),
|
||||
('Starchy foods', 'potatoes, pasta, rice'),
|
||||
('Fruit', 'bananas, apples, berries'),
|
||||
('Legumes', 'beans, lentils, chickpeas'),
|
||||
('Vegetables', 'sweetcorn, peas')],
|
||||
'Whole grains and fibre-rich carbohydrate sources are generally preferable to highly refined options.'),
|
||||
'nl': ('Geven energie voor je hersenen, spieren en dagelijkse activiteiten.', [
|
||||
('Volkoren granen', 'havermout, volkorenbrood, zilvervliesrijst'),
|
||||
('Zetmeelrijke producten', 'aardappelen, pasta, rijst'),
|
||||
('Fruit', 'bananen, appels, bessen'),
|
||||
('Peulvruchten', 'bonen, linzen, kikkererwten'),
|
||||
('Groenten', 'suikermaïs, erwten')],
|
||||
'Volkoren en vezelrijke koolhydraatbronnen hebben doorgaans de voorkeur boven sterk geraffineerde producten.'),
|
||||
},
|
||||
'fat_g': {
|
||||
'en': ('Supports hormone production, cell function and absorption of certain vitamins.', [
|
||||
('Nuts', 'walnuts, almonds, cashews'),
|
||||
('Seeds', 'chia, flaxseed, sunflower seeds'),
|
||||
('Oils', 'olive oil, rapeseed oil'), ('Avocado', ''),
|
||||
('Oily fish', 'salmon, mackerel, sardines'),
|
||||
('Dairy and butter', 'cheese, cream, butter')],
|
||||
'Unsaturated fats are generally preferable to saturated fats.'),
|
||||
'nl': ('Ondersteunt de hormoonproductie, celfunctie en opname van bepaalde vitamines.', [
|
||||
('Noten', 'walnoten, amandelen, cashewnoten'),
|
||||
('Zaden', 'chiazaad, lijnzaad, zonnebloempitten'),
|
||||
('Oliën', 'olijfolie, koolzaadolie'), ('Avocado', ''),
|
||||
('Vette vis', 'zalm, makreel, sardines'),
|
||||
('Zuivel en boter', 'kaas, room, boter')],
|
||||
'Onverzadigde vetten hebben doorgaans de voorkeur boven verzadigde vetten.'),
|
||||
},
|
||||
'fibre_g': {
|
||||
'en': ('Supports digestion, gut health and feelings of fullness.', [
|
||||
('Legumes', 'lentils, kidney beans, chickpeas'),
|
||||
('Whole grains', 'oats, wholemeal bread, barley'),
|
||||
('Seeds', 'chia seeds, flaxseed'),
|
||||
('Fruit', 'raspberries, pears, apples with skin'),
|
||||
('Vegetables', 'broccoli, carrots, Brussels sprouts'),
|
||||
('Nuts', 'almonds, pistachios')],
|
||||
'Increase fibre gradually and drink enough fluids.'),
|
||||
'nl': ('Ondersteunt de spijsvertering, darmgezondheid en een vol gevoel.', [
|
||||
('Peulvruchten', 'linzen, kidneybonen, kikkererwten'),
|
||||
('Volkoren granen', 'havermout, volkorenbrood, gerst'),
|
||||
('Zaden', 'chiazaad, lijnzaad'),
|
||||
('Fruit', 'frambozen, peren, appels met schil'),
|
||||
('Groenten', 'broccoli, wortels, spruitjes'),
|
||||
('Noten', 'amandelen, pistachenoten')],
|
||||
'Verhoog je vezelinname geleidelijk en drink voldoende.'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def nutrient_guidance(slug, language):
|
||||
explanation, sources, tip = GUIDANCE[slug]['nl' if language.startswith('nl') else 'en']
|
||||
titles = {'protein_g': 'Eiwitten', 'carbohydrates_g': 'Koolhydraten',
|
||||
'fat_g': 'Vetten', 'fibre_g': 'Vezels'}
|
||||
return {'title': titles[slug] if language.startswith('nl') else {
|
||||
'protein_g': 'Protein', 'carbohydrates_g': 'Carbohydrates',
|
||||
'fat_g': 'Fat', 'fibre_g': 'Fibre'}[slug],
|
||||
'explanation': explanation, 'sources': sources, 'tip': tip}
|
||||
@@ -68,6 +68,15 @@ def map_product(data):
|
||||
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 ''
|
||||
package_text = str(data.get('quantity') or '')[:100]
|
||||
package_match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', package_text, re.IGNORECASE)
|
||||
package_amount = _decimal(package_match.group(1).replace(',', '.')) if package_match else None
|
||||
package_unit = package_match.group(2).lower() if package_match else ''
|
||||
if package_amount is not None and package_unit in ('kg', 'l'):
|
||||
package_amount *= 1000
|
||||
package_unit = 'g' if package_unit == 'kg' else 'ml'
|
||||
if package_amount is not None and package_amount <= 0:
|
||||
package_amount = None
|
||||
image_url = str(data.get('image_front_small_url') or data.get('image_front_url') or '')
|
||||
try:
|
||||
parsed_image = urlparse(image_url)
|
||||
@@ -78,7 +87,9 @@ def map_product(data):
|
||||
image_url = ''
|
||||
return {'barcode': code[:64], 'product_name': name[:255], 'brand': str(data.get('brands') or '')[:255],
|
||||
'image_url': image_url[:200],
|
||||
'package_quantity': str(data.get('quantity') or '')[:100], 'serving_size_text': serving_text,
|
||||
'package_quantity': package_text, 'package_amount': package_amount,
|
||||
'package_unit': package_unit if package_amount is not None else '',
|
||||
'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}
|
||||
|
||||
@@ -148,7 +159,7 @@ def cached_product(user, barcode, *, refresh=False):
|
||||
return product
|
||||
raise
|
||||
mapped = map_product(data)
|
||||
if not mapped:
|
||||
if not mapped or mapped['barcode'] != barcode:
|
||||
return product
|
||||
mapped['source'] = FoodProduct.Source.OPEN_FOOD_FACTS
|
||||
mapped['fetched_at'] = timezone.now()
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""Owner-scoped product matching and creation shared by the HTTP API."""
|
||||
import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db import transaction
|
||||
from django.db.models import Q
|
||||
|
||||
from food.models import FoodProduct, Unit
|
||||
from food.services.openfoodfacts import cached_product, cached_search
|
||||
|
||||
NUTRITION_FIELDS = {
|
||||
'calories_kcal': 'energy_kcal_100', 'carbohydrates_g': 'carbohydrates_100',
|
||||
'protein_g': 'protein_100', 'fat_g': 'fat_100', 'saturated_fat_g': 'saturated_fat_100',
|
||||
'sugars_g': 'sugars_100', 'fibre_g': 'fibre_100', 'salt_g': 'salt_100',
|
||||
}
|
||||
|
||||
|
||||
def _name(value, field, limit, required=False):
|
||||
if not isinstance(value, str):
|
||||
raise ValueError(f'{field} must be text.')
|
||||
cleaned = ' '.join(value.split())
|
||||
if len(cleaned) > limit or (required and not cleaned):
|
||||
raise ValueError(f'Invalid {field}.')
|
||||
return cleaned
|
||||
|
||||
|
||||
def _amount(value, field, positive=True):
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(f'Invalid {field}.')
|
||||
try:
|
||||
amount = Decimal(str(value))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
raise ValueError(f'Invalid {field}.') from None
|
||||
if not amount.is_finite() or amount < 0 or (positive and amount == 0) or amount > Decimal('9999999.999'):
|
||||
raise ValueError(f'Invalid {field}.')
|
||||
return amount
|
||||
|
||||
|
||||
def package_size(product):
|
||||
if product.package_amount is not None:
|
||||
return product.package_amount, product.package_unit
|
||||
match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(g|ml)\s*', product.package_quantity, re.IGNORECASE)
|
||||
if match:
|
||||
return Decimal(match.group(1).replace(',', '.')), match.group(2).lower()
|
||||
return None, ''
|
||||
|
||||
|
||||
def match_data(product, confidence, source=None):
|
||||
amount, unit = package_size(product)
|
||||
return {'product_id': str(product.api_id), 'source': source or product.source,
|
||||
'external_id': product.barcode if product.source == FoodProduct.Source.OPEN_FOOD_FACTS else None,
|
||||
'name': product.product_name, 'brand': product.brand, 'barcode': product.barcode or None,
|
||||
'package_quantity': str(amount) if amount is not None else None, 'package_unit': unit or None,
|
||||
'nutrition_per_100': {field: str(getattr(product, model_field)) if getattr(product, model_field) is not None else None
|
||||
for field, model_field in NUTRITION_FIELDS.items()}, 'confidence': confidence}
|
||||
|
||||
|
||||
def _same_package(product, amount, unit):
|
||||
existing_amount, existing_unit = package_size(product)
|
||||
return amount is None or (existing_amount == amount and existing_unit == unit)
|
||||
|
||||
|
||||
def local_matches(user, name='', brand='', barcode='', amount=None, unit='', limit=10, include_partial=False):
|
||||
qs = FoodProduct.objects.filter(owner=user)
|
||||
if barcode:
|
||||
exact = qs.filter(barcode=barcode).first()
|
||||
if exact:
|
||||
return [match_data(exact, 'exact_barcode')]
|
||||
if not name:
|
||||
return []
|
||||
if include_partial:
|
||||
for token in name.split():
|
||||
qs = qs.filter(Q(product_name__icontains=token) | Q(brand__icontains=token))
|
||||
else:
|
||||
qs = qs.filter(product_name__iexact=name)
|
||||
candidates = list(qs.order_by('pk')[:100])
|
||||
if brand:
|
||||
candidates = [p for p in candidates if p.brand.casefold() == brand.casefold()]
|
||||
if amount is not None and not include_partial:
|
||||
candidates = [p for p in candidates if _same_package(p, amount, unit)]
|
||||
candidates.sort(key=lambda p: (p.product_name.casefold() != name.casefold(),
|
||||
p.brand.casefold() != brand.casefold() if brand else False,
|
||||
not _same_package(p, amount, unit), p.pk))
|
||||
return [match_data(p, 'exact_details' if p.product_name.casefold() == name.casefold() and
|
||||
brand and p.brand.casefold() == brand.casefold() and amount is not None and
|
||||
_same_package(p, amount, unit) else 'candidate') for p in candidates[:limit]]
|
||||
|
||||
|
||||
def external_matches(user, query='', barcode='', brand='', amount=None, unit='', limit=10):
|
||||
if barcode:
|
||||
# A lookup must never mutate the product catalogue. Search results are read-only.
|
||||
from food.services.openfoodfacts import OpenFoodFactsClient, _rate_limit, map_product
|
||||
_rate_limit(user.pk, 'product', 10)
|
||||
raw = OpenFoodFactsClient().get_product(barcode)
|
||||
products = [map_product(raw)] if raw else []
|
||||
else:
|
||||
products = cached_search(user, query)[:20]
|
||||
matches = []
|
||||
for product in products:
|
||||
if not product:
|
||||
continue
|
||||
if barcode and product['barcode'] != barcode:
|
||||
continue
|
||||
package_amount = product.get('package_amount')
|
||||
package_unit = product.get('package_unit') or None
|
||||
exact = bool(barcode and product['barcode'] == barcode)
|
||||
details = bool(query and brand and amount is not None and
|
||||
product['product_name'].casefold() == query.casefold() and
|
||||
product['brand'].casefold() == brand.casefold() and
|
||||
package_amount == amount and package_unit == unit)
|
||||
matches.append({'product_id': None, 'source': 'open_food_facts', 'external_id': product['barcode'],
|
||||
'name': product['product_name'], 'brand': product['brand'], 'barcode': product['barcode'],
|
||||
'package_quantity': str(package_amount) if package_amount is not None else None,
|
||||
'package_unit': package_unit,
|
||||
'nutrition_per_100': {field: str(product[model_field]) if product.get(model_field) is not None else None
|
||||
for field, model_field in NUTRITION_FIELDS.items()},
|
||||
'confidence': 'exact_barcode' if exact else 'exact_details' if details else 'candidate'})
|
||||
matches.sort(key=lambda item: (
|
||||
0 if item['confidence'] == 'exact_barcode' else 1 if item['confidence'] == 'exact_details' else 2,
|
||||
item['name'].casefold() != query.casefold() if query else False,
|
||||
item['brand'].casefold() != brand.casefold() if brand else False,
|
||||
Decimal(item['package_quantity']) != amount if amount is not None and item['package_quantity'] else bool(amount)))
|
||||
return matches[:limit]
|
||||
|
||||
|
||||
def create_manual(user, data):
|
||||
allowed = {'name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100', 'source'}
|
||||
if set(data) - allowed or data.get('source', 'manual') != 'manual':
|
||||
raise ValueError('Invalid manual product fields.')
|
||||
name = _name(data.get('name'), 'name', 255, True)
|
||||
brand = _name(data.get('brand', ''), 'brand', 255)
|
||||
barcode = _name(data.get('barcode') or '', 'barcode', 64)
|
||||
if barcode and not re.fullmatch(r'[0-9]{1,64}', barcode):
|
||||
raise ValueError('Barcode must be numeric.')
|
||||
amount = data.get('package_quantity')
|
||||
unit = data.get('package_unit') or ''
|
||||
if (amount is None) != (not unit) or (unit and unit not in Unit.values):
|
||||
raise ValueError('Package quantity and unit must be supplied together.')
|
||||
amount = _amount(amount, 'package_quantity') if amount is not None else None
|
||||
nutrition = data.get('nutrition_per_100') or {}
|
||||
if not isinstance(nutrition, dict) or set(nutrition) - NUTRITION_FIELDS.keys():
|
||||
raise ValueError('Invalid nutrition fields.')
|
||||
nutrients = {model_field: _amount(value, field, False) if value is not None else None
|
||||
for field, model_field in NUTRITION_FIELDS.items() for value in [nutrition.get(field)]}
|
||||
with transaction.atomic():
|
||||
# Serialize concurrent creates for one owner, including products without barcodes.
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
if barcode:
|
||||
existing = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
|
||||
if existing:
|
||||
return existing, 'reused', []
|
||||
exact = local_matches(user, name, brand, '', amount, unit, 20)
|
||||
if exact:
|
||||
if len(exact) == 1 and not barcode and (amount is not None or not exact[0]['package_quantity']):
|
||||
return FoodProduct.objects.get(api_id=exact[0]['product_id']), 'reused', []
|
||||
return None, 'needs_review', exact
|
||||
product = FoodProduct(owner=user, product_name=name, brand=brand, barcode=barcode,
|
||||
package_quantity=f'{amount:g} {unit}' if amount is not None else '',
|
||||
package_amount=amount, package_unit=unit, base_unit=unit or Unit.GRAM,
|
||||
source=FoodProduct.Source.MANUAL, **nutrients)
|
||||
product.full_clean()
|
||||
product.save()
|
||||
return product, 'created', []
|
||||
|
||||
|
||||
def import_off(user, barcode):
|
||||
if not isinstance(barcode, str) or not re.fullmatch(r'[0-9]{1,64}', barcode):
|
||||
raise ValueError('Enter a numeric Open Food Facts barcode.')
|
||||
product = cached_product(user, barcode)
|
||||
return product
|
||||
@@ -26,12 +26,38 @@ body[data-theme="dark"]{--food-surface:#202923;--food-border:#3b473f;--food-ink:
|
||||
.food-macro p,.food-product-list small{color:var(--food-muted)}
|
||||
body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
|
||||
|
||||
/* Keep the three macro summaries on one compact row on phones. */
|
||||
/* Four goals fit the existing nutrition sidebar in a compact two-column grid. */
|
||||
.food-macros{grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}
|
||||
.food-macro{display:flex;flex-direction:column;align-items:center;gap:.25rem;min-width:0;margin:0;padding:.7rem .3rem;text-align:center}
|
||||
.food-ring{width:54px;height:54px;margin:0}
|
||||
.food-ring span{width:42px;height:42px;font-size:.75rem}
|
||||
.food-macro h3{font-size:.82rem;line-height:1.15;margin:0;white-space:nowrap}
|
||||
.food-macro p{font-size:.72rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere}
|
||||
.food-macro--green{--accent:var(--food-green)}
|
||||
|
||||
/* Keep the four nutrition goals readable on phones. */
|
||||
@media(max-width:760px){
|
||||
.food-macros{grid-template-columns:repeat(3,minmax(0,1fr));gap:.4rem}
|
||||
.food-macro{display:flex;flex-direction:column;align-items:center;gap:.35rem;min-width:0;padding:.55rem .25rem;text-align:center}
|
||||
.food-ring{width:48px;height:48px;margin:0}
|
||||
.food-ring span{width:38px;height:38px;font-size:.7rem}
|
||||
.food-macro h3{font-size:.8rem;line-height:1.15;margin:0;overflow-wrap:anywhere}
|
||||
.food-macro p{font-size:.7rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere}
|
||||
.food-macros{grid-template-columns:repeat(2,minmax(0,1fr));gap:.45rem}
|
||||
.food-macro{display:flex;flex-direction:column;align-items:center;gap:.25rem;min-width:0;padding:.7rem .3rem;text-align:center}
|
||||
.food-ring{width:54px;height:54px;margin:0}
|
||||
.food-ring span{width:42px;height:42px;font-size:.75rem}
|
||||
.food-macro h3{font-size:.82rem;line-height:1.15;margin:0;white-space:nowrap}
|
||||
.food-macro p{font-size:.72rem;line-height:1.2;margin:.1rem 0;overflow-wrap:anywhere}
|
||||
}
|
||||
|
||||
/* Nutrient guidance sits above the card content and stays within the viewport. */
|
||||
.food-macro{position:relative;padding-top:2.8rem}
|
||||
.food-help-trigger{position:absolute;top:.25rem;right:.25rem;display:grid;place-items:center;width:44px;height:44px;padding:0;border:0;background:transparent;color:var(--food-ink);cursor:pointer}
|
||||
.food-help-trigger span{display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--food-muted);border-radius:50%;font:700 .85rem/1 inherit}
|
||||
.food-help-trigger:hover span,.food-help-trigger[aria-expanded="true"] span{background:var(--food-progress-track)}
|
||||
.food-help-trigger:focus-visible,.food-help-close:focus-visible{outline:2px solid var(--food-green);outline-offset:2px;border-radius:.4rem}
|
||||
.food-help-popover{position:fixed;z-index:100;width:min(320px,calc(100vw - 24px));max-height:calc(100dvh - 24px);overflow:auto;padding:1rem;text-align:left;background:var(--food-surface);color:var(--food-ink);border:1px solid var(--food-border);border-radius:1rem;box-shadow:0 12px 32px #0008;font-size:.9rem;line-height:1.4}
|
||||
.food-help-popover[hidden]{display:none}
|
||||
.food-help-heading{display:flex;align-items:center;justify-content:space-between;gap:1rem}
|
||||
.food-help-heading h4{margin:0;font-size:1.05rem}
|
||||
.food-help-close{display:grid;place-items:center;flex:none;width:44px;height:44px;padding:0;border:0;background:transparent;color:var(--food-ink);font-size:1.5rem;cursor:pointer}
|
||||
.food-help-popover p{margin:.45rem 0 .75rem;color:var(--food-ink)}
|
||||
.food-help-popover ul{margin:.4rem 0;padding-left:1.25rem}
|
||||
.food-help-popover li{margin:.25rem 0}
|
||||
.food-help-popover .food-help-tip{margin-top:.75rem;color:var(--food-muted)}
|
||||
@media(max-width:600px){.food-help-popover{top:auto!important;left:12px!important;right:12px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;max-height:min(70dvh,560px)}}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
(() => {
|
||||
let active = null;
|
||||
|
||||
function close(restoreFocus = false) {
|
||||
if (!active) return;
|
||||
const { trigger, popover } = active;
|
||||
popover.hidden = true;
|
||||
trigger.setAttribute('aria-expanded', 'false');
|
||||
active = null;
|
||||
if (restoreFocus && trigger.isConnected) trigger.focus();
|
||||
}
|
||||
|
||||
function position(trigger, popover) {
|
||||
if (window.matchMedia('(max-width: 600px)').matches) {
|
||||
popover.style.left = '';
|
||||
popover.style.top = '';
|
||||
return;
|
||||
}
|
||||
const rect = trigger.getBoundingClientRect();
|
||||
const width = popover.getBoundingClientRect().width;
|
||||
const left = Math.max(12, Math.min(rect.right - width, window.innerWidth - width - 12));
|
||||
const below = rect.bottom + 8;
|
||||
const height = popover.getBoundingClientRect().height;
|
||||
const top = below + height <= window.innerHeight - 12
|
||||
? below : Math.max(12, rect.top - height - 8);
|
||||
popover.style.left = `${left}px`;
|
||||
popover.style.top = `${top}px`;
|
||||
}
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
const trigger = event.target.closest('[data-food-help-trigger]');
|
||||
if (trigger) {
|
||||
if (active?.trigger === trigger) { close(); return; }
|
||||
close();
|
||||
const popover = document.getElementById(trigger.getAttribute('aria-controls'));
|
||||
if (!popover) return;
|
||||
popover.hidden = false;
|
||||
trigger.setAttribute('aria-expanded', 'true');
|
||||
active = { trigger, popover };
|
||||
position(trigger, popover);
|
||||
popover.querySelector('[data-food-help-close]').focus();
|
||||
return;
|
||||
}
|
||||
if (event.target.closest('[data-food-help-close]')) { close(true); return; }
|
||||
if (active && !active.popover.contains(event.target)) close();
|
||||
});
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key === 'Escape' && active) { event.preventDefault(); close(true); }
|
||||
});
|
||||
window.addEventListener('resize', () => {
|
||||
if (active) position(active.trigger, active.popover);
|
||||
});
|
||||
document.addEventListener('htmx:beforeSwap', () => close());
|
||||
})();
|
||||
@@ -2,6 +2,7 @@
|
||||
{% load static %}
|
||||
{% block title %}Food · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}">
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261011-help">
|
||||
{% include 'food/partials/diary_content.html' %}
|
||||
<script defer src="{% static 'food/nutrient_help.js' %}?v=20261011-help"></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -23,7 +23,17 @@
|
||||
</div>
|
||||
<aside class="food-sidebar" aria-label="Daily nutrition summary">
|
||||
<section class="food-card" id="food-summary"><h2>Calories</h2>{% if calorie_goal is not None %}<p class="food-remaining">{% if calorie_remaining < 0 %}{{ calorie_remaining|floatformat:0|cut:'-' }} kcal over goal{% else %}{{ calorie_remaining|floatformat:0 }} kcal remaining{% endif %}</p><div class="food-progress" role="progressbar" aria-label="Calories eaten" aria-valuenow="{{ totals.calories_kcal|floatformat:0 }}" aria-valuemin="0" aria-valuemax="{{ calorie_goal }}"><span style="width:{{ calorie_percent }}%"></span></div><p>{{ totals.calories_kcal|floatformat:0 }} kcal eaten · Goal: {{ calorie_goal }} kcal</p>{% else %}<p class="food-remaining">{{ totals.calories_kcal|floatformat:0 }} kcal eaten</p><p>No calorie goal. <a href="{% url 'planner:user-settings' %}">Set one in Settings</a>.</p>{% endif %}</section>
|
||||
<section class="food-macros" id="food-macro-summary" aria-label="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-macros" id="food-macro-summary" aria-label="Daily nutrition goals">{% for macro in macros %}<article class="food-card food-macro food-macro--{{ macro.color }}" aria-labelledby="food-goal-{{ macro.slug }}">
|
||||
<button class="food-help-trigger" type="button" aria-label="{% if help_language|slice:':2' == 'nl' %}Hulp bij {{ macro.guidance.title }}{% else %}About {{ macro.guidance.title }}{% endif %}" aria-expanded="false" aria-controls="food-help-{{ macro.slug }}" data-food-help-trigger><span aria-hidden="true">?</span></button>
|
||||
<div class="food-ring" {% if macro.percent is not None %}style="--progress:{{ macro.percent }}%" role="progressbar" aria-label="{{ macro.label }} progress" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ macro.percent }}" aria-valuetext="{% if macro.incomplete %}At least {% endif %}{{ macro.eaten|floatformat:1 }} g of {{ macro.goal|floatformat:1 }} g{% if macro.incomplete %}; some food entries have unknown fibre{% endif %}"{% else %}aria-label="{{ macro.label }} progress unknown"{% endif %}><span aria-hidden="true">{% if macro.percent is not None %}{{ macro.percent }}%{% else %}—{% endif %}</span></div>
|
||||
<div><h3 id="food-goal-{{ macro.slug }}">{{ macro.label }}</h3><p>{% if macro.eaten is None %}Unknown{% elif macro.incomplete %}At least {{ macro.eaten|floatformat:1 }} g{% else %}{{ macro.eaten|floatformat:1 }} g eaten{% endif %}{% if macro.goal is not None %} · {{ macro.goal|floatformat:1 }} g goal{% endif %}</p>{% if macro.incomplete %}<p>Some entries unknown</p>{% elif macro.goal is not None %}<p>{% if macro.remaining < 0 %}{{ macro.remaining|floatformat:1|cut:'-' }} g over target{% else %}{{ macro.remaining|floatformat:1 }} g remaining{% endif %}</p>{% else %}<p>No target</p>{% endif %}</div>
|
||||
<div class="food-help-popover" id="food-help-{{ macro.slug }}" role="region" aria-labelledby="food-help-title-{{ macro.slug }}" hidden>
|
||||
<div class="food-help-heading"><h4 id="food-help-title-{{ macro.slug }}">{{ macro.guidance.title }}</h4><button type="button" class="food-help-close" data-food-help-close aria-label="{% if help_language|slice:':2' == 'nl' %}Sluiten{% else %}Close{% endif %}">×</button></div>
|
||||
<p>{{ macro.guidance.explanation }}</p><strong>{% if help_language|slice:':2' == 'nl' %}Goede bronnen:{% else %}Good sources:{% endif %}</strong>
|
||||
<ul>{% for group, foods in macro.guidance.sources %}<li><strong>{{ group }}</strong>{% if foods %}: {{ foods }}{% endif %}</li>{% endfor %}</ul>
|
||||
{% if macro.guidance.tip %}<p class="food-help-tip">{{ macro.guidance.tip }}</p>{% endif %}
|
||||
</div>
|
||||
</article>{% endfor %}</section>
|
||||
<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>
|
||||
|
||||
@@ -20,15 +20,15 @@
|
||||
</form>
|
||||
</section>
|
||||
<section class="settings-card">
|
||||
<h2>Your tokens</h2>
|
||||
<h2>Active tokens</h2>
|
||||
{% for token in tokens %}
|
||||
<div>
|
||||
<h3>{{ token.name }}</h3>
|
||||
<p>Permissions: {{ token.scopes|join:", " }} · Created: {{ token.created_at|date:"SHORT_DATETIME_FORMAT" }} · Last used: {{ token.last_used_at|date:"SHORT_DATETIME_FORMAT"|default:"Never" }}</p>
|
||||
<p>Status: {% if token.revoked_at %}Revoked{% elif token.expires_at and token.expires_at <= now %}Expired{% else %}Active{% endif %}{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}</p>
|
||||
{% if not token.revoked_at %}<form method="post" action="{% url 'food:token-revoke' token.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">Revoke {{ token.name }}</button></form>{% endif %}
|
||||
<p>Status: Active{% if token.expires_at %} · Expires: {{ token.expires_at|date:"SHORT_DATETIME_FORMAT" }}{% endif %}</p>
|
||||
<form method="post" action="{% url 'food:token-revoke' token.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">Revoke {{ token.name }}</button></form>
|
||||
</div>
|
||||
{% empty %}<p>No API tokens yet.</p>{% endfor %}
|
||||
{% empty %}<p>No active API tokens.</p>{% endfor %}
|
||||
</section>
|
||||
<section class="settings-card mcp-helper" data-mcp-helper>
|
||||
<h2>Connect an AI assistant</h2>
|
||||
|
||||
+156
-2
@@ -1,6 +1,7 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime, timedelta, timezone as py_timezone
|
||||
from decimal import Decimal
|
||||
from unittest.mock import patch
|
||||
@@ -8,12 +9,14 @@ from unittest.mock import patch
|
||||
from PIL import Image
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from django.test import TestCase, override_settings
|
||||
from django.test import Client, TestCase, TransactionTestCase, override_settings
|
||||
from django.db import connection
|
||||
from django.utils import timezone
|
||||
|
||||
from planner.models import UserSettings
|
||||
from .api import create_token
|
||||
from .models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem, PersonalAccessToken
|
||||
from .services.openfoodfacts import OpenFoodFactsError
|
||||
|
||||
|
||||
class FoodApiTests(TestCase):
|
||||
@@ -105,6 +108,118 @@ class FoodApiTests(TestCase):
|
||||
with patch('planner.timezones.timezone.now', return_value=datetime(2026, 1, 1, 1, tzinfo=py_timezone.utc)):
|
||||
self.assertEqual(self.call('get', '/api/v1/food/today/').json()['date'], '2025-12-31')
|
||||
|
||||
def test_product_lookup_create_and_duplicate_protection(self):
|
||||
local = self.call('get', '/api/v1/food/products/lookup/?barcode=123456&include_open_food_facts=false')
|
||||
self.assertEqual(local.json()['matches'], [])
|
||||
payload = {'name': 'Oat milk', 'brand': 'Example', 'barcode': '123456',
|
||||
'package_quantity': '1000', 'package_unit': 'ml'}
|
||||
first = self.call('post', '/api/v1/food/products/create/', payload, HTTP_IDEMPOTENCY_KEY='new-oats')
|
||||
self.assertEqual(first.status_code, 201, first.content)
|
||||
self.assertEqual(first.json()['product']['package_amount'], '1000')
|
||||
self.assertIsNone(first.json()['product']['energy_kcal_100'])
|
||||
match = self.call('get', '/api/v1/food/products/lookup/?barcode=123456')
|
||||
self.assertEqual(match.json()['matches'][0]['confidence'], 'exact_barcode')
|
||||
self.assertEqual(match.json()['matches'][0]['product_id'], first.json()['product_id'])
|
||||
by_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false')
|
||||
self.assertEqual(by_name.json()['matches'][0]['product_id'], first.json()['product_id'])
|
||||
exact_name = self.call('get', '/api/v1/food/products/lookup/?query=Oat%20milk&brand=Example&package_quantity=1000&package_unit=ml&include_open_food_facts=false')
|
||||
self.assertEqual(exact_name.json()['matches'][0]['confidence'], 'exact_details')
|
||||
again = self.call('post', '/api/v1/food/products/create/', {**payload, 'name': 'Changed name'})
|
||||
self.assertEqual(again.json()['status'], 'reused')
|
||||
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2)
|
||||
self.assertEqual(FoodProduct.objects.get(owner=self.a, barcode='123456').product_name, 'Oat milk')
|
||||
conflict = self.call('post', '/api/v1/food/products/create/', {**payload, 'brand': 'Other'},
|
||||
HTTP_IDEMPOTENCY_KEY='new-oats')
|
||||
self.assertEqual(conflict.status_code, 409)
|
||||
self.assertEqual(self.call('post', '/api/v1/food/products/create/',
|
||||
{'name': 'Bad', 'package_quantity': '-1', 'package_unit': 'g'}).status_code, 400)
|
||||
self.assertEqual(self.call('post', '/api/v1/food/products/create/',
|
||||
{'name': 'Bad', 'nutrition_per_100': {'calories_kcal': '-1'}}).status_code, 400)
|
||||
|
||||
@patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product')
|
||||
def test_open_food_facts_lookup_and_import(self, get_product):
|
||||
sample = {'code': '87654321', 'product_name': 'Yoghurt', 'brands': 'Example',
|
||||
'quantity': '500 g', 'nutriments': {'energy-kcal_100g': 60}}
|
||||
get_product.return_value = sample
|
||||
lookup = self.call('get', '/api/v1/food/products/lookup/?barcode=87654321').json()
|
||||
self.assertEqual(lookup['matches'][0]['source'], 'open_food_facts')
|
||||
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 1)
|
||||
imported = self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'})
|
||||
self.assertEqual(imported.status_code, 201, imported.content)
|
||||
self.assertEqual(imported.json()['product']['package_amount'], '500.000')
|
||||
self.assertIsNone(imported.json()['product']['protein_100'])
|
||||
self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '87654321'}).json()['status'], 'reused')
|
||||
get_product.return_value = None
|
||||
self.assertEqual(self.call('post', '/api/v1/food/products/import/', {'barcode': '999999'}).status_code, 404)
|
||||
get_product.side_effect = OpenFoodFactsError('Open Food Facts is temporarily unavailable.')
|
||||
self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?barcode=999999').json()['external_error'],
|
||||
'Open Food Facts is temporarily unavailable.')
|
||||
|
||||
def test_batch_grocery_partial_success_and_idempotency(self):
|
||||
payload = {'create_missing_products': True, 'items': [
|
||||
{'name': 'Loose apples', 'quantity': 2, 'location': 'Fridge'},
|
||||
{'name': 'Broken', 'quantity': -1, 'location': 'Fridge'},
|
||||
]}
|
||||
first = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1')
|
||||
self.assertEqual(first.status_code, 200, first.content)
|
||||
self.assertEqual(first.json()['status'], 'partial_success')
|
||||
self.assertEqual([row['status'] for row in first.json()['items']], ['added', 'skipped'])
|
||||
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1)
|
||||
self.assertEqual(FoodProduct.objects.filter(owner=self.a).count(), 2)
|
||||
second = self.call('post', '/api/v1/kitchen/import-groceries/', payload, HTTP_IDEMPOTENCY_KEY='groceries-1')
|
||||
self.assertEqual(second.json(), first.json())
|
||||
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 1)
|
||||
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
|
||||
{**payload, 'items': [{'name': 'Pears', 'location': 'Fridge'}]},
|
||||
HTTP_IDEMPOTENCY_KEY='groceries-1').status_code, 409)
|
||||
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
|
||||
{'items': [{'product_id': str(self.product_b.api_id), 'location': 'Fridge'}]},
|
||||
HTTP_IDEMPOTENCY_KEY='other-user-product').json()['items'][0]['status'], 'skipped')
|
||||
|
||||
def test_ambiguous_product_requires_review_and_partial_contents_require_one_package(self):
|
||||
FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store A',
|
||||
package_quantity='500 g', package_amount=Decimal('500'), package_unit='g')
|
||||
FoodProduct.objects.create(owner=self.a, product_name='Yoghurt', brand='Store B',
|
||||
package_quantity='500 g', package_amount=Decimal('500'), package_unit='g')
|
||||
candidates = self.call('post', '/api/v1/food/products/create/', {'name': 'Yoghurt'})
|
||||
self.assertEqual(candidates.json()['status'], 'needs_review')
|
||||
self.assertEqual(len(candidates.json()['candidates']), 2)
|
||||
self.assertEqual(FoodProduct.objects.filter(owner=self.a, product_name='Yoghurt').count(), 2)
|
||||
product = FoodProduct.objects.filter(owner=self.a, brand='Store A').first()
|
||||
invalid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id),
|
||||
'quantity': 2, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'})
|
||||
self.assertEqual(invalid.status_code, 400)
|
||||
valid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id),
|
||||
'quantity': 1, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'})
|
||||
self.assertEqual(valid.status_code, 201, valid.content)
|
||||
self.assertEqual(valid.json()['remaining_amount'], '350')
|
||||
|
||||
def test_barcode_mismatch_does_not_reuse_similar_product(self):
|
||||
FoodProduct.objects.create(owner=self.a, product_name='Milk', brand='Example', barcode='11111',
|
||||
package_amount=Decimal('1000'), package_unit='ml', package_quantity='1000 ml')
|
||||
create = self.call('post', '/api/v1/food/products/create/', {'name': 'Milk', 'brand': 'Example',
|
||||
'barcode': '22222', 'package_quantity': '1000', 'package_unit': 'ml'})
|
||||
self.assertEqual(create.json()['status'], 'needs_review')
|
||||
with patch('food.services.openfoodfacts.OpenFoodFactsClient.get_product', return_value=None):
|
||||
response = self.call('post', '/api/v1/kitchen/import-groceries/', {'create_missing_products': True,
|
||||
'items': [{'name': 'Milk', 'brand': 'Example', 'barcode': '22222',
|
||||
'package_quantity': '1000', 'package_unit': 'ml', 'location': 'Fridge'}]},
|
||||
HTTP_IDEMPOTENCY_KEY='different-milk-barcode')
|
||||
self.assertEqual(response.json()['items'][0]['status'], 'needs_review')
|
||||
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a).count(), 0)
|
||||
|
||||
def test_new_tools_respect_scopes_and_owner_isolation(self):
|
||||
_, food_read = create_token(self.a, 'Food read', ['food:read'])
|
||||
self.assertEqual(self.call('get', '/api/v1/food/products/lookup/?query=Pasta&include_open_food_facts=false', token=food_read).status_code, 200)
|
||||
self.assertEqual(self.call('post', '/api/v1/food/products/create/', {'name': 'New'},
|
||||
token=food_read).status_code, 403)
|
||||
_, inventory_write = create_token(self.a, 'Inventory write', ['inventory:write'])
|
||||
self.assertEqual(self.call('post', '/api/v1/kitchen/import-groceries/',
|
||||
{'items': [{'name': 'New', 'location': 'Fridge'}], 'create_missing_products': True},
|
||||
token=inventory_write).status_code, 403)
|
||||
lookup = self.call('get', '/api/v1/food/products/lookup/?query=Private&include_open_food_facts=false')
|
||||
self.assertEqual(lookup.json()['matches'], [])
|
||||
|
||||
def test_food_diary_accepts_specific_date(self):
|
||||
entry = FoodLogEntry.objects.create(user=self.a, date=datetime(2026, 1, 2).date(), meal='breakfast',
|
||||
product_name_snapshot='Oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
|
||||
@@ -112,11 +227,24 @@ class FoodApiTests(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['date'], '2026-01-02')
|
||||
self.assertEqual(response.json()['meals']['breakfast'][0]['id'], str(entry.api_id))
|
||||
self.assertEqual(response.json()['totals']['calories_kcal'], '120')
|
||||
self.assertEqual(response.json()['totals']['calories_kcal'], '120.000')
|
||||
self.assertEqual(self.call('get', '/api/v1/food/today/?date=2026-01-03').json()['meals']['breakfast'], [])
|
||||
for invalid in ('', 'yesterday', '2026-02-30', '2026-1-2'):
|
||||
self.assertEqual(self.call('get', f'/api/v1/food/today/?date={invalid}').status_code, 400)
|
||||
|
||||
def test_fibre_api_totals_preserve_unknown_values(self):
|
||||
FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='breakfast',
|
||||
product_name_snapshot='Unknown fibre', amount=Decimal('100'), unit='g')
|
||||
response = self.call('get', '/api/v1/food/today/').json()
|
||||
self.assertEqual(response['goals']['fibre_goal_g'], '40.0')
|
||||
self.assertIsNone(response['totals']['fibre_g'])
|
||||
self.assertTrue(response['fibre_incomplete'])
|
||||
FoodLogEntry.objects.create(user=self.a, date=timezone.localdate(), meal='lunch',
|
||||
product_name_snapshot='Known fibre', amount=Decimal('100'), unit='g', fibre_g=Decimal('6.5'))
|
||||
response = self.call('get', '/api/v1/food/today/').json()
|
||||
self.assertEqual(response['totals']['fibre_g'], '6.500')
|
||||
self.assertTrue(response['fibre_incomplete'])
|
||||
|
||||
@override_settings(MEDIA_ROOT='/tmp/tasknest-api-test-media')
|
||||
def test_attachment_validation_and_isolation(self):
|
||||
entry = self.call('post', '/api/v1/food/log/', {'meal': 'lunch', 'amount': '1', 'unit': 'g',
|
||||
@@ -162,8 +290,34 @@ class FoodApiTests(TestCase):
|
||||
self.assertEqual(self.client.post(f'/food/settings/tokens/{created.pk}/revoke/').status_code, 302)
|
||||
created.refresh_from_db()
|
||||
self.assertIsNotNone(created.revoked_at)
|
||||
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Revoke Phone')
|
||||
self.assertTrue(PersonalAccessToken.objects.filter(pk=created.pk).exists())
|
||||
create_token(self.a, 'Expired token', ['food:read'], timezone.now() - timedelta(days=1))
|
||||
self.assertNotContains(self.client.get('/food/settings/tokens/'), 'Expired token')
|
||||
|
||||
def test_api_fallback_errors_are_json(self):
|
||||
response = self.call('get', '/api/v1/does-not-exist/')
|
||||
self.assertEqual(response.status_code, 404)
|
||||
self.assertEqual(response['Content-Type'], 'application/json')
|
||||
|
||||
|
||||
class ConcurrentProductCreationTests(TransactionTestCase):
|
||||
def test_concurrent_manual_creation_reuses_one_product(self):
|
||||
if connection.vendor == 'sqlite':
|
||||
self.skipTest('SQLite does not support select_for_update row locking.')
|
||||
user = get_user_model().objects.create_user('concurrent-products', password='test')
|
||||
_, secret = create_token(user, 'Product create', ['food:write'])
|
||||
payload = json.dumps({'name': 'Milk', 'brand': 'Example',
|
||||
'package_quantity': '1000', 'package_unit': 'ml'})
|
||||
|
||||
def create(_):
|
||||
client = Client()
|
||||
response = client.post('/api/v1/food/products/create/', data=payload,
|
||||
content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {secret}')
|
||||
return response.status_code, response.json()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(create, range(2)))
|
||||
self.assertEqual(sorted(status for status, _ in results), [200, 201])
|
||||
self.assertEqual(results[0][1]['product_id'], results[1][1]['product_id'])
|
||||
self.assertEqual(FoodProduct.objects.filter(owner=user).count(), 1)
|
||||
|
||||
@@ -69,6 +69,6 @@ class FoodExportTests(TestCase):
|
||||
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):
|
||||
with self.assertNumQueries(3):
|
||||
context = diary_context(self.user, date(2026, 10, 3))
|
||||
self.assertEqual(len(context['meals'][1]['entries']), 8)
|
||||
|
||||
@@ -32,9 +32,18 @@ class OpenFoodFactsTests(TestCase):
|
||||
self.assertEqual(mapped['serving_amount'], Decimal('300.000'))
|
||||
self.assertEqual(mapped['energy_kcal_100'], Decimal('58.000'))
|
||||
self.assertIsNone(mapped['fat_100'])
|
||||
self.assertIsNone(mapped['fibre_100'])
|
||||
unsafe = dict(SAMPLE, image_front_url='https://example.com/track.png')
|
||||
self.assertEqual(map_product(unsafe)['image_url'], '')
|
||||
|
||||
@patch.object(OpenFoodFactsClient, 'get_product')
|
||||
def test_fibre_survives_import_and_cached_barcode_lookup(self, get_product):
|
||||
get_product.return_value = {**SAMPLE, 'nutriments': {**SAMPLE['nutriments'], 'fiber_100g': 2.7}}
|
||||
product = cached_product(self.user, SAMPLE['code'])
|
||||
self.assertEqual(product.fibre_100, Decimal('2.700'))
|
||||
self.assertEqual(cached_product(self.user, SAMPLE['code']).fibre_100, Decimal('2.700'))
|
||||
get_product.assert_called_once()
|
||||
|
||||
@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'],
|
||||
|
||||
+59
-1
@@ -28,6 +28,64 @@ class FoodFoundationTests(TestCase):
|
||||
self.product.refresh_from_db()
|
||||
self.assertIsNone(self.product.energy_kcal_100)
|
||||
self.assertIsNone(self.product.protein_100)
|
||||
self.assertIsNone(self.product.fibre_100)
|
||||
|
||||
def test_default_and_custom_fibre_goal(self):
|
||||
from planner.forms import FoodGoalForm
|
||||
|
||||
self.client.force_login(self.user)
|
||||
profile = UserSettings.objects.create(user=self.user)
|
||||
self.assertEqual(profile.fibre_goal_g, Decimal('40'))
|
||||
response = self.client.get(reverse('planner:user-settings'))
|
||||
self.assertContains(response, 'Daily fibre goal (g)')
|
||||
response = self.client.post(reverse('planner:user-settings'), {'section': 'food',
|
||||
'daily_calorie_goal': '2000', 'carbohydrate_goal_g': '250', 'protein_goal_g': '100',
|
||||
'fat_goal_g': '70', 'fibre_goal_g': '35.5'})
|
||||
self.assertEqual(response.status_code, 302)
|
||||
profile.refresh_from_db()
|
||||
self.assertEqual(profile.fibre_goal_g, Decimal('35.5'))
|
||||
self.assertEqual(profile.protein_goal_g, Decimal('100'))
|
||||
self.assertContains(self.client.get(reverse('planner:user-settings')), 'value="35.5"')
|
||||
self.assertFalse(FoodGoalForm(data={'fibre_goal_g': '-1'}).is_valid())
|
||||
|
||||
def test_fibre_snapshots_scale_and_unknown_is_not_zero(self):
|
||||
from .services.logging import apply_product_snapshot
|
||||
|
||||
self.product.fibre_100 = Decimal('3.2')
|
||||
self.product.save(update_fields=['fibre_100'])
|
||||
entry = FoodLogEntry(user=self.user, date=date(2026, 10, 3), meal=MealType.BREAKFAST,
|
||||
amount=Decimal('250'), unit=Unit.GRAM)
|
||||
apply_product_snapshot(entry, self.product)
|
||||
self.assertEqual(entry.fibre_g, Decimal('8.000'))
|
||||
entry.full_clean()
|
||||
entry.save()
|
||||
self.product.fibre_100 = None
|
||||
self.product.save(update_fields=['fibre_100'])
|
||||
old = FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.LUNCH,
|
||||
product_name_snapshot='Legacy food', amount=Decimal('100'), unit=Unit.GRAM)
|
||||
context = diary_context(self.user, date(2026, 10, 3))
|
||||
self.assertIsNone(old.fibre_g)
|
||||
self.assertEqual(context['totals']['fibre_g'], Decimal('8.000'))
|
||||
fibre = context['macros'][3]
|
||||
self.assertTrue(fibre['incomplete'])
|
||||
self.assertEqual(fibre['percent'], 20)
|
||||
self.assertIsNone(fibre['remaining'])
|
||||
self.assertEqual(FoodLogEntry.objects.get(pk=entry.pk).fibre_g, Decimal('8.000'))
|
||||
|
||||
def test_fibre_totals_and_over_goal(self):
|
||||
UserSettings.objects.create(user=self.user, fibre_goal_g=Decimal('40'))
|
||||
for value in ('25', '20'):
|
||||
FoodLogEntry.objects.create(user=self.user, date=date(2026, 10, 3), meal=MealType.SNACKS,
|
||||
product_name_snapshot='Known fibre', amount=Decimal('100'), unit=Unit.GRAM,
|
||||
fibre_g=Decimal(value))
|
||||
context = diary_context(self.user, date(2026, 10, 3))
|
||||
self.assertEqual(context['totals']['fibre_g'], Decimal('45'))
|
||||
fibre = context['macros'][3]
|
||||
self.assertEqual(fibre['percent'], 100)
|
||||
self.assertEqual(fibre['remaining'], Decimal('-5'))
|
||||
self.assertFalse(fibre['incomplete'])
|
||||
self.client.force_login(self.user)
|
||||
self.assertContains(self.client.get(reverse('food:diary'), {'date': '2026-10-03'}), '5.0 g over target')
|
||||
|
||||
def test_favourite_and_portion_uniqueness(self):
|
||||
FoodFavourite.objects.create(user=self.user, product=self.product)
|
||||
@@ -106,7 +164,7 @@ class FoodFoundationTests(TestCase):
|
||||
self.assertEqual(context['calorie_remaining'], Decimal('-35'))
|
||||
self.assertEqual(context['meals'][0]['calories'], Decimal('80'))
|
||||
self.assertEqual(context['meals'][2]['calories'], Decimal('55'))
|
||||
self.assertEqual(context['macros'][0]['percent'], None)
|
||||
self.assertEqual(context['macros'][1]['percent'], None)
|
||||
self.client.force_login(self.user)
|
||||
response = self.client.get(reverse('food:diary'), {'date': '2026-10-03'})
|
||||
self.assertContains(response, '35 kcal over goal')
|
||||
|
||||
@@ -2,6 +2,7 @@ from datetime import datetime, time, timedelta
|
||||
|
||||
from django import forms
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from django.db.models import Q
|
||||
from django.shortcuts import get_object_or_404, redirect, render
|
||||
from django.utils import timezone
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
@@ -42,10 +43,11 @@ def tokens(request):
|
||||
expires_at = timezone.make_aware(datetime.combine(expiry + timedelta(days=1), time.min), timezone_for_user(request.user)) if expiry else None
|
||||
_, new_token = create_token(request.user, form.cleaned_data['name'], form.cleaned_data['scopes'], expires_at)
|
||||
form = TokenForm(user=request.user)
|
||||
now = timezone.now()
|
||||
return render(request, 'food/tokens.html', {
|
||||
'form': form, 'new_token': new_token,
|
||||
'tokens': PersonalAccessToken.objects.filter(user=request.user).order_by('-created_at'),
|
||||
'now': timezone.now(),
|
||||
'tokens': PersonalAccessToken.objects.filter(user=request.user, revoked_at__isnull=True)
|
||||
.filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now)).order_by('-created_at'),
|
||||
})
|
||||
|
||||
|
||||
|
||||
+5
-2
@@ -14,6 +14,7 @@ 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.utils.translation import get_language_from_request
|
||||
from django.views.decorators.http import require_GET, require_http_methods, require_POST
|
||||
from django.views.decorators.cache import never_cache
|
||||
|
||||
@@ -131,7 +132,8 @@ def _save_entry(form, user, day, product):
|
||||
|
||||
def _diary_response(request, day):
|
||||
if request.headers.get('HX-Request') == 'true':
|
||||
response = 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, get_language_from_request(request)))
|
||||
response['HX-Push-Url'] = f"{reverse('food:diary')}?date={day.isoformat()}"
|
||||
return response
|
||||
return redirect(f"{reverse('food:diary')}?date={day.isoformat()}")
|
||||
@@ -142,7 +144,8 @@ def diary(request):
|
||||
day, error = _day(request)
|
||||
if error:
|
||||
return error
|
||||
return render(request, 'food/diary.html', diary_context(request.user, day))
|
||||
return render(request, 'food/diary.html',
|
||||
diary_context(request.user, day, get_language_from_request(request)))
|
||||
|
||||
|
||||
@login_required
|
||||
|
||||
Reference in New Issue
Block a user