diff --git a/main/MCP.md b/main/MCP.md index d4b58a2..67740cd 100644 --- a/main/MCP.md +++ b/main/MCP.md @@ -1,6 +1,6 @@ # TaskNest MCP server -The Streamable HTTP MCP endpoint exposes the Food and Kitchen API to an AI assistant. The server in `mcp_server.server` is an HTTP adapter: every user operation goes through `/api/v1/` with the connected user's bearer token. It does not read Django models directly. +The Streamable HTTP MCP endpoint exposes the Food, Kitchen, and Recipes API to an AI assistant. The server in `mcp_server.server` is an HTTP adapter: every user operation goes through `/api/v1/` with the connected user's bearer token. It does not read Django models directly. ## Local development @@ -64,6 +64,32 @@ Image interpretation belongs to the AI client. For a grocery photograph, identif For ambiguous candidates, ask the user to select one or supply more identifying details. Report batch item statuses individually: `added`, `needs_review`, or `skipped`. A batch can return `partial_success`; successful items remain added while failed items do not leave partial product or inventory writes. A changed payload with the same idempotency key returns a conflict. +## Recipes + +Recipe tools use the connected user's recipes and products. `recipe_search` and `recipe_get` require `food:read`. Creation, updates, deletion, variation, ingredient, and subrecipe tools require `food:write`. Ingredient product IDs must belong to the user. Variations copy ingredients, substitutions, and component links; later edits are independent. Component recipes cannot form cycles. + +Create a recipe, then add ingredients: + +```json +{"recipe":{"title":"Oat bowl","default_servings":"2","instructions_markdown":"Mix oats and milk."},"idempotency_key":"recipe-oat-bowl-1"} +``` + +```json +{"recipe_id":"","ingredient":{"name":"Oats","quantity":"150","unit":"g","inventory_product_id":"","nutrition_product_id":""},"idempotency_key":"oat-ingredient-1"} +``` + +`recipe_create_variation` accepts `recipe_id`, an optional `title`, and an optional `idempotency_key`. `recipe_subrecipe_add` accepts the parent `recipe_id`, owned `component_id`, positive decimal `quantity` (default 1), `unit` (default `servings`), and an optional `idempotency_key`. `recipe_subrecipe_remove` takes the parent `recipe_id` and returned `subrecipe_id`. + +Inventory deduction is an explicit two-step action. Call `recipe_check_inventory` with the recipe ID and an optional `options` object containing `servings`, `include_optional`, or `substitutions`. It returns shortages, the package deduction plan, and a signed `confirmation` only when stock is ready. After the user confirms that plan, pass its exact `confirmation` and `recipe_id` to `recipe_deduct_inventory`. A repeated confirmation returns the existing operation without deducting twice. `recipe_undo_inventory` takes the returned `stock_use_id` and reverses the deduction when affected packages have not changed. Preview requires `inventory:read`; deduction and undo require `inventory:write`. + +`recipe_log_meal` is a separate `food:write` action. It logs a nutrition snapshot for consumed servings and never deducts inventory. Supply `recipe_id`, `consumed_servings`, `meal`, and an `idempotency_key`; `servings`, `date`, and `time` are optional. Repeat the same key and arguments on retry to avoid duplicate diary entries. A recipe meal can be logged even when inventory is short. + +```json +{"recipe_id":"","consumed_servings":"1","meal":"dinner","date":"2026-10-12","idempotency_key":"recipe-dinner-2026-10-12-1"} +``` + +The corresponding HTTP routes are listed in `GET /api/v1/schema/`. Recipe meal dates use the user's local calendar date by default. Inventory deduction never creates a food diary entry as a side effect. + ## Partial inventory use `inventory_get_stock` returns owned products, remaining totals, and individual packages. Use a product ID for a definite match; a text query returns candidates. `inventory_preview_consumption` is read only and shows package deductions and any shortage. `inventory_consume` requires a product ID, positive decimal amount, compatible unit, and idempotency key. It uses opened packages first, then best-before date and age. Set `allow_partial` only after the user explicitly accepts a shortage. `inventory_undo_consumption` records a reversal when the affected package quantities have not changed. All four tools enforce the existing inventory read or write scopes through the HTTP API. diff --git a/main/food/api_schema.py b/main/food/api_schema.py index 386c71a..fc27b98 100644 --- a/main/food/api_schema.py +++ b/main/food/api_schema.py @@ -65,6 +65,34 @@ HYDRATION_SETTINGS = {'type': 'object', 'properties': { 'hydration_beverage_rules': {'type': 'object', 'description': 'Optional beverage type rules with enabled and factor (0 to 1) keys.'}, }} +RECIPE = {'type': 'object', 'properties': { + 'title': {'type': 'string', 'maxLength': 180}, + 'description': {'type': 'string'}, 'instructions_markdown': {'type': 'string'}, + 'notes_markdown': {'type': 'string'}, 'category': {'type': 'string'}, + 'tags': {'type': 'array', 'items': {'type': 'string'}}, + 'default_servings': {'type': 'string', 'description': 'Positive decimal'}, + 'yield_amount': {'type': ['string', 'null']}, + 'yield_unit': {'type': ['string', 'null'], 'enum': ['g', 'ml', None]}, + 'preparation_minutes': {'type': 'integer', 'minimum': 0}, + 'cooking_minutes': {'type': 'integer', 'minimum': 0}, + 'status': {'type': 'string', 'enum': ['draft', 'published']}, + 'is_favourite': {'type': 'boolean'}, +}} +RECIPE_INGREDIENT = {'type': 'object', 'properties': { + 'name': {'type': 'string'}, 'quantity': {'type': 'string', 'description': 'Positive decimal'}, + 'unit': {'type': 'string', 'enum': ['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions']}, + 'amount_per_unit': {'type': ['string', 'null']}, + 'amount_per_unit_unit': {'type': ['string', 'null'], 'enum': ['g', 'ml', None]}, + 'inventory_product_id': {'type': ['string', 'null'], 'format': 'uuid'}, + 'nutrition_product_id': {'type': ['string', 'null'], 'format': 'uuid'}, + 'preparation_note': {'type': 'string'}, 'is_optional': {'type': 'boolean'}, + 'display_order': {'type': 'integer', 'minimum': 0}, +}} +RECIPE_ANALYSIS = {'type': 'object', 'properties': { + 'servings': {'type': 'string', 'description': 'Prepared servings; defaults to the recipe'}, + 'include_optional': {'type': 'boolean'}, + 'substitutions': {'type': 'object', 'additionalProperties': {'type': 'string'}}, +}} @require_GET @@ -114,16 +142,52 @@ def schema(request): 'get': operation('Read hydration settings', 'food:read'), 'patch': operation('Update hydration settings', 'food:write', HYDRATION_SETTINGS), }, + '/recipes/': {'get': operation('Search own recipes by query, category, and limit', 'food:read')}, + '/recipes/create/': {'post': operation('Create own recipe with optional Idempotency-Key', 'food:write', RECIPE)}, + '/recipes/{id}/': { + 'get': operation('Read own recipe with ingredients, subrecipes, and variations', 'food:read'), + 'patch': operation('Update own recipe', 'food:write', RECIPE), + 'delete': operation('Delete own recipe when no parent recipe uses it', 'food:write'), + }, + '/recipes/{id}/variations/': {'post': operation('Copy own recipe as an independent variation', 'food:write', + {'type': 'object', 'properties': {'title': {'type': 'string'}}})}, + '/recipes/{id}/ingredients/': {'post': operation('Add ingredient to own recipe', 'food:write', RECIPE_INGREDIENT)}, + '/recipes/{id}/ingredients/{item_id}/': { + 'patch': operation('Update own recipe ingredient', 'food:write', RECIPE_INGREDIENT), + 'delete': operation('Remove own recipe ingredient', 'food:write'), + }, + '/recipes/{id}/subrecipes/': {'post': operation('Attach an owned component recipe', 'food:write', + {'type': 'object', 'required': ['component_id'], 'properties': { + 'component_id': {'type': 'string', 'format': 'uuid'}, 'quantity': {'type': 'string'}, + 'unit': {'type': 'string'}, 'note': {'type': 'string'}, + 'display_order': {'type': 'integer'}}})}, + '/recipes/{id}/subrecipes/{item_id}/': {'delete': operation('Detach a component recipe', 'food:write')}, + '/recipes/{id}/stock/preview/': {'post': operation('Preview inventory and issue confirmation when stock is ready', + 'inventory:read', RECIPE_ANALYSIS)}, + '/recipes/{id}/stock/confirm/': {'post': operation('Deduct inventory using the exact preview confirmation', + 'inventory:write', {'type': 'object', 'required': ['confirmation'], 'properties': { + 'confirmation': {'type': 'string'}}})}, + '/recipes/stock-use/{id}/undo/': {'post': operation('Undo a safe recipe inventory deduction', 'inventory:write')}, + '/recipes/{id}/log/': {'post': operation('Log consumed recipe servings without deducting stock; requires Idempotency-Key', + 'food:write', {'type': 'object', 'required': ['consumed_servings', 'meal'], + 'properties': {**RECIPE_ANALYSIS['properties'], + 'consumed_servings': {'type': 'string'}, + 'meal': {'type': 'string', 'enum': ['breakfast', 'lunch', 'dinner', 'snacks']}, + 'date': {'type': 'string', 'format': 'date'}, 'time': {'type': 'string', 'format': 'time'}}})}, }, } for path, methods in document['paths'].items(): if '{id}' in path: methods['parameters'] = [{'name': 'id', 'in': 'path', 'required': True, 'schema': {'type': 'string', 'format': 'uuid'}}] + if '{item_id}' in path: + methods.setdefault('parameters', []).append({'name': 'item_id', 'in': 'path', 'required': True, + 'schema': {'type': 'integer', 'minimum': 1}}) if 'post' in methods: methods['post']['responses']['201'] = methods['post']['responses'].pop('200') for path in ('/kitchen/consumption/preview/', '/kitchen/consumption/', - '/kitchen/consumption/{id}/undo/'): + '/kitchen/consumption/{id}/undo/', '/recipes/{id}/stock/preview/', + '/recipes/{id}/stock/confirm/', '/recipes/stock-use/{id}/undo/'): document['paths'][path]['post']['responses']['200'] = document['paths'][path]['post']['responses'].pop('201') document['paths']['/food/today/']['get']['parameters'] = [{ 'name': 'date', 'in': 'query', 'required': False, @@ -145,6 +209,10 @@ def schema(request): 'name': 'Idempotency-Key', 'in': 'header', 'required': True, 'schema': {'type': 'string', 'maxLength': 128}, }] + document['paths']['/recipes/{id}/log/']['post']['parameters'] = [{ + 'name': 'Idempotency-Key', 'in': 'header', 'required': True, + 'schema': {'type': 'string', 'maxLength': 128}, + }] document['paths']['/food/attachments/{id}/file/']['get']['responses']['200'] = { 'description': 'Owned image bytes', 'content': {mime: {'schema': {'type': 'string', 'format': 'binary'}} diff --git a/main/food/api_urls.py b/main/food/api_urls.py index a7df4f1..3f71243 100644 --- a/main/food/api_urls.py +++ b/main/food/api_urls.py @@ -1,5 +1,6 @@ from django.urls import path from . import api, api_schema +from recipes import api as recipe_api urlpatterns = [ path('auth/whoami/', api.whoami), @@ -25,4 +26,16 @@ urlpatterns = [ path('hydration/manual/', api.hydration_log), path('hydration/manual//', api.hydration_manual_entry), path('hydration/settings/', api.hydration_settings), + path('recipes/', recipe_api.recipe_search), + path('recipes/create/', recipe_api.recipe_create), + path('recipes//', recipe_api.recipe_item), + path('recipes//variations/', recipe_api.recipe_variation), + path('recipes//ingredients/', recipe_api.recipe_ingredient_create), + path('recipes//ingredients//', recipe_api.recipe_ingredient_item), + path('recipes//subrecipes/', recipe_api.recipe_subrecipe_create), + path('recipes//subrecipes//', recipe_api.recipe_subrecipe_delete), + path('recipes//stock/preview/', recipe_api.recipe_stock_preview), + path('recipes//stock/confirm/', recipe_api.recipe_stock_confirm), + path('recipes/stock-use//undo/', recipe_api.recipe_stock_undo), + path('recipes//log/', recipe_api.recipe_log), ] diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index 9a8872a..38959d6 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -126,6 +126,69 @@ class HydrationSettingsUpdate(BaseModel): hydration_beverage_rules: dict[str, dict[str, Any]] | None = None +class RecipeInput(BaseModel): + title: str + description: str = '' + instructions_markdown: str = '' + notes_markdown: str = '' + preparation_minutes: int = Field(default=0, ge=0) + cooking_minutes: int = Field(default=0, ge=0) + default_servings: Decimal = Field(default=Decimal('2'), gt=0) + yield_amount: Decimal | None = Field(default=None, gt=0) + yield_unit: Literal['g', 'ml'] | None = None + category: str = '' + tags: list[str] = Field(default_factory=list) + status: Literal['draft', 'published'] = 'draft' + + +class RecipeChanges(BaseModel): + title: str | None = None + description: str | None = None + instructions_markdown: str | None = None + notes_markdown: str | None = None + preparation_minutes: int | None = Field(default=None, ge=0) + cooking_minutes: int | None = Field(default=None, ge=0) + default_servings: Decimal | None = Field(default=None, gt=0) + yield_amount: Decimal | None = Field(default=None, gt=0) + yield_unit: Literal['g', 'ml'] | None = None + category: str | None = None + tags: list[str] | None = None + status: Literal['draft', 'published'] | None = None + is_favourite: bool | None = None + + +class RecipeIngredientInput(BaseModel): + name: str + quantity: Decimal = Field(gt=0) + unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions'] + amount_per_unit: Decimal | None = Field(default=None, gt=0) + amount_per_unit_unit: Literal['g', 'ml'] | None = None + inventory_product_id: str | None = None + nutrition_product_id: str | None = None + preparation_note: str = '' + is_optional: bool = False + display_order: int = Field(default=0, ge=0) + + +class RecipeIngredientChanges(BaseModel): + name: str | None = None + quantity: Decimal | None = Field(default=None, gt=0) + unit: Literal['g', 'kg', 'ml', 'L', 'pieces', 'tsp', 'tbsp', 'portions'] | None = None + amount_per_unit: Decimal | None = Field(default=None, gt=0) + amount_per_unit_unit: Literal['g', 'ml'] | None = None + inventory_product_id: str | None = None + nutrition_product_id: str | None = None + preparation_note: str | None = None + is_optional: bool | None = None + display_order: int | None = Field(default=None, ge=0) + + +class RecipeAnalysisInput(BaseModel): + servings: Decimal | None = Field(default=None, gt=0) + include_optional: bool = False + substitutions: dict[str, str] = Field(default_factory=dict) + + def _token() -> str: access = get_access_token() if access is None: @@ -460,6 +523,106 @@ def create_server() -> MCPServer: return await api_request('PATCH', 'hydration/settings/', payload=changes.model_dump(mode='json', exclude_unset=True)) + @server.tool(structured_output=True, description='Search your own recipes by title, description, or ingredient name. Returns recipe IDs and summaries; read only.') + async def recipe_search(query: str = '', category: str = '', limit: int = 20) -> dict[str, Any]: + return await api_request('GET', 'recipes/', params={'query': query, 'category': category, 'limit': limit}) + + @server.tool(structured_output=True, description='Read one owned recipe with Markdown instructions, ingredients, substitutions, related variations, and subrecipes. Read only.') + async def recipe_get(recipe_id: str) -> dict[str, Any]: + return await api_request('GET', f'recipes/{recipe_id}/') + + @server.tool(structured_output=True, description='Create an owned recipe. Add measured ingredients with recipe_ingredient_add. Reuse idempotency_key on retries.') + async def recipe_create(recipe: RecipeInput, idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', 'recipes/create/', + payload=recipe.model_dump(mode='json', exclude_none=True), idempotency_key=key) + return {'recipe': data, 'idempotency_key': key} + + @server.tool(structured_output=True, description='Update supplied fields of one owned recipe, including Markdown and serving yield. Existing variations remain independent.') + async def recipe_update(recipe_id: str, changes: RecipeChanges) -> dict[str, Any]: + return await api_request('PATCH', f'recipes/{recipe_id}/', + payload=changes.model_dump(mode='json', exclude_unset=True)) + + @server.tool(structured_output=True, description='Delete one owned recipe and its ingredients. Existing Food Diary nutrition snapshots remain unchanged. Require clear user intent.') + async def recipe_delete(recipe_id: str) -> dict[str, Any]: + return await api_request('DELETE', f'recipes/{recipe_id}/') + + @server.tool(structured_output=True, description='Create an independently editable copy linked as a variation of the owned recipe. Copies ingredients, substitutions, and subrecipes. Reuse idempotency_key on retries.') + async def recipe_create_variation(recipe_id: str, title: str | None = None, + idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', f'recipes/{recipe_id}/variations/', + payload={'title': title} if title else {}, idempotency_key=key) + return {'recipe': data, 'idempotency_key': key} + + @server.tool(structured_output=True, description='Add a measured ingredient to one owned recipe. Use owned food product IDs for unambiguous stock and nutrition matching.') + async def recipe_ingredient_add(recipe_id: str, ingredient: RecipeIngredientInput, + idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', f'recipes/{recipe_id}/ingredients/', + payload=ingredient.model_dump(mode='json', exclude_none=True), idempotency_key=key) + return {'ingredient': data, 'idempotency_key': key} + + @server.tool(structured_output=True, description='Correct only the supplied fields of an ingredient in an owned recipe.') + async def recipe_ingredient_update(recipe_id: str, ingredient_id: int, + changes: RecipeIngredientChanges) -> dict[str, Any]: + return await api_request('PATCH', f'recipes/{recipe_id}/ingredients/{ingredient_id}/', + payload=changes.model_dump(mode='json', exclude_unset=True)) + + @server.tool(structured_output=True, description='Remove one ingredient from an owned recipe. Require clear user intent.') + async def recipe_ingredient_delete(recipe_id: str, ingredient_id: int) -> dict[str, Any]: + return await api_request('DELETE', f'recipes/{recipe_id}/ingredients/{ingredient_id}/') + + @server.tool(structured_output=True, description='Attach another owned recipe as a reusable subrecipe. Cycles and cross-user references are rejected. Reuse idempotency_key on retries.') + async def recipe_subrecipe_add(recipe_id: str, component_id: str, + quantity: Decimal = Decimal('1'), + unit: Literal['servings', 'g', 'ml'] = 'servings', + note: str = '', idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + data = await api_request('POST', f'recipes/{recipe_id}/subrecipes/', + payload={'component_id': component_id, 'quantity': str(quantity), + 'unit': unit, 'note': note}, idempotency_key=key) + return {'subrecipe': data, 'idempotency_key': key} + + @server.tool(structured_output=True, description='Remove one reusable subrecipe link from an owned recipe; the component recipe remains.') + async def recipe_subrecipe_remove(recipe_id: str, subrecipe_id: int) -> dict[str, Any]: + return await api_request('DELETE', f'recipes/{recipe_id}/subrecipes/{subrecipe_id}/') + + @server.tool(structured_output=True, description='Check scaled ingredient availability and nutrition, with exact package deductions. Read only. If ready, returns a short-lived confirmation token for explicit inventory deduction.') + async def recipe_check_inventory(recipe_id: str, options: RecipeAnalysisInput = None) -> dict[str, Any]: + return await api_request('POST', f'recipes/{recipe_id}/stock/preview/', + payload=(options or RecipeAnalysisInput()).model_dump(mode='json')) + + @server.tool(structured_output=True, description='Deduct the exact recipe packages approved in a recent recipe_check_inventory preview. Requires the user’s explicit approval and the returned confirmation token. Replays of the same token do not double count.') + async def recipe_deduct_inventory(recipe_id: str, confirmation: str) -> dict[str, Any]: + return await api_request('POST', f'recipes/{recipe_id}/stock/confirm/', + payload={'confirmation': confirmation}) + + @server.tool(structured_output=True, description='Undo a confirmed recipe inventory deduction when the affected packages have not changed since. Does not remove Food Diary entries.') + async def recipe_undo_inventory(stock_use_id: str) -> dict[str, Any]: + return await api_request('POST', f'recipes/stock-use/{stock_use_id}/undo/', payload={}) + + @server.tool(structured_output=True, description='Log a personally consumed portion of an owned recipe to Food Diary using a historical nutrition snapshot. This never deducts inventory. Specify prepared and consumed servings separately; reuse idempotency_key on retries.') + async def recipe_log_meal(recipe_id: str, consumed_servings: Decimal, + meal: Literal['breakfast', 'lunch', 'dinner', 'snacks'], + servings: Decimal | None = None, date: str | None = None, + time: str | None = None, include_optional: bool = False, + substitutions: dict[str, str] | None = None, + idempotency_key: str | None = None) -> dict[str, Any]: + key = _key(idempotency_key) + payload = {'consumed_servings': str(consumed_servings), 'meal': meal, + 'include_optional': include_optional, + 'substitutions': substitutions or {}} + if servings is not None: + payload['servings'] = str(servings) + if date is not None: + payload['date'] = date + if time is not None: + payload['time'] = time + data = await api_request('POST', f'recipes/{recipe_id}/log/', + payload=payload, idempotency_key=key) + return {**data, 'idempotency_key': key} + return server diff --git a/main/mcp_server/tests.py b/main/mcp_server/tests.py index e847f6b..b818b39 100644 --- a/main/mcp_server/tests.py +++ b/main/mcp_server/tests.py @@ -26,6 +26,7 @@ from oauth2_provider.models import Application from food.api import create_token from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem from planner.timezones import localdate_for_user +from recipes.models import Recipe, RecipeUse from .server import ClientImageFile, _allowed_file_host, _resolve_image @@ -211,7 +212,7 @@ class McpHttpTests(LiveServerTestCase): async def check(client): names = {tool.name for tool in (await client.list_tools()).tools} - self.assertEqual(len(names), 26) + self.assertEqual(len(names), 41) self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product', 'inventory_import_groceries'} <= names) today = (await client.call_tool('food_get_today')).structured_content @@ -323,3 +324,87 @@ class McpHttpTests(LiveServerTestCase): 'transaction_id': used['transaction_id']})).structured_content self.assertEqual(undone['reverses'], used['transaction_id']) asyncio.run(self._client(self.secret, check)) + + def test_recipe_tools_end_to_end_with_separate_stock_and_meal_actions(self): + location = InventoryLocation.objects.create(user=self.a, name='Recipe pantry') + package = KitchenInventoryItem.objects.create( + user=self.a, product=self.a_product, location=location, + original_amount=Decimal('300'), remaining_amount=Decimal('300'), inventory_unit='g') + + async def check(client): + created = await client.call_tool('recipe_create', {'recipe': { + 'title': 'Pasta supper', 'default_servings': '2', + 'instructions_markdown': 'Cook pasta.'}, 'idempotency_key': 'recipe-supper'}) + self.assertFalse(created.is_error, created) + recipe_id = created.structured_content['recipe']['id'] + again = (await client.call_tool('recipe_create', {'recipe': { + 'title': 'Pasta supper', 'default_servings': '2', + 'instructions_markdown': 'Cook pasta.'}, 'idempotency_key': 'recipe-supper'})).structured_content + self.assertEqual(again['recipe']['id'], recipe_id) + self.assertEqual((await client.call_tool('recipe_search', + {'query': 'Pasta supper'})).structured_content['count'], 1) + ingredient = (await client.call_tool('recipe_ingredient_add', {'recipe_id': recipe_id, + 'ingredient': {'name': 'Pasta', 'quantity': '200', 'unit': 'g', + 'inventory_product_id': str(self.a_product.api_id), + 'nutrition_product_id': str(self.a_product.api_id)}, + 'idempotency_key': 'recipe-pasta-ingredient'})).structured_content['ingredient'] + self.assertEqual(ingredient['name'], 'Pasta') + self.assertEqual((await client.call_tool('recipe_get', + {'recipe_id': recipe_id})).structured_content['ingredients'][0]['id'], ingredient['id']) + self.assertFalse((await client.call_tool('recipe_ingredient_update', { + 'recipe_id': recipe_id, 'ingredient_id': ingredient['id'], + 'changes': {'quantity': '150'}})).is_error) + variation = (await client.call_tool('recipe_create_variation', { + 'recipe_id': recipe_id, 'title': 'Spicy pasta', + 'idempotency_key': 'recipe-spicy'})).structured_content['recipe'] + self.assertEqual(variation['parent_id'], recipe_id) + self.assertEqual(variation['ingredients'][0]['quantity'], '150.000') + component = (await client.call_tool('recipe_create', { + 'recipe': {'title': 'Pasta topping'}, 'idempotency_key': 'recipe-topping'})).structured_content['recipe'] + attached = (await client.call_tool('recipe_subrecipe_add', { + 'recipe_id': recipe_id, 'component_id': component['id'], + 'idempotency_key': 'recipe-attach-topping'})).structured_content['subrecipe'] + self.assertEqual(attached['component_id'], component['id']) + self.assertTrue((await client.call_tool('recipe_subrecipe_add', { + 'recipe_id': component['id'], 'component_id': recipe_id})).is_error) + self.assertFalse((await client.call_tool('recipe_subrecipe_remove', { + 'recipe_id': recipe_id, 'subrecipe_id': attached['id']})).is_error) + preview = (await client.call_tool('recipe_check_inventory', { + 'recipe_id': recipe_id})).structured_content + self.assertTrue(preview['stock_ready']) + self.assertEqual(preview['products'][0]['deductions'][0]['amount'], '150.000') + stock = (await client.call_tool('recipe_deduct_inventory', { + 'recipe_id': recipe_id, 'confirmation': preview['confirmation']})).structured_content + self.assertTrue(stock['created']) + replay = (await client.call_tool('recipe_deduct_inventory', { + 'recipe_id': recipe_id, 'confirmation': preview['confirmation']})).structured_content + self.assertFalse(replay['created']) + logged = (await client.call_tool('recipe_log_meal', {'recipe_id': recipe_id, + 'consumed_servings': '0.5', 'servings': '2', 'meal': 'dinner', + 'idempotency_key': 'recipe-meal-supper'})).structured_content + self.assertEqual(logged['nutrition']['calories_kcal'], '131.250') + again = (await client.call_tool('recipe_log_meal', {'recipe_id': recipe_id, + 'consumed_servings': '0.5', 'servings': '2', 'meal': 'dinner', + 'idempotency_key': 'recipe-meal-supper'})).structured_content + self.assertEqual(again['entry_id'], logged['entry_id']) + self.assertFalse((await client.call_tool('recipe_update', {'recipe_id': recipe_id, + 'changes': {'title': 'Updated supper'}})).is_error) + self.assertFalse((await client.call_tool('recipe_undo_inventory', { + 'stock_use_id': stock['stock_use_id']})).is_error) + self.assertFalse((await client.call_tool('recipe_ingredient_delete', { + 'recipe_id': recipe_id, 'ingredient_id': ingredient['id']})).is_error) + self.assertFalse((await client.call_tool('recipe_delete', { + 'recipe_id': component['id']})).is_error) + self.assertFalse((await client.call_tool('recipe_delete', { + 'recipe_id': recipe_id})).is_error) + return recipe_id, logged['entry_id'] + + recipe_id, entry_id = asyncio.run(self._client(self.secret, check)) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('300')) + self.assertEqual(RecipeUse.objects.count(), 1) + self.assertEqual(FoodLogEntry.objects.get(api_id=entry_id).product_name_snapshot, 'Pasta supper') + async def isolated(client): + self.assertTrue((await client.call_tool('recipe_get', {'recipe_id': recipe_id})).is_error) + self.assertTrue((await client.call_tool('recipe_check_inventory', {'recipe_id': recipe_id})).is_error) + asyncio.run(self._client(self.b_secret, isolated)) diff --git a/main/recipes/api.py b/main/recipes/api.py new file mode 100644 index 0000000..2c29600 --- /dev/null +++ b/main/recipes/api.py @@ -0,0 +1,381 @@ +"""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 Recipe, RecipeIngredient, RecipeSubrecipe, RecipeUse +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, '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()]) + return data + + +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.') + return JsonResponse({'count': recipes.count(), 'recipes': [_summary(item) for item in recipes[:limit]]}) + + +@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) + + +@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': + 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) diff --git a/main/recipes/services/variations.py b/main/recipes/services/variations.py new file mode 100644 index 0000000..897101a --- /dev/null +++ b/main/recipes/services/variations.py @@ -0,0 +1,38 @@ +"""Create an independent variation from one owned recipe.""" + +from django.db import transaction + +from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution, + RecipeSubrecipe) + + +@transaction.atomic +def create_variation(user, parent, title=None): + if parent.owner_id != user.pk: + raise ValueError('Recipe not found.') + variation = Recipe.objects.create( + owner=user, parent=parent, title=title or f'{parent.title[:160]} variation', + description=parent.description, instructions_markdown=parent.instructions_markdown, + notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes, + cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings, + yield_amount=parent.yield_amount, yield_unit=parent.yield_unit, + category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT) + for item in parent.ingredients.select_related('inventory_product', 'nutrition_product').prefetch_related('substitutions'): + copied = RecipeIngredient.objects.create( + recipe=variation, name=item.name, quantity=item.quantity, unit=item.unit, + amount_per_unit=item.amount_per_unit, amount_per_unit_unit=item.amount_per_unit_unit, + display_order=item.display_order, inventory_product=item.inventory_product, + nutrition_product=item.nutrition_product, preparation_note=item.preparation_note, + is_optional=item.is_optional) + RecipeIngredientSubstitution.objects.bulk_create([ + RecipeIngredientSubstitution( + ingredient=copied, name=alternative.name, quantity=alternative.quantity, + unit=alternative.unit, amount_per_unit=alternative.amount_per_unit, + amount_per_unit_unit=alternative.amount_per_unit_unit, + product=alternative.product, display_order=alternative.display_order) + for alternative in item.substitutions.all()]) + RecipeSubrecipe.objects.bulk_create([ + RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity, + unit=item.unit, display_order=item.display_order, note=item.note) + for item in parent.subrecipes.all()]) + return variation diff --git a/main/recipes/test_api.py b/main/recipes/test_api.py new file mode 100644 index 0000000..5e540bd --- /dev/null +++ b/main/recipes/test_api.py @@ -0,0 +1,168 @@ +import json +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import TestCase + +from food.api import create_token +from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem +from recipes.models import (Recipe, RecipeIngredient, RecipeIngredientSubstitution, + RecipeSubrecipe, RecipeUse) + + +class RecipeApiTests(TestCase): + def setUp(self): + users = get_user_model() + self.user = users.objects.create_user('recipe-api-owner') + self.other = users.objects.create_user('recipe-api-other') + _, self.secret = create_token(self.user, 'Recipe API', + ['food:read', 'food:write', 'inventory:read', 'inventory:write']) + _, self.food_read = create_token(self.user, 'Recipe read', ['food:read']) + _, self.stock_read = create_token(self.user, 'Stock read', ['inventory:read']) + self.product = FoodProduct.objects.create(owner=self.user, product_name='Oats', + energy_kcal_100=Decimal('400'), protein_100=Decimal('10'), + carbohydrates_100=Decimal('60'), fat_100=Decimal('5'), fibre_100=Decimal('8')) + self.other_product = FoodProduct.objects.create(owner=self.other, product_name='Private oats') + self.other_recipe = Recipe.objects.create(owner=self.other, title='Private recipe') + location = InventoryLocation.objects.create(user=self.user, name='Pantry') + self.package = KitchenInventoryItem.objects.create(user=self.user, product=self.product, + location=location, original_amount=Decimal('300'), + remaining_amount=Decimal('300'), inventory_unit='g') + + def call(self, method, path, data=None, token=None, key=None): + headers = {'HTTP_AUTHORIZATION': f'Bearer {token or self.secret}'} + if key: + headers['HTTP_IDEMPOTENCY_KEY'] = key + if data is not None: + headers['content_type'] = 'application/json' + data = json.dumps(data) + return getattr(self.client, method)(f'/api/v1/{path}', data=data, **headers) + + def create(self): + response = self.call('post', 'recipes/create/', + {'title': 'Oat bowl', 'default_servings': '2', + 'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl') + self.assertEqual(response.status_code, 201, response.content) + return response.json()['id'] + + def test_recipe_crud_variation_and_scopes(self): + recipe_id = self.create() + repeat = self.call('post', 'recipes/create/', + {'title': 'Oat bowl', 'default_servings': '2', + 'instructions_markdown': 'Mix oats.'}, key='create-oat-bowl') + self.assertEqual(repeat.status_code, 200) + self.assertEqual(repeat.json()['id'], recipe_id) + self.assertEqual(self.call('post', 'recipes/create/', + {'title': 'Other'}, key='create-oat-bowl').status_code, 409) + self.assertEqual(self.call('get', 'recipes/?query=Oat').json()['count'], 1) + self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['title'], 'Oat bowl') + self.assertEqual(self.call('patch', f'recipes/{recipe_id}/', + {'title': 'Updated bowl', 'instructions_markdown': 'Toast oats.'}).json()['title'], 'Updated bowl') + self.assertEqual(self.call('patch', f'recipes/{recipe_id}/', + {'title': 'No write'}, token=self.food_read).status_code, 403) + self.assertEqual(self.call('get', f'recipes/{recipe_id}/', token=self.stock_read).status_code, 403) + self.assertEqual(self.call('get', f'recipes/{self.other_recipe.api_id}/').status_code, 404) + self.assertEqual(self.call('patch', f'recipes/{self.other_recipe.api_id}/', + {'title': 'Stolen'}).status_code, 404) + variation = self.call('post', f'recipes/{recipe_id}/variations/', + {'title': 'Spicy bowl'}, key='variation-1') + self.assertEqual(variation.status_code, 201, variation.content) + variation_id = variation.json()['id'] + self.assertEqual(variation.json()['parent_id'], recipe_id) + self.assertEqual(self.call('get', f'recipes/{recipe_id}/').json()['variations'][0]['id'], variation_id) + self.assertEqual(self.call('delete', f'recipes/{recipe_id}/').status_code, 200) + self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['parent_id'], None) + + def test_ingredients_subrecipes_ownership_cycle_and_independent_variation(self): + recipe_id = self.create() + ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g', + 'inventory_product_id': str(self.product.api_id), + 'nutrition_product_id': str(self.product.api_id)} + created = self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient, key='oats-ingredient') + self.assertEqual(created.status_code, 201, created.content) + item_id = created.json()['id'] + self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient, + key='oats-ingredient').json()['id'], item_id) + self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', + {**ingredient, 'inventory_product_id': str(self.other_product.api_id)}).status_code, 400) + self.assertEqual(self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/', + {'quantity': '150'}).json()['quantity'], '150') + RecipeIngredientSubstitution.objects.create( + ingredient=RecipeIngredient.objects.get(pk=item_id), name='Buckwheat', + quantity=Decimal('150'), unit='g', product=self.product) + variation = self.call('post', f'recipes/{recipe_id}/variations/', {}, key='var-with-oats').json() + variation_id = variation['id'] + self.assertEqual(variation['ingredients'][0]['quantity'], '150.000') + self.assertEqual(variation['ingredients'][0]['substitutions'][0]['name'], 'Buckwheat') + self.call('patch', f'recipes/{recipe_id}/ingredients/{item_id}/', {'quantity': '100'}) + self.assertEqual(self.call('get', f'recipes/{variation_id}/').json()['ingredients'][0]['quantity'], '150.000') + component = self.call('post', 'recipes/create/', {'title': 'Topping'}, key='topping').json()['id'] + link = self.call('post', f'recipes/{recipe_id}/subrecipes/', + {'component_id': component, 'quantity': '1', 'unit': 'servings'}, key='link-topping') + self.assertEqual(link.status_code, 201, link.content) + self.assertEqual(self.call('post', f'recipes/{component}/subrecipes/', + {'component_id': recipe_id}).status_code, 400) + self.assertEqual(self.call('post', f'recipes/{recipe_id}/subrecipes/', + {'component_id': str(self.other_recipe.api_id)}).status_code, 404) + self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 409) + self.assertEqual(self.call('delete', f'recipes/{recipe_id}/subrecipes/{link.json()["id"]}/').status_code, 200) + self.assertEqual(self.call('delete', f'recipes/{component}/').status_code, 200) + self.assertEqual(self.call('delete', f'recipes/{recipe_id}/ingredients/{item_id}/').status_code, 200) + + def test_inventory_preview_confirm_replay_undo_and_recipe_log_snapshot(self): + recipe_id = self.create() + ingredient = {'name': 'Oats', 'quantity': '200', 'unit': 'g', + 'inventory_product_id': str(self.product.api_id), + 'nutrition_product_id': str(self.product.api_id)} + self.assertEqual(self.call('post', f'recipes/{recipe_id}/ingredients/', ingredient).status_code, 201) + preview = self.call('post', f'recipes/{recipe_id}/stock/preview/', + {'servings': '2'}, token=self.stock_read) + self.assertEqual(preview.status_code, 200, preview.content) + self.assertTrue(preview.json()['stock_ready']) + self.assertEqual(preview.json()['products'][0]['deductions'][0]['amount'], '200.000') + self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/', + {'confirmation': preview.json()['confirmation']}, token=self.stock_read).status_code, 403) + confirmation = {'confirmation': preview.json()['confirmation']} + confirmed = self.call('post', f'recipes/{recipe_id}/stock/confirm/', confirmation) + self.assertEqual(confirmed.status_code, 200, confirmed.content) + self.assertTrue(confirmed.json()['created']) + self.assertFalse(self.call('post', f'recipes/{recipe_id}/stock/confirm/', + confirmation).json()['created']) + self.package.refresh_from_db() + self.assertEqual(self.package.remaining_amount, Decimal('100')) + self.assertEqual(RecipeUse.objects.count(), 1) + logged = self.call('post', f'recipes/{recipe_id}/log/', + {'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner', + 'date': '2026-10-12'}, key='recipe-meal-1') + self.assertEqual(logged.status_code, 201, logged.content) + self.assertEqual(logged.json()['nutrition']['calories_kcal'], '200.000') + self.assertFalse(logged.json()['stock_deducted']) + self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/', + {'servings': '2', 'consumed_servings': '0.5', 'meal': 'dinner', + 'date': '2026-10-12'}, key='recipe-meal-1').status_code, 200) + self.assertEqual(FoodLogEntry.objects.count(), 1) + self.call('patch', f'recipes/{recipe_id}/', {'title': 'Edited bowl'}) + entry = FoodLogEntry.objects.get() + self.assertEqual((entry.product_name_snapshot, entry.calories_kcal), + ('Oat bowl', Decimal('200'))) + self.assertEqual(self.call('post', f'recipes/stock-use/{confirmed.json()["stock_use_id"]}/undo/', + {}).status_code, 200) + self.package.refresh_from_db() + self.assertEqual(self.package.remaining_amount, Decimal('300')) + self.assertEqual(FoodLogEntry.objects.count(), 1) + self.assertEqual(self.call('post', f'recipes/{recipe_id}/stock/confirm/', + {'confirmation': 'invalid'}).status_code, 400) + + def test_missing_stock_blocks_confirmation_but_not_meal(self): + recipe_id = self.create() + self.call('post', f'recipes/{recipe_id}/ingredients/', + {'name': 'Oats', 'quantity': '400', 'unit': 'g', + 'nutrition_product_id': str(self.product.api_id), + 'inventory_product_id': str(self.product.api_id)}) + preview = self.call('post', f'recipes/{recipe_id}/stock/preview/', {}).json() + self.assertFalse(preview['stock_ready']) + self.assertIsNone(preview['confirmation']) + self.assertEqual(self.call('post', f'recipes/{recipe_id}/log/', + {'consumed_servings': '1', 'meal': 'lunch'}, key='meal-with-shortage').status_code, 201) + self.package.refresh_from_db() + self.assertEqual(self.package.remaining_amount, Decimal('300')) diff --git a/main/recipes/views.py b/main/recipes/views.py index 0ca632d..70dce13 100644 --- a/main/recipes/views.py +++ b/main/recipes/views.py @@ -20,6 +20,7 @@ from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, Reci from .services.analysis import AnalysisError, analyze from .services.cooking import CookingError, complete, instruction_steps, make_completion from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use +from .services.variations import create_variation as clone_variation def _owned(user): @@ -363,30 +364,7 @@ def autosave_new(request): def create_variation(request, identifier): parent = get_object_or_404(_owned(request.user).prefetch_related('ingredients', 'subrecipes'), api_id=identifier) - with transaction.atomic(): - variation = Recipe.objects.create( - owner=request.user, parent=parent, title=f'{parent.title[:160]} variation', - description=parent.description, instructions_markdown=parent.instructions_markdown, - notes_markdown=parent.notes_markdown, preparation_minutes=parent.preparation_minutes, - cooking_minutes=parent.cooking_minutes, default_servings=parent.default_servings, - yield_amount=parent.yield_amount, yield_unit=parent.yield_unit, - category=parent.category, tags=list(parent.tags), status=Recipe.Status.DRAFT, - ) - RecipeIngredient.objects.bulk_create([ - RecipeIngredient(recipe=variation, name=item.name, quantity=item.quantity, - unit=item.unit, amount_per_unit=item.amount_per_unit, - amount_per_unit_unit=item.amount_per_unit_unit, - display_order=item.display_order, - inventory_product=item.inventory_product, - nutrition_product=item.nutrition_product, - preparation_note=item.preparation_note, is_optional=item.is_optional) - for item in parent.ingredients.all() - ]) - RecipeSubrecipe.objects.bulk_create([ - RecipeSubrecipe(recipe=variation, component=item.component, quantity=item.quantity, - unit=item.unit, display_order=item.display_order, note=item.note) - for item in parent.subrecipes.all() - ]) + variation = clone_variation(request.user, parent) messages.success(request, 'Variation created. Edit it to make it your own.') return redirect('recipes:edit', identifier=variation.api_id)