Files
Django_TasksApp/main/food/api.py
T
2026-10-17 11:38:57 +02:00

1139 lines
57 KiB
Python

"""Token-authenticated, owner-scoped HTTP API for future MCP adapters."""
import hashlib
import hmac
import json
import secrets
from django.conf import settings
from decimal import Decimal
from datetime import datetime
from functools import wraps
from uuid import UUID
from PIL import Image, UnidentifiedImageError
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Q
from django.http import FileResponse, JsonResponse
from django.utils import timezone
from django.utils.dateparse import parse_date, parse_time
from django.views.decorators.csrf import csrf_exempt
from planner.models import UserSettings, WaterIntakeEntry
from planner.timezones import localdate_for_user, timezone_for_user
from .models import (ApiIdempotencyRecord, FoodLogAttachment, FoodLogEntry, FoodProduct,
InventoryCategory, InventoryLocation, KitchenInventoryItem,
MealType, PersonalAccessToken, Unit)
from .services.logging import apply_product_snapshot
from .services.hydration import sync_food_hydration, validate_rules
from planner.services.hydration import daily_hydration
from .services.openfoodfacts import OpenFoodFactsError
from .services.product_resolution import (create_manual, external_matches, import_off,
local_matches, match_data)
from .services.inventory_consumption import FACTORS, StockError, consume as consume_stock, preview as preview_stock, stock as stock_packages, undo as undo_stock
SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'}
NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
MANUAL_FIELDS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g')
MAX_IMAGE_BYTES = 5 * 1024 * 1024
def error(code, message, status=400, details=None):
payload = {'error': {'code': code, 'message': message}}
if details:
payload['error']['details'] = details
return JsonResponse(payload, status=status)
def token_value():
prefix = secrets.token_hex(8)
secret = secrets.token_urlsafe(32)
return prefix, f'tn_{prefix}_{secret}'
def create_token(user, name, scopes, expires_at=None):
prefix, value = token_value()
token = PersonalAccessToken.objects.create(user=user, name=name, prefix=prefix,
token_hash=hashlib.sha256(value.encode()).hexdigest(), scopes=sorted(set(scopes)), expires_at=expires_at)
return token, value
def _authenticate(request):
header = request.headers.get('Authorization', '')
if not header.startswith('Bearer '):
return None, error('authentication_required', 'Provide a Bearer API token.', 401)
raw = header[7:]
if len(raw) > 512:
return None, error('invalid_token', 'Invalid API token.', 401)
parts = raw.split('_', 2)
prefix = parts[1] if len(parts) == 3 and parts[0] == 'tn' else ''
token = PersonalAccessToken.objects.select_related('user').filter(prefix=prefix).first() if prefix else None
if token is None or not hmac.compare_digest(token.token_hash, hashlib.sha256(raw.encode()).hexdigest()):
return None, error('invalid_token', 'Invalid API token.', 401)
if token.revoked_at:
return None, error('revoked_token', 'API token has been revoked.', 401)
if token.expires_at and token.expires_at <= timezone.now():
return None, error('expired_token', 'API token has expired.', 401)
PersonalAccessToken.objects.filter(pk=token.pk).update(last_used_at=timezone.now())
return token, None
def api_view(scope, methods):
def decorator(view):
@csrf_exempt
@wraps(view)
def wrapped(request, *args, **kwargs):
if request.method not in methods:
return error('method_not_allowed', 'Method not allowed.', 405)
token, failure = _authenticate(request)
if failure:
return failure
required_scope = scope.get(request.method) if isinstance(scope, dict) else scope
if required_scope and required_scope not in token.scopes:
return error('insufficient_scope', f'Missing {required_scope} scope.', 403)
request.api_token = token
request.api_user = token.user
try:
return view(request, *args, **kwargs)
except (ValueError, ValidationError) as exc:
return error('invalid_request', 'Invalid request data.', 400, str(exc))
return wrapped
return decorator
def _json(request):
if request.content_type != 'application/json':
raise ValueError('Use application/json.')
try:
payload = json.loads(request.body)
except (UnicodeDecodeError, json.JSONDecodeError):
raise ValueError('Malformed JSON.') from None
if not isinstance(payload, dict):
raise ValueError('Expected a JSON object.')
return payload
def _decimal(value, name, positive=False):
try:
result = Decimal(str(value))
except Exception:
raise ValueError(f'Invalid {name}.') from None
if not result.is_finite() or result < 0 or (positive and result == 0):
raise ValueError(f'Invalid {name}.')
return result
def _uuid(value):
try:
return UUID(str(value))
except (TypeError, ValueError, AttributeError):
raise ValueError('Invalid API identifier.') from None
def _date(value, user):
if value is None:
return localdate_for_user(user)
result = parse_date(str(value))
if result is None or result.isoformat() != value:
raise ValueError('Enter date as YYYY-MM-DD.')
return result
def _time(value):
if value is None or value == '':
return None
result = parse_time(str(value))
if result is None:
raise ValueError('Invalid time.')
return result
def _page(request, queryset):
try:
limit = int(request.GET.get('limit', 30))
offset = int(request.GET.get('offset', 0))
except ValueError:
raise ValueError('Invalid pagination.') from None
if not 1 <= limit <= 100 or not 0 <= offset <= 10000:
raise ValueError('Pagination out of range.')
return {'count': queryset.count(), 'limit': limit, 'offset': offset,
'results': queryset[offset:offset + limit]}
def _attachment_data(item):
return {'id': str(item.api_id), 'original_filename': item.original_filename,
'content_type': item.content_type, 'file_size': item.file_size,
'caption': item.caption, 'created_at': item.created_at.isoformat(),
'download_url': f'/api/v1/food/attachments/{item.api_id}/file/'}
def _entry_data(entry):
data = {name: getattr(entry, name) for name in (
'meal', 'product_name_snapshot', 'brand_snapshot', 'barcode_snapshot',
'portion_label_snapshot', 'amount', 'unit', *NUTRIENTS, 'source', 'created_via')}
data.update(id=str(entry.api_id), date=entry.date.isoformat(),
time=entry.time.isoformat() if entry.time else None,
product_id=str(entry.product.api_id) if entry.product_id else None,
beverage_volume_ml=(str(entry.beverage_volume_ml) if entry.beverage_volume_ml is not None else None),
hydration_amount_ml=str(entry.hydration_amount_ml),
hydration_factor=str(entry.hydration_factor_snapshot),
hydration_kind=entry.hydration_kind or None,
hydration_source=entry.hydration_source or None,
attachments=[_attachment_data(item) for item in entry.attachments.all()],
created_at=entry.created_at.isoformat(), updated_at=entry.updated_at.isoformat())
for name in ('amount', *NUTRIENTS):
data[name] = str(data[name]) if data[name] is not None else None
return data
def _product_data(product):
fields = ('product_name', 'brand', 'barcode', 'image_url', 'package_quantity',
'serving_size_text', 'serving_amount', 'serving_unit', 'base_unit',
'energy_kcal_100', 'carbohydrates_100', 'protein_100', 'fat_100',
'fibre_100', 'sugars_100', 'salt_100', 'source')
data = {name: getattr(product, name) for name in fields}
for name in fields:
if isinstance(data[name], Decimal):
data[name] = str(data[name])
data['id'] = str(product.api_id)
data.update(is_beverage=product.is_beverage, hydration_enabled=product.hydration_enabled,
hydration_factor=str(product.hydration_factor), hydration_source=product.hydration_source)
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
def _inventory_data(item):
return {'id': str(item.api_id), 'product_id': str(item.product.api_id),
'product_name': item.product.product_name, 'brand': item.product.brand,
'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,
'original_amount': str(item.original_amount) if item.original_amount is not None else None,
'unit': item.inventory_unit or 'packs', 'status': item.package_status,
'best_before': item.best_before.isoformat() if item.best_before else None,
'archived_at': item.archived_at.isoformat() if item.archived_at else None,
'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()}
def _idempotent(request, payload, action, digest_override=None):
key = request.headers.get('Idempotency-Key')
if not key:
return action()
if len(key) > 128 or not key.isascii() or any(ord(ch) < 33 or ord(ch) > 126 for ch in key):
return error('invalid_idempotency_key', 'Invalid Idempotency-Key.')
digest = digest_override or hashlib.sha256(request.path.encode() + b'\0' + request.body).hexdigest()
with transaction.atomic():
# Lock the token row so concurrent retries serialize on databases with row locking.
PersonalAccessToken.objects.select_for_update().get(pk=request.api_token.pk)
record = ApiIdempotencyRecord.objects.filter(token=request.api_token, key=key).first()
if record:
if not hmac.compare_digest(record.request_hash, digest):
return error('idempotency_conflict', 'This key was used with another request.', 409)
return JsonResponse(record.response, status=200)
response = action()
if response.status_code < 400:
ApiIdempotencyRecord.objects.create(token=request.api_token, key=key,
request_hash=digest, response=json.loads(response.content))
return response
@api_view('food:read', ('GET',))
def today(request):
requested_date = request.GET.get('date')
if requested_date is None:
day = localdate_for_user(request.api_user)
else:
day = parse_date(requested_date)
if day is None or day.isoformat() != requested_date:
return error('invalid_date', 'Use a date in YYYY-MM-DD format.')
entries = list(FoodLogEntry.objects.filter(user=request.api_user, date=day)
.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 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', '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',))
def whoami(request):
subject = hashlib.sha256(f'{request.api_user.pk}:{settings.SECRET_KEY}'.encode()).hexdigest()[:24]
return JsonResponse({'subject': subject, 'scopes': request.api_token.scopes,
'expires_at': request.api_token.expires_at.isoformat() if request.api_token.expires_at else None})
@api_view('food:read', ('GET',))
def products(request):
query = request.GET.get('search', '').strip()[:100]
qs = FoodProduct.objects.filter(owner=request.api_user).prefetch_related('portions').order_by('product_name', 'pk')
if query:
qs = qs.filter(Q(product_name__icontains=query) | Q(brand__icontains=query) | Q(barcode__icontains=query))
page = _page(request, qs)
page['results'] = [_product_data(p) for p in page['results']]
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:
entry = FoodLogEntry(user=request.api_user, created_via='api')
allowed = {'date', 'time', 'meal', 'product_id', 'product_name', 'brand', 'barcode',
'portion_label', 'amount', 'unit', *MANUAL_FIELDS}
unknown = set(data) - allowed
if unknown:
raise ValueError(f'Unknown fields: {", ".join(sorted(unknown))}.')
if 'date' in data or creating:
entry.date = _date(data.get('date'), request.api_user)
if 'time' in data:
entry.time = _time(data['time'])
if 'meal' in data:
if data['meal'] not in MealType.values:
raise ValueError('Invalid meal.')
entry.meal = data['meal']
if 'amount' in data:
entry.amount = _decimal(data['amount'], 'amount', positive=True)
if 'unit' in data:
if data['unit'] not in Unit.values:
raise ValueError('Invalid unit.')
entry.unit = data['unit']
if 'portion_label' in data:
entry.portion_label_snapshot = str(data['portion_label'])
if not entry.meal or entry.amount is None or not entry.unit:
raise ValueError('meal, amount, and unit are required.')
if 'product_id' in data:
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first()
if product is None:
return None, error('product_not_found', 'Food product not found.', 404)
entry.product = product
if entry.product_id:
if entry.unit != entry.product.base_unit:
raise ValueError('Unit must match the product nutrition basis.')
if any(field in data for field in ('product_name', 'brand', 'barcode', *MANUAL_FIELDS)):
raise ValueError('Product entries calculate nutrition from the product.')
apply_product_snapshot(entry, entry.product)
else:
if 'product_name' in data:
entry.product_name_snapshot = str(data['product_name']).strip()
if 'brand' in data:
entry.brand_snapshot = str(data['brand'])
if 'barcode' in data:
entry.barcode_snapshot = str(data['barcode'])
if not entry.product_name_snapshot:
raise ValueError('product_name is required for manual food.')
entry.source = FoodProduct.Source.MANUAL
for name in MANUAL_FIELDS:
if name in data:
setattr(entry, name, _decimal(data[name], name) if data[name] is not None else None)
sync_food_hydration(entry)
entry.full_clean()
entry.save()
return entry, None
@api_view('food:write', ('POST',))
def log_create(request):
data = _json(request)
def create():
entry, failure = _save_entry(request, data)
return failure or JsonResponse(_entry_data(entry), status=201)
return _idempotent(request, data, create)
@api_view('food:read', ('GET',))
def log_detail(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').prefetch_related('attachments').first()
return JsonResponse(_entry_data(entry)) if entry else error('entry_not_found', 'Food log entry not found.', 404)
@api_view('food:write', ('PATCH', 'DELETE'))
def log_change(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).select_related('product').first()
if entry is None:
return error('entry_not_found', 'Food log entry not found.', 404)
if request.method == 'DELETE':
entry.delete()
return JsonResponse({'deleted': True})
entry, failure = _save_entry(request, _json(request), entry)
return failure or JsonResponse(_entry_data(entry))
@api_view('inventory:read', ('GET',))
def inventory_list(request):
qs = KitchenInventoryItem.objects.filter(user=request.api_user, archived_at__isnull=True)
query = request.GET.get('search', '').strip()[:100]
if query:
qs = qs.filter(Q(product__product_name__icontains=query) | Q(product__brand__icontains=query) |
Q(product__barcode__icontains=query) | Q(location__name__icontains=query) |
Q(category__name__icontains=query))
qs = qs.select_related('product', 'location', 'category').order_by('-added_at', '-pk')
page = _page(request, qs)
page['results'] = [_inventory_data(item) for item in page['results']]
return JsonResponse(page)
def _save_inventory(request, data, item=None):
creating = item is None
was_count_only = item is not None and item.original_amount is None
if item is None:
item = KitchenInventoryItem(user=request.api_user)
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount',
'original_amount', 'unit', 'purchase_batch'}
if set(data) - allowed:
raise ValueError('Unknown inventory fields.')
if 'product_id' in data:
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(data['product_id'])).first()
if product is None:
return None, error('product_not_found', 'Food product not found.', 404)
item.product = product
if 'quantity' in data:
if isinstance(data['quantity'], bool) or not isinstance(data['quantity'], int) or data['quantity'] < 1:
raise ValueError('Quantity must be a positive integer.')
item.quantity = data['quantity']
if 'location' in data:
name = ' '.join(str(data['location']).split())
if not name or len(name) > 100:
raise ValueError('Invalid location.')
item.location, _ = InventoryLocation.objects.get_or_create(user=request.api_user, name__iexact=name, defaults={'name': name})
if 'category' in data:
name = ' '.join(str(data['category'] or '').split())
if len(name) > 100:
raise ValueError('Invalid category.')
item.category = (InventoryCategory.objects.get_or_create(user=request.api_user, name__iexact=name,
defaults={'name': name})[0] if name else None)
if 'notes' in data:
item.notes = str(data['notes'])
if 'opened' in data:
if not isinstance(data['opened'], bool):
raise ValueError('opened must be a boolean.')
item.opened = data['opened']
if 'remaining_amount' in data:
new_remaining = (_decimal(data['remaining_amount'], 'remaining_amount')
if data['remaining_amount'] is not None else None)
if not creating and new_remaining != item.remaining_amount:
raise ValueError('Use inventory consumption or undo to change remaining stock.')
item.remaining_amount = new_remaining
if 'original_amount' in data:
new_original = _decimal(data['original_amount'], 'original_amount') if data['original_amount'] is not None else None
if not creating and not was_count_only and new_original != item.original_amount:
raise ValueError('Existing package size cannot be changed.')
item.original_amount = new_original
if 'unit' in data:
if not creating and not was_count_only and data['unit'] != item.inventory_unit:
raise ValueError('Existing package unit cannot be changed.')
item.inventory_unit = str(data['unit'])
if 'purchase_batch' in data:
item.purchase_batch = str(data['purchase_batch'])[:100]
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:
raise ValueError('product_id and location are required.')
if creating and item.original_amount is None and item.product.package_amount:
item.original_amount, item.inventory_unit = item.product.package_amount, item.product.package_unit
if item.original_amount is not None and item.remaining_amount is None:
item.remaining_amount = item.original_amount
item.full_clean()
item.save()
if creating or (was_count_only and item.original_amount is not None):
from .services.inventory_consumption import materialize_packages
materialize_packages(item)
return item, None
@api_view('inventory:write', ('POST',))
def inventory_create(request):
data = _json(request)
def create():
item, failure = _save_inventory(request, data)
return failure or JsonResponse(_inventory_data(item), status=201)
return _idempotent(request, data, create)
@api_view('inventory:read', ('GET',))
def inventory_detail(request, identifier):
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
archived_at__isnull=True).select_related('product', 'location', 'category').first()
return JsonResponse(_inventory_data(item)) if item else error('inventory_item_not_found', 'Inventory item not found.', 404)
@api_view('inventory:write', ('PATCH', 'DELETE'))
def inventory_change(request, identifier):
if request.method == 'DELETE':
item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier,
archived_at__isnull=True).first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
item.archived_at = timezone.now()
item.save(update_fields=('archived_at', 'updated_at'))
return JsonResponse({'deleted': True})
data = _json(request)
try:
with transaction.atomic():
# Serialize absolute remaining-amount updates with stock consumption.
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
item = KitchenInventoryItem.objects.select_for_update().filter(
user=request.api_user, api_id=identifier, archived_at__isnull=True,
).select_related('product', 'location', 'category').first()
if item is None:
return error('inventory_item_not_found', 'Inventory item not found.', 404)
return _apply_inventory_update(request, item, data)
except (ValueError, ValidationError) as exc:
return _inventory_exception(exc)
def _apply_inventory_update(request, item, data):
"""Shared single-item rules for PATCH and batch updates; caller owns the transaction."""
data = dict(data)
try:
remaining = data.get('remaining_amount', item.remaining_amount)
if 'remaining_amount' in data and remaining is not None:
try:
remaining = _decimal(remaining, 'remaining_amount')
except ValueError as exc:
return _inventory_validation('remaining_amount', str(exc))
if item.original_amount is None or item.remaining_amount is None:
return _inventory_validation('remaining_amount', 'This item has no known package amount.')
if remaining > item.original_amount:
return _inventory_validation('remaining_amount', 'Amount exceeds the package capacity.')
if remaining != remaining.quantize(Decimal('.001')):
return _inventory_validation('remaining_amount', 'Use at most three decimal places.')
if remaining > item.remaining_amount:
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
if remaining < item.remaining_amount:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0],
'Change package identity or size separately from consumption.')
if data.get('opened') is False and remaining > 0:
return _inventory_validation('opened', 'A partly used package must be opened.')
from .services.inventory_consumption import StockError, consume
try:
consume(request.api_user, item.product, item.remaining_amount - remaining,
item.inventory_unit, package_id=item.api_id, source='mcp',
description=str(data.get('notes') or '')[:255])
except StockError as exc:
return _inventory_validation('remaining_amount', str(exc))
item.refresh_from_db()
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
elif 'remaining_amount' in data:
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
item, failure = _save_inventory(request, data, item)
return failure or JsonResponse(_inventory_data(item))
except (ValueError, ValidationError) as exc:
return _inventory_exception(exc)
def _inventory_exception(exc):
if isinstance(exc, ValidationError) and hasattr(exc, 'message_dict'):
field, messages = next(iter(exc.message_dict.items()))
return _inventory_validation(field, '; '.join(messages))
return _inventory_validation('inventory', '; '.join(exc.messages) if isinstance(exc, ValidationError) else str(exc))
def _inventory_validation(field, reason):
return error('invalid_inventory_update', 'Inventory update rejected.', 400,
{'field': field, 'reason': reason})
def _inventory_batch_input(request, data, *, deleting=False):
rows = data.get('item_ids' if deleting else 'items')
if not isinstance(rows, list) or not 1 <= len(rows) <= 20:
raise ValueError('Provide between 1 and 20 inventory items.')
if set(data) - ({'item_ids', 'dry_run', 'atomic', 'confirm'} if deleting else {'items', 'dry_run', 'atomic'}):
raise ValueError('Unknown bulk inventory fields.')
if any(type(data.get(key, default)) is not bool for key, default in (('dry_run', False), ('atomic', False))):
raise ValueError('dry_run and atomic must be booleans.')
if deleting and type(data.get('confirm', False)) is not bool:
raise ValueError('confirm must be a boolean.')
parsed = []
for raw in rows:
if deleting:
identifier = raw
changes = None
expected = None
else:
if not isinstance(raw, dict) or set(raw) - {'item_id', 'changes', 'expected_updated_at'}:
raise ValueError('Each update needs item_id and changes.')
identifier = raw.get('item_id')
changes = raw.get('changes')
expected = raw.get('expected_updated_at')
if not isinstance(changes, dict) or not changes or set(changes) - {
'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'remaining_amount', 'best_before'}:
raise ValueError('Each update needs supported, nonempty changes.')
if expected is not None and not isinstance(expected, str):
raise ValueError('expected_updated_at must be a timestamp.')
parsed.append((_uuid(identifier), changes, expected))
if len({identifier for identifier, _, _ in parsed}) != len(parsed):
raise ValueError('Duplicate inventory item IDs are not allowed.')
return parsed
def _inventory_batch(request, parsed, *, deleting, dry_run, atomic):
results = []
with transaction.atomic():
type(request.api_user).objects.select_for_update().get(pk=request.api_user.pk)
for identifier, changes, expected in parsed:
with transaction.atomic():
item = KitchenInventoryItem.objects.select_for_update().filter(
user=request.api_user, api_id=identifier, archived_at__isnull=True,
).select_related('product', 'location', 'category').first()
if item is None:
result = {'item_id': str(identifier), 'status': 'failed', 'error': {
'code': 'inventory_item_not_found', 'message': 'Inventory item not found or unavailable.'}}
results.append(result)
continue
before = _inventory_data(item)
if expected is not None and expected != item.updated_at.isoformat():
results.append({'item_id': str(identifier), 'status': 'failed', 'before': before,
'error': {'code': 'inventory_conflict', 'message': 'Item changed since it was read.'}})
continue
if deleting:
item.archived_at = timezone.now()
item.save(update_fields=('archived_at', 'updated_at'))
after = _inventory_data(item)
failed = False
else:
response = _apply_inventory_update(request, item, changes)
failed = response.status_code >= 400
if failed:
result = {'item_id': str(identifier), 'status': 'failed', 'before': before,
'error': json.loads(response.content)['error']}
transaction.set_rollback(True)
results.append(result)
continue
after = json.loads(response.content)
meaningful = {key: value for key, value in after.items() if key != 'updated_at'} != {
key: value for key, value in before.items() if key != 'updated_at'}
results.append({'item_id': str(identifier), 'status': 'validated' if dry_run and meaningful else
'changed' if meaningful else 'unchanged', 'before': before, 'after': after})
if dry_run or not meaningful:
transaction.set_rollback(True)
failed_count = sum(row['status'] == 'failed' for row in results)
if atomic and failed_count and not dry_run:
for row in results:
if row['status'] == 'changed':
row['status'] = 'rolled_back'
transaction.set_rollback(True)
if dry_run:
transaction.set_rollback(True)
counts = {status: sum(row['status'] == status for row in results) for status in
('validated', 'changed', 'unchanged', 'failed', 'rolled_back')}
return JsonResponse({'dry_run': dry_run, 'atomic': atomic, 'items': results, 'counts': counts,
'status': 'preview' if dry_run else 'rolled_back' if atomic and failed_count else
'partial_success' if failed_count else 'success'})
@api_view('inventory:write', ('POST',))
def inventory_bulk_update(request):
if len(request.body) > 65536:
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
data = _json(request)
parsed = _inventory_batch_input(request, data)
dry_run = data.get('dry_run', True)
if not dry_run and not request.headers.get('Idempotency-Key'):
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
action = lambda: _inventory_batch(request, parsed, deleting=False, dry_run=dry_run, atomic=data.get('atomic', False))
return action() if dry_run else _idempotent(request, data, action)
@api_view('inventory:write', ('POST',))
def inventory_bulk_delete(request):
if len(request.body) > 65536:
return error('batch_too_large', 'Batch payload exceeds 64 KB.', 413)
data = _json(request)
parsed = _inventory_batch_input(request, data, deleting=True)
dry_run = data.get('dry_run', True)
if not dry_run and not data.get('confirm', False):
return error('confirmation_required', 'Preview the items and explicitly confirm deletion.', 400)
if not dry_run and not request.headers.get('Idempotency-Key'):
return error('idempotency_key_required', 'Provide an Idempotency-Key.', 400)
action = lambda: _inventory_batch(request, parsed, deleting=True, dry_run=dry_run, atomic=data.get('atomic', False))
return action() if dry_run else _idempotent(request, data, action)
@api_view('food:write', ('POST',))
def attachment_create(request, identifier):
entry = FoodLogEntry.objects.filter(user=request.api_user, api_id=identifier).first()
if entry is None:
return error('entry_not_found', 'Food log entry not found.', 404)
if int(request.META.get('CONTENT_LENGTH') or 0) > MAX_IMAGE_BYTES + 65536:
return error('image_too_large', 'Image exceeds 5 MB.', 413)
upload = request.FILES.get('image')
if upload is None:
return error('image_required', 'Upload an image field.')
if upload.size > MAX_IMAGE_BYTES:
return error('image_too_large', 'Image exceeds 5 MB.', 413)
try:
image = Image.open(upload)
if image.width * image.height > 25_000_000:
return error('image_too_large', 'Image dimensions are too large.', 413)
image.verify()
image_format = image.format
except (UnidentifiedImageError, OSError, ValueError):
return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.')
content_types = {'JPEG': 'image/jpeg', 'PNG': 'image/png', 'WEBP': 'image/webp'}
if image_format not in content_types or upload.content_type != content_types[image_format]:
return error('unsupported_image_type', 'Use a valid JPEG, PNG, or WebP image.')
upload.seek(0)
extension = {'JPEG': 'jpg', 'PNG': 'png', 'WEBP': 'webp'}[image_format]
attachment = FoodLogAttachment(log_entry=entry, image=upload,
original_filename=upload.name.rsplit('/', 1)[-1].rsplit('\\', 1)[-1][:255],
content_type=content_types[image_format], file_size=upload.size,
caption=request.POST.get('caption', '')[:255])
attachment.image.name = f'{secrets.token_hex(16)}.{extension}'
def create():
attachment.save()
return JsonResponse(_attachment_data(attachment), status=201)
digest = hashlib.sha256(str(entry.api_id).encode() + b'\0' + upload.read() +
b'\0' + attachment.caption.encode()).hexdigest()
upload.seek(0)
return _idempotent(request, None, create, digest_override=digest)
@api_view('food:read', ('GET',))
def attachment_file(request, identifier):
item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first()
if item is None:
return error('attachment_not_found', 'Attachment not found.', 404)
response = FileResponse(item.image.open('rb'), content_type=item.content_type)
response['Content-Disposition'] = 'inline'
response['X-Content-Type-Options'] = 'nosniff'
return response
@api_view('food:write', ('DELETE',))
def attachment_delete(request, identifier):
item = FoodLogAttachment.objects.filter(api_id=identifier, log_entry__user=request.api_user).first()
if item is None:
return error('attachment_not_found', 'Attachment not found.', 404)
item.delete()
return JsonResponse({'deleted': True})
@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'}, ('GET', 'PATCH', 'DELETE'))
def log_item(request, identifier):
if request.method == 'GET':
return log_detail.__wrapped__(request, identifier)
return log_change.__wrapped__(request, identifier)
@api_view({'GET': 'inventory:read', 'POST': 'inventory:write'}, ('GET', 'POST'))
def inventory_collection(request):
if request.method == 'GET':
return inventory_list.__wrapped__(request)
return inventory_create.__wrapped__(request)
@api_view({'GET': 'inventory:read', 'PATCH': 'inventory:write', 'DELETE': 'inventory:write'}, ('GET', 'PATCH', 'DELETE'))
def inventory_item(request, identifier):
if request.method == 'GET':
return inventory_detail.__wrapped__(request, identifier)
return inventory_change.__wrapped__(request, identifier)
def _stock_product(request, identifier):
return FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(identifier)).first()
def _stock_result(plan):
return {'requested': str(plan['requested']), 'unit': plan['unit'],
'available': str(plan['total']), 'shortage': str(plan['shortage']),
'deductions': [{'package_id': str(row['package'].api_id),
'amount': str(row['amount']), 'unit': row['unit'],
'before': str(row['before']), 'after': str(row['after'])}
for row in plan['deductions']]}
@api_view('inventory:read', ('GET',))
def inventory_stock(request):
identifier = request.GET.get('product_id')
if identifier:
product = _stock_product(request, identifier)
if product is None:
return error('product_not_found', 'Product not found.', 404)
products = [product]
else:
query = request.GET.get('query', '').strip()[:100]
if not query:
return error('product_required', 'Provide product_id or query.')
products = list(FoodProduct.objects.filter(owner=request.api_user,
inventory_items__archived_at__isnull=True).filter(
Q(product_name__icontains=query) | Q(barcode=query)).distinct()[:20])
result = []
location = request.GET.get('location_id')
for product in products:
packages = stock_packages(request.api_user, product, location)
groups = {}
for item in packages:
unit = item.inventory_unit or 'packs'
amount = item.remaining_amount if item.remaining_amount is not None else Decimal(item.quantity)
dimension, factor = FACTORS[unit]
base_unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, unit)
groups[base_unit] = groups.get(base_unit, Decimal(0)) + amount * factor
result.append({'product_id': str(product.api_id), 'product_name': product.product_name,
'totals': {unit: str(amount) for unit, amount in groups.items()},
'available': any(amount > 0 for amount in groups.values()),
'packages': [_inventory_data(item) for item in packages]})
return JsonResponse({'count': len(result), 'products': result})
@api_view('inventory:read', ('POST',))
def inventory_preview(request):
try:
data = _json(request)
product = _stock_product(request, data['product_id'])
if product is None:
return error('product_not_found', 'Product not found.', 404)
plan = preview_stock(request.api_user, product, data['amount'], data['unit'], data.get('package_id'))
return JsonResponse(_stock_result(plan))
except (StockError, KeyError, ValueError) as exc:
return error('invalid_consumption', str(exc))
@api_view('inventory:write', ('POST',))
def inventory_consume(request):
try:
data = _json(request)
product = _stock_product(request, data['product_id'])
if product is None:
return error('product_not_found', 'Product not found.', 404)
key = request.headers.get('Idempotency-Key', '')
if not key:
return error('idempotency_key_required', 'Provide an Idempotency-Key.')
operation = consume_stock(request.api_user, product, data['amount'], data['unit'],
package_id=data.get('package_id'), source='mcp',
source_reference=data.get('source_reference', ''),
description=data.get('description', ''), idempotency_key=key,
allow_partial=data.get('allow_partial') is True)
return JsonResponse({'transaction_id': str(operation.pk), 'amount': str(operation.amount),
'unit': operation.unit, 'deductions': [{'package_id': str(line.package.api_id),
'amount': str(line.amount), 'unit': line.unit} for line in operation.lines.select_related('package')]})
except (StockError, KeyError, ValueError) as exc:
return error('invalid_consumption', str(exc))
@api_view('inventory:write', ('POST',))
def inventory_undo(request, identifier):
try:
reversal = undo_stock(request.api_user, identifier)
return JsonResponse({'transaction_id': str(reversal.pk), 'reverses': str(reversal.reverses_id)})
except (StockError, ValueError) as exc:
return error('cannot_undo', str(exc))
def _water_data(entry):
return {'id': str(entry.api_id), 'amount_ml': str(entry.amount_ml),
'beverage_type': entry.beverage_type, 'recorded_at': entry.recorded_at.isoformat(),
'source': 'manual'}
def _water_amount(value):
amount = _decimal(value, 'amount_ml', positive=True)
if amount > 3000 or amount != amount.quantize(Decimal('.001')):
raise ValueError('Amount must be at most 3000 ml with up to three decimal places.')
return amount
def _water_timestamp(value, user):
if not value:
return timezone.now()
try:
parsed = datetime.fromisoformat(str(value).replace('Z', '+00:00'))
except ValueError:
raise ValueError('Use an ISO 8601 timestamp.') from None
if timezone.is_naive(parsed):
parsed = timezone.make_aware(parsed, timezone_for_user(user))
return parsed
@api_view('food:read', ('GET',))
def hydration_daily(request):
value = request.GET.get('date')
day = parse_date(value) if value else localdate_for_user(request.api_user)
if day is None or (value and day.isoformat() != value):
return error('invalid_date', 'Use YYYY-MM-DD.')
result = daily_hydration(request.api_user, day)
return JsonResponse({key: value.isoformat() if key == 'date' else str(value)
for key, value in result.items()})
@api_view('food:write', ('POST',))
def hydration_log(request):
data = _json(request)
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
allowed = {'amount_ml', 'beverage_type', 'recorded_at'}
if set(data) - allowed:
return error('invalid_fields', 'Unknown hydration fields.')
amount = _water_amount(data.get('amount_ml'))
beverage_type = str(data.get('beverage_type', 'water')).strip().lower()
if not beverage_type or len(beverage_type) > 32:
return error('invalid_beverage_type', 'Invalid beverage type.')
recorded_at = _water_timestamp(data.get('recorded_at'), request.api_user)
key = request.headers.get('Idempotency-Key', '')
def create():
if key:
previous = WaterIntakeEntry.objects.filter(user=request.api_user, idempotency_key=key).first()
if previous:
if previous.amount_ml != amount or previous.beverage_type != beverage_type or (
data.get('recorded_at') and previous.recorded_at != recorded_at):
return error('idempotency_conflict', 'Key was used for another hydration entry.', 409)
return JsonResponse(_water_data(previous))
entry = WaterIntakeEntry.objects.create(user=request.api_user, amount_ml=amount,
beverage_type=beverage_type, recorded_at=recorded_at, idempotency_key=key)
return JsonResponse(_water_data(entry), status=201)
return _idempotent(request, data, create)
@api_view('food:write', ('PATCH', 'DELETE'))
def hydration_manual_entry(request, identifier):
entry = WaterIntakeEntry.objects.filter(user=request.api_user, api_id=identifier).first()
if entry is None:
return error('hydration_entry_not_found', 'Manual hydration entry not found.', 404)
if not UserSettings.objects.get_or_create(user=request.api_user)[0].allow_manual_hydration_adjustments:
return error('manual_hydration_disabled', 'Manual hydration is disabled.', 403)
if request.method == 'DELETE':
entry.delete()
return JsonResponse({'deleted': True})
data = _json(request)
if set(data) - {'amount_ml', 'beverage_type', 'recorded_at'}:
return error('invalid_fields', 'Unknown hydration fields.')
if 'amount_ml' in data:
entry.amount_ml = _water_amount(data['amount_ml'])
if 'beverage_type' in data:
entry.beverage_type = str(data['beverage_type']).strip().lower()
if not entry.beverage_type or len(entry.beverage_type) > 32:
return error('invalid_beverage_type', 'Invalid beverage type.')
if 'recorded_at' in data:
entry.recorded_at = _water_timestamp(data['recorded_at'], request.api_user)
entry.full_clean()
entry.save()
return JsonResponse(_water_data(entry))
def _hydration_settings_data(settings):
return {'daily_water_goal_ml': settings.daily_water_goal_ml,
'auto_count_food_drinks': settings.auto_count_food_drinks,
'include_liquid_foods': settings.include_liquid_foods,
'show_hydration_breakdown': settings.show_hydration_breakdown,
'allow_manual_hydration_adjustments': settings.allow_manual_hydration_adjustments,
'hydration_beverage_rules': settings.hydration_beverage_rules}
@api_view({'GET': 'food:read', 'PATCH': 'food:write'}, ('GET', 'PATCH'))
def hydration_settings(request):
settings = UserSettings.objects.get_or_create(user=request.api_user)[0]
if request.method == 'GET':
return JsonResponse(_hydration_settings_data(settings))
data = _json(request)
allowed = set(_hydration_settings_data(settings))
if set(data) - allowed:
return error('invalid_fields', 'Unknown hydration settings.')
for field in ('auto_count_food_drinks', 'include_liquid_foods', 'show_hydration_breakdown',
'allow_manual_hydration_adjustments'):
if field in data:
if not isinstance(data[field], bool):
return error('invalid_setting', f'{field} must be true or false.')
setattr(settings, field, data[field])
if 'daily_water_goal_ml' in data:
goal = data['daily_water_goal_ml']
if isinstance(goal, bool) or not isinstance(goal, int) or not 250 <= goal <= 10000:
return error('invalid_goal', 'Daily goal must be 250 to 10000 ml.')
settings.daily_water_goal_ml = goal
if 'hydration_beverage_rules' in data:
settings.hydration_beverage_rules = validate_rules(data['hydration_beverage_rules'])
settings.full_clean()
settings.save()
return JsonResponse(_hydration_settings_data(settings))