recipe links

This commit is contained in:
Joren de Graaf
2026-10-23 14:30:58 +02:00
parent 5b986134be
commit 4d76a2bc9c
52 changed files with 2698 additions and 19 deletions
+179 -2
View File
@@ -10,7 +10,7 @@ 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, RecipeSubrecipe, RecipeUse
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
@@ -82,10 +82,26 @@ def _detail(recipe):
'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()])
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():
@@ -198,6 +214,167 @@ def recipe_create(request):
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):