Files
Django_TasksApp/main/recipes/services/cook_later.py
T
2026-10-15 19:58:33 +02:00

64 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Canonical owner-scoped Cook Later operations for web and MCP."""
import uuid
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db.models import Q
from recipes.models import CookLater, Recipe
def visible_recipes(user):
visible = Q(owner=user)
demo_name = getattr(settings, 'RECIPE_MATCH_DEMO_USERNAME', '')
if demo_name:
demo = get_user_model().objects.filter(username=demo_name, is_active=True).first()
if demo:
visible |= Q(owner=demo, status=Recipe.Status.PUBLISHED)
return Recipe.objects.filter(visible)
def owned_recipe(user, recipe_id):
try:
identifier = uuid.UUID(str(recipe_id))
except (ValueError, AttributeError, TypeError):
raise ValidationError('Invalid recipe ID.')
recipe = visible_recipes(user).filter(api_id=identifier).first()
if recipe is None:
raise Recipe.DoesNotExist
return recipe
def add(user, recipe_id):
recipe = owned_recipe(user, recipe_id)
entry, created = CookLater.objects.get_or_create(user=user, recipe=recipe)
return {'recipe_id': str(recipe.api_id), 'is_cook_later': True, 'created': created,
'created_at': entry.created_at.isoformat()}
def remove(user, recipe_id):
try:
identifier = uuid.UUID(str(recipe_id))
except (ValueError, AttributeError, TypeError):
raise ValidationError('Invalid recipe ID.')
saved = CookLater.objects.filter(user=user, recipe__api_id=identifier).select_related('recipe').first()
recipe = saved.recipe if saved else owned_recipe(user, identifier)
removed, _ = CookLater.objects.filter(user=user, recipe=recipe).delete()
return {'recipe_id': str(recipe.api_id), 'is_cook_later': False, 'removed': bool(removed)}
def list_entries(user, search='', limit=20, offset=0):
if not 1 <= limit <= 100 or offset < 0:
raise ValidationError('limit must be 1–100 and offset must be non-negative.')
entries = CookLater.objects.filter(user=user, recipe__in=visible_recipes(user)).select_related('recipe')
if search:
entries = entries.filter(Q(recipe__title__icontains=search) |
Q(recipe__description__icontains=search))
count = entries.count()
items = [{'recipe_id': str(entry.recipe.api_id), 'title': entry.recipe.title,
'summary': entry.recipe.description, 'created_at': entry.created_at.isoformat(),
'is_cook_later': True} for entry in entries[offset:offset + limit]]
return {'count': count, 'limit': limit, 'offset': offset, 'recipes': items}