food logger context tips

This commit is contained in:
Joren de Graaf
2026-10-11 15:21:10 +02:00
parent 559c51e9bb
commit 400e8254c0
51 changed files with 1988 additions and 41 deletions
+198 -4
View File
@@ -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: