Files
Django_TasksApp/main/recipes/api.py
T
2026-10-23 14:30:58 +02:00

595 lines
30 KiB
Python

"""Owner-scoped HTTP recipe operations used by the MCP adapter."""
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
from django.db.models import Q
from django.http import JsonResponse
from food.api import (_date, _decimal, _idempotent, _json, _time, _uuid,
api_view, error)
from food.models import FoodProduct, MealType
from .models import CookLater, Recipe, RecipeIngredient, RecipeLink, RecipeSubrecipe, RecipeUse
from .services import cook_later
from .services.analysis import AnalysisError, analyze
from .services.cooking import CookingError, complete, make_completion
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
from .services.variations import create_variation
RECIPE_FIELDS = {'title', 'description', 'instructions_markdown', 'notes_markdown',
'preparation_minutes', 'cooking_minutes', 'default_servings',
'yield_amount', 'yield_unit', 'category', 'tags', 'status', 'is_favourite'}
INGREDIENT_FIELDS = {'name', 'quantity', 'unit', 'amount_per_unit', 'amount_per_unit_unit',
'inventory_product_id', 'nutrition_product_id', 'preparation_note',
'is_optional', 'display_order'}
def _unknown(data, allowed):
extra = set(data) - allowed
if extra:
raise ValueError(f'Unknown fields: {", ".join(sorted(extra))}.')
def _owned(request, identifier):
return Recipe.objects.filter(owner=request.api_user, api_id=identifier).first()
def _product(request, value):
product = FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(value)).first()
if product is None:
raise ValueError('Choose one of your own food products.')
return product
def _summary(recipe):
return {'id': str(recipe.api_id), 'title': recipe.title, 'description': recipe.description,
'category': recipe.category, 'tags': recipe.tags, 'status': recipe.status,
'is_favourite': recipe.is_favourite, 'is_cook_later': getattr(recipe, 'is_cook_later', False),
'default_servings': str(recipe.default_servings),
'total_minutes': recipe.total_minutes,
'parent_id': str(recipe.parent.api_id) if recipe.parent_id else None,
'updated_at': recipe.updated_at.isoformat()}
def _ingredient_data(item):
return {'id': item.pk, 'name': item.name, 'quantity': str(item.quantity), 'unit': item.unit,
'amount_per_unit': str(item.amount_per_unit) if item.amount_per_unit is not None else None,
'amount_per_unit_unit': item.amount_per_unit_unit or None,
'inventory_product_id': str(item.inventory_product.api_id) if item.inventory_product_id else None,
'nutrition_product_id': str(item.nutrition_product.api_id) if item.nutrition_product_id else None,
'preparation_note': item.preparation_note, 'is_optional': item.is_optional,
'display_order': item.display_order,
'substitutions': [{'id': alternative.pk, 'name': alternative.name,
'quantity': str(alternative.quantity), 'unit': alternative.unit,
'product_id': str(alternative.product.api_id) if alternative.product_id else None}
for alternative in item.substitutions.all()]}
def _detail(recipe):
data = _summary(recipe)
data.update(instructions_markdown=recipe.instructions_markdown,
notes_markdown=recipe.notes_markdown,
preparation_minutes=recipe.preparation_minutes,
cooking_minutes=recipe.cooking_minutes,
yield_amount=str(recipe.yield_amount) if recipe.yield_amount is not None else None,
yield_unit=recipe.yield_unit or None,
markdown_revision=recipe.markdown_revision,
ingredients=[_ingredient_data(item) for item in recipe.ingredients.all()],
subrecipes=[{'id': item.pk, 'component_id': str(item.component.api_id),
'title': item.component.title, 'quantity': str(item.quantity),
'unit': item.unit, 'note': item.note, 'display_order': item.display_order}
for item in recipe.subrecipes.all()],
variations=[{'id': str(item.api_id), 'title': item.title}
for item in recipe.variations.all()],
linked_recipes=_link_data(recipe))
return data
def _link_data(recipe):
links = RecipeLink.objects.filter(owner=recipe.owner, source=recipe,
target__owner=recipe.owner).select_related('target')
incoming = RecipeLink.objects.filter(owner=recipe.owner, target=recipe, reciprocal=True,
source__owner=recipe.owner).select_related('source')
return ([{'link_id': str(link.id), 'recipe_id': str(link.target.api_id),
'title': link.target.title, 'relationship': link.relationship,
'note': link.note, 'reciprocal': link.reciprocal, 'direction': 'outgoing'}
for link in links[:50]] +
[{'link_id': str(link.id), 'recipe_id': str(link.source.api_id),
'title': link.source.title, 'relationship': link.relationship,
'note': link.note, 'reciprocal': True, 'direction': 'incoming'}
for link in incoming[:50]])
def _set_recipe(request, recipe, data):
_unknown(data, RECIPE_FIELDS)
for field, value in data.items():
if field in ('default_servings', 'yield_amount'):
value = _decimal(value, field, positive=True) if value is not None else None
elif field in ('preparation_minutes', 'cooking_minutes'):
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ValueError(f'{field} must be a non-negative integer.')
elif field == 'is_favourite':
if not isinstance(value, bool):
raise ValueError('is_favourite must be a boolean.')
elif field == 'tags':
if (not isinstance(value, list) or len(value) > 12 or
any(not isinstance(tag, str) or not tag.strip() or len(tag) > 40 for tag in value)):
raise ValueError('tags must contain up to 12 non-empty names of at most 40 characters.')
value = list(dict.fromkeys(tag.strip() for tag in value))
elif field == 'yield_unit' and value is None:
value = ''
elif not isinstance(value, str):
raise ValueError(f'{field} must be a string.')
setattr(recipe, field, value)
recipe.full_clean()
recipe.save()
def _set_ingredient(request, item, data):
_unknown(data, INGREDIENT_FIELDS)
for field, value in data.items():
if field in ('quantity', 'amount_per_unit'):
value = _decimal(value, field, positive=True) if value is not None else None
elif field in ('inventory_product_id', 'nutrition_product_id'):
field = field.removesuffix('_id')
value = _product(request, value) if value is not None else None
elif field == 'is_optional':
if not isinstance(value, bool):
raise ValueError('is_optional must be a boolean.')
elif field == 'display_order':
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
raise ValueError('display_order must be a non-negative integer.')
elif not isinstance(value, str):
raise ValueError(f'{field} must be a string.')
setattr(item, field, value)
item.full_clean()
item.save()
@api_view('food:read', ('GET',))
def recipe_search(request):
query = request.GET.get('query', '').strip()[:100]
recipes = Recipe.objects.filter(owner=request.api_user).select_related('parent')
if query:
recipes = recipes.filter(Q(title__icontains=query) | Q(description__icontains=query) |
Q(ingredients__name__icontains=query)).distinct()
if request.GET.get('category'):
recipes = recipes.filter(category=request.GET['category'][:80])
try:
limit = int(request.GET.get('limit', 20))
except ValueError:
return error('invalid_limit', 'limit must be an integer.')
if not 1 <= limit <= 100:
return error('invalid_limit', 'limit must be between 1 and 100.')
items = list(recipes[:limit])
saved = set(CookLater.objects.filter(user=request.api_user, recipe__in=items)
.values_list('recipe_id', flat=True))
for item in items:
item.is_cook_later = item.pk in saved
return JsonResponse({'count': recipes.count(), 'recipes': [_summary(item) for item in items]})
@api_view({'GET': 'food:read', 'POST': 'food:write'}, ('GET', 'POST'))
def recipe_cook_later_collection(request):
if request.method == 'GET':
try:
limit = int(request.GET.get('limit', 20))
offset = int(request.GET.get('offset', 0))
result = cook_later.list_entries(request.api_user, request.GET.get('search', '')[:100], limit, offset)
except (ValueError, ValidationError) as exc:
return error('invalid_pagination', str(exc))
return JsonResponse(result)
try:
result = cook_later.add(request.api_user, _json(request).get('recipe_id'))
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_id', str(exc))
except Recipe.DoesNotExist:
return error('recipe_not_found', 'Recipe not found.', 404)
return JsonResponse(result)
@api_view('food:write', ('DELETE',))
def recipe_cook_later_item(request, identifier):
try:
result = cook_later.remove(request.api_user, identifier)
except Recipe.DoesNotExist:
return error('recipe_not_found', 'Recipe not found.', 404)
return JsonResponse(result)
@api_view('food:write', ('POST',))
def recipe_create(request):
data = _json(request)
def action():
if not data.get('title'):
return error('title_required', 'Provide a recipe title.')
recipe = Recipe(owner=request.api_user)
try:
_set_recipe(request, recipe, data)
except (ValueError, ValidationError) as exc:
return error('invalid_recipe', str(exc))
return JsonResponse(_detail(recipe), status=201)
return _idempotent(request, data, action)
def _link_payload(link, direction='outgoing'):
other = link.target if direction == 'outgoing' else link.source
return {'link_id': str(link.id), 'recipe_id': str(other.api_id), 'title': other.title,
'relationship': link.relationship, 'note': link.note,
'reciprocal': link.reciprocal, 'direction': direction}
@api_view({'GET': 'food:read', 'POST': 'food:write'}, ('GET', 'POST'))
def recipe_links(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
if request.method == 'GET':
return JsonResponse({'links': _link_data(recipe)})
data = _json(request)
try:
_unknown(data, {'recipe_id', 'relationship', 'note', 'reciprocal'})
target = _owned(request, _uuid(data.get('recipe_id')))
if target is None:
return error('recipe_not_found', 'Linked recipe not found.', 404)
if target.pk == recipe.pk:
raise ValueError('A recipe cannot link to itself.')
relationship = data.get('relationship', RecipeLink.Relationship.GOES_WELL_WITH)
note = data.get('note', '')
reciprocal = data.get('reciprocal', True)
if relationship not in RecipeLink.Relationship.values:
raise ValueError('Choose a supported relationship.')
if not isinstance(note, str) or len(note) > 255:
raise ValueError('note must be at most 255 characters.')
if not isinstance(reciprocal, bool):
raise ValueError('reciprocal must be a boolean.')
if RecipeLink.objects.filter(owner=request.api_user, source=target, target=recipe).exists():
raise ValueError('A reverse link already exists; edit that link instead.')
def action():
try:
link = RecipeLink(owner=request.api_user, source=recipe, target=target,
relationship=relationship, note=note.strip(), reciprocal=reciprocal)
link.full_clean()
link.save()
except (ValidationError, IntegrityError):
return error('duplicate_link', 'This recipe link already exists.', 409)
return JsonResponse(_link_payload(link), status=201)
return _idempotent(request, data, action)
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_link', str(exc))
@api_view({'PATCH': 'food:write', 'DELETE': 'food:write'}, ('PATCH', 'DELETE'))
def recipe_link_item(request, identifier, link_id):
link = RecipeLink.objects.filter(owner=request.api_user, id=link_id).select_related('source', 'target').first()
if link is None or str(link.source.api_id) != str(identifier):
return error('recipe_link_not_found', 'Recipe link not found.', 404)
if request.method == 'DELETE':
link.delete()
return JsonResponse({'deleted': True, 'link_id': str(link_id)})
data = _json(request)
try:
_unknown(data, {'relationship', 'note', 'reciprocal'})
for field, value in data.items():
if field == 'relationship' and value not in RecipeLink.Relationship.values:
raise ValueError('Choose a supported relationship.')
if field == 'note' and (not isinstance(value, str) or len(value) > 255):
raise ValueError('note must be at most 255 characters.')
if field == 'reciprocal' and not isinstance(value, bool):
raise ValueError('reciprocal must be a boolean.')
setattr(link, field, value.strip() if field == 'note' else value)
link.full_clean()
link.save()
except (ValueError, ValidationError) as exc:
return error('invalid_recipe_link', str(exc))
return JsonResponse(_link_payload(link))
def _composition(request, data):
components = data.get('components')
if not isinstance(components, list) or not 1 <= len(components) <= 10:
raise ValueError('Choose between one and ten component recipes.')
resolved, seen = [], set()
for row in components:
if not isinstance(row, dict) or set(row) != {'recipe_id', 'servings'}:
raise ValueError('Each component needs recipe_id and servings.')
component = _owned(request, _uuid(row['recipe_id']))
if component is None:
raise ValueError('A selected component recipe was not found.')
if component.pk in seen:
raise ValueError('Choose each component recipe only once.')
seen.add(component.pk)
servings = _decimal(row['servings'], 'servings', positive=True)
if servings > Decimal('99999.99') or servings != servings.quantize(Decimal('.01')):
raise ValueError('Servings must be between 0.01 and 99,999.99 with at most two decimal places.')
resolved.append((component, servings))
return resolved
@api_view('food:read', ('POST',))
def recipe_composition_preview(request):
try:
resolved = _composition(request, _json(request))
component_results, ingredient_counts = [], {}
nutrition_totals = {}
nutrition_completeness = {}
for component, servings in resolved:
result = analyze(component, request.api_user, servings)
for key, value in result['nutrition'].items():
nutrition_completeness[key] = nutrition_completeness.get(key, True) and value['complete']
if value['total'] is not None:
nutrition_totals[key] = nutrition_totals.get(key, Decimal(0)) + value['total']
ingredients = []
for line in result['lines']:
key = (line['name'].strip().casefold(), line['unit'])
ingredient_counts[key] = ingredient_counts.get(key, 0) + 1
ingredients.append({'name': line['name'], 'quantity': str(line['quantity']),
'unit': line['unit'], 'source': line['source']})
component_results.append({'recipe_id': str(component.api_id), 'title': component.title,
'servings': str(servings), 'ingredients': ingredients,
'nutrition': {key: {'total': str(val['total']) if val['total'] is not None else None,
'complete': val['complete']} for key, val in result['nutrition'].items()},
'issues': result['issues']})
duplicates = [{'name': name, 'unit': unit} for (name, unit), count in ingredient_counts.items() if count > 1]
return JsonResponse({'components': component_results, 'duplicate_ingredients': duplicates,
'nutrition': {key: {'total': str(nutrition_totals[key]) if key in nutrition_totals else None,
'complete': nutrition_completeness[key] and key in nutrition_totals}
for key in nutrition_completeness},
'nutrition_complete': bool(nutrition_completeness) and all(
nutrition_completeness[key] and key in nutrition_totals for key in nutrition_completeness),
'note': 'Preview only. Suggestions are excluded; inventory and diary are unchanged.'})
except (ValueError, ValidationError, AnalysisError) as exc:
return error('invalid_composition', str(exc))
@api_view('food:write', ('POST',))
def recipe_composition_create(request):
data = _json(request)
try:
_unknown(data, {'title', 'default_servings', 'components'})
title = data.get('title')
if not isinstance(title, str) or not title.strip() or len(title.strip()) > 180:
raise ValueError('Provide a title of at most 180 characters.')
root_servings = _decimal(data.get('default_servings', '2'), 'default_servings', positive=True)
if root_servings > Decimal('99999.99') or root_servings != root_servings.quantize(Decimal('.01')):
raise ValueError('default_servings must be between 0.01 and 99,999.99 with at most two decimal places.')
resolved = _composition(request, data)
except (ValueError, ValidationError) as exc:
return error('invalid_composition', str(exc))
def action():
try:
with transaction.atomic():
recipe = Recipe(owner=request.api_user, title=title.strip(), default_servings=root_servings)
recipe.full_clean()
recipe.save()
for index, (component, servings) in enumerate(resolved):
relation = RecipeSubrecipe(recipe=recipe, component=component,
quantity=servings, unit='servings', display_order=index)
relation.full_clean()
relation.save()
except (ValidationError, IntegrityError) as exc:
return error('invalid_composition', str(exc))
return JsonResponse(_detail(recipe), status=201)
return _idempotent(request, data, action)
@api_view({'GET': 'food:read', 'PATCH': 'food:write', 'DELETE': 'food:write'},
('GET', 'PATCH', 'DELETE'))
def recipe_item(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
if request.method == 'GET':
recipe.is_cook_later = CookLater.objects.filter(user=request.api_user, recipe=recipe).exists()
return JsonResponse(_detail(recipe))
if request.method == 'PATCH':
data = _json(request)
if not data:
return error('empty_update', 'Provide at least one field.')
try:
_set_recipe(request, recipe, data)
except (ValueError, ValidationError) as exc:
return error('invalid_recipe', str(exc))
return JsonResponse(_detail(recipe))
if recipe.used_in_recipes.exists():
return error('recipe_in_use', 'Remove this recipe from its parent recipes first.', 409)
photo = recipe.photo.name if recipe.photo else ''
with transaction.atomic():
recipe.delete()
if photo:
transaction.on_commit(lambda: recipe.photo.storage.delete(photo))
return JsonResponse({'deleted': True, 'recipe_id': str(identifier)})
@api_view('food:write', ('POST',))
def recipe_variation(request, identifier):
parent = _owned(request, identifier)
if parent is None:
return error('recipe_not_found', 'Recipe not found.', 404)
data = _json(request)
_unknown(data, {'title'})
def action():
title = data.get('title')
if title is not None and (not isinstance(title, str) or not title.strip() or len(title) > 180):
return error('invalid_title', 'Provide a title of at most 180 characters.')
variation = create_variation(request.api_user, parent, title.strip() if title else None)
return JsonResponse(_detail(variation), status=201)
return _idempotent(request, data, action)
@api_view('food:write', ('POST',))
def recipe_ingredient_create(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
data = _json(request)
def action():
item = RecipeIngredient(recipe=recipe)
try:
_set_ingredient(request, item, data)
except (ValueError, ValidationError) as exc:
return error('invalid_ingredient', str(exc))
return JsonResponse(_ingredient_data(item), status=201)
return _idempotent(request, data, action)
@api_view('food:write', ('PATCH', 'DELETE'))
def recipe_ingredient_item(request, identifier, item_id):
item = RecipeIngredient.objects.filter(recipe__api_id=identifier,
recipe__owner=request.api_user, pk=item_id).first()
if item is None:
return error('ingredient_not_found', 'Ingredient not found.', 404)
if request.method == 'DELETE':
item.delete()
return JsonResponse({'deleted': True, 'ingredient_id': item_id})
try:
_set_ingredient(request, item, _json(request))
except (ValueError, ValidationError) as exc:
return error('invalid_ingredient', str(exc))
return JsonResponse(_ingredient_data(item))
@api_view('food:write', ('POST',))
def recipe_subrecipe_create(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
data = _json(request)
_unknown(data, {'component_id', 'quantity', 'unit', 'note', 'display_order'})
component = Recipe.objects.filter(owner=request.api_user,
api_id=_uuid(data.get('component_id'))).first()
if component is None:
return error('component_not_found', 'Component recipe not found.', 404)
def action():
item = RecipeSubrecipe(recipe=recipe, component=component,
quantity=_decimal(data.get('quantity', '1'), 'quantity', positive=True),
unit=data.get('unit', 'servings'), note=data.get('note', ''),
display_order=data.get('display_order', 0))
try:
item.full_clean()
item.save()
except (ValueError, ValidationError, IntegrityError) as exc:
return error('invalid_subrecipe', str(exc))
return JsonResponse({'id': item.pk, 'component_id': str(component.api_id),
'title': component.title, 'quantity': str(item.quantity), 'unit': item.unit}, status=201)
return _idempotent(request, data, action)
@api_view('food:write', ('DELETE',))
def recipe_subrecipe_delete(request, identifier, item_id):
item = RecipeSubrecipe.objects.filter(recipe__api_id=identifier,
recipe__owner=request.api_user, pk=item_id).first()
if item is None:
return error('subrecipe_not_found', 'Subrecipe link not found.', 404)
item.delete()
return JsonResponse({'deleted': True, 'subrecipe_id': item_id})
def _analysis(request, recipe, data):
_unknown(data, {'servings', 'include_optional', 'substitutions'})
if not isinstance(data.get('include_optional', False), bool):
raise ValueError('include_optional must be a boolean.')
substitutions = data.get('substitutions', {})
if not isinstance(substitutions, dict):
raise ValueError('substitutions must be an object.')
return analyze(recipe, request.api_user, data.get('servings'),
include_optional=data.get('include_optional', False),
substitutions=substitutions)
def _analysis_data(result):
return {'recipe_id': str(result['recipe'].api_id), 'servings': str(result['servings']),
'stock_ready': result['stock_ready'], 'issues': result['issues'],
'ingredients': [{'id': line['ingredient'].pk, 'name': line['name'],
'quantity': str(line['quantity']), 'unit': line['unit'],
'status': line['status'], 'reason': line['reason'],
'source': line['source']} for line in result['lines']],
'nutrition': {field: {'total': str(row['total']) if row['total'] is not None else None,
'per_serving': str(row['per_serving']) if row['per_serving'] is not None else None,
'complete': row['complete']}
for field, row in result['nutrition'].items()},
'products': [{'product_id': str(group['product'].api_id),
'product_name': group['product'].product_name,
'required': str(group['stock_amount']) if group.get('stock_amount') else None,
'unit': group['unit'], 'status': group['status'],
'available': str(group['plan']['total']) if group.get('plan') else None,
'shortage': str(group['plan']['shortage']) if group.get('plan') else None,
'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 (group.get('plan') or {}).get('deductions', [])]}
for group in result['groups']]}
@api_view('inventory:read', ('POST',))
def recipe_stock_preview(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
try:
result = _analysis(request, recipe, _json(request))
except (ValueError, AnalysisError) as exc:
return error('invalid_recipe_analysis', str(exc))
data = _analysis_data(result)
data['confirmation'] = make_confirmation(result) if result['stock_ready'] else None
return JsonResponse(data)
@api_view('inventory:write', ('POST',))
def recipe_stock_confirm(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
data = _json(request)
_unknown(data, {'confirmation'})
try:
operation, created = confirm(request.api_user, recipe, data.get('confirmation', ''))
except RecipeStockError as exc:
return error('cannot_deduct_recipe', str(exc))
return JsonResponse({'stock_use_id': str(operation.pk), 'recipe_id': str(recipe.api_id),
'created': created, 'servings': str(operation.servings),
'products_used': operation.lines.count()})
@api_view('inventory:write', ('POST',))
def recipe_stock_undo(request, identifier):
try:
operation, reversed_now = reverse_use(request.api_user, identifier)
except RecipeStockError as exc:
return error('cannot_undo_recipe', str(exc))
return JsonResponse({'stock_use_id': str(operation.pk), 'undone': reversed_now})
@api_view('food:write', ('POST',))
def recipe_log(request, identifier):
recipe = _owned(request, identifier)
if recipe is None:
return error('recipe_not_found', 'Recipe not found.', 404)
data = _json(request)
_unknown(data, {'servings', 'consumed_servings', 'meal', 'date', 'time',
'include_optional', 'substitutions'})
if not request.headers.get('Idempotency-Key'):
return error('idempotency_key_required', 'Provide an Idempotency-Key.')
def action():
try:
result = _analysis(request, recipe, {key: data[key] for key in
('servings', 'include_optional', 'substitutions') if key in data})
run = complete(request.api_user, recipe, make_completion(result),
log_food=True, deduct_stock=False,
consumed_servings=data.get('consumed_servings'),
meal=data.get('meal'), day=_date(data.get('date'), request.api_user),
time=_time(data.get('time')))
except (ValueError, AnalysisError, CookingError, ValidationError) as exc:
return error('invalid_recipe_log', str(exc))
entry = run.food_entry
return JsonResponse({'entry_id': str(entry.api_id), 'recipe_id': str(recipe.api_id),
'date': entry.date.isoformat(), 'meal': entry.meal,
'consumed_servings': str(entry.amount),
'nutrition': {field: str(getattr(entry, field)) if getattr(entry, field) is not None else None
for field in ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g')},
'nutrition_complete': {field: row['complete'] for field, row in run.nutrition_snapshot.items()},
'stock_deducted': False}, status=201)
return _idempotent(request, data, action)