from decimal import Decimal from unittest.mock import patch from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from food.models import (FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem) from food.services.inventory_consumption import StockError, consume as inventory_consume from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse from .services.analysis import analyze, physical_amount from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use class RecipeStockTests(TestCase): def setUp(self): users = get_user_model() self.user = users.objects.create_user(username='recipe-stock-owner') self.other = users.objects.create_user(username='recipe-stock-other') self.client.force_login(self.user) self.location = InventoryLocation.objects.create(user=self.user, name='Pantry') self.butter = FoodProduct.objects.create( owner=self.user, product_name='Butter', base_unit='g', energy_kcal_100=Decimal('700'), carbohydrates_100=Decimal('1'), protein_100=Decimal('1'), fat_100=Decimal('80'), fibre_100=Decimal('0')) self.recipe = Recipe.objects.create(owner=self.user, title='Butter noodles', default_servings=2) def package(self, product=None, amount='250', remaining=None, unit='g', opened=False): amount = Decimal(amount) return KitchenInventoryItem.objects.create( user=self.user, product=product or self.butter, location=self.location, original_amount=amount, remaining_amount=Decimal(remaining) if remaining is not None else amount, inventory_unit=unit, opened=opened) def ingredient(self, recipe=None, name='Butter', quantity='150', unit='g', product=None, **kwargs): return RecipeIngredient.objects.create( recipe=recipe or self.recipe, name=name, quantity=Decimal(quantity), unit=unit, inventory_product=product or self.butter, nutrition_product=product or self.butter, **kwargs) def test_scaling_nutrition_cross_package_confirmation_retry_and_undo(self): self.ingredient(quantity='150') self.ingredient(name='Extra butter', quantity='50') opened = self.package(amount='250', remaining='100', opened=True) unopened = self.package() result = analyze(self.recipe, self.user, '2') self.assertTrue(result['stock_ready']) self.assertEqual(result['groups'][0]['stock_amount'], Decimal('200')) self.assertEqual(result['nutrition']['calories_kcal']['total'], Decimal('1400')) self.assertEqual(result['nutrition']['calories_kcal']['per_serving'], Decimal('700')) self.assertEqual(result['nutrition']['fibre_g']['total'], Decimal('0')) self.assertEqual([row['amount'] for row in result['groups'][0]['plan']['deductions']], [Decimal('100'), Decimal('100')]) opened.refresh_from_db(); unopened.refresh_from_db() self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('100'), Decimal('250'))) token = make_confirmation(result) operation, created = confirm(self.user, self.recipe, token) self.assertTrue(created) self.assertEqual(operation.lines.count(), 1) opened.refresh_from_db(); unopened.refresh_from_db() self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('0'), Decimal('150'))) self.assertTrue(opened.archived_at) repeat, created = confirm(self.user, self.recipe, token) self.assertFalse(created) self.assertEqual(repeat.pk, operation.pk) self.assertEqual(InventoryConsumption.objects.filter(user=self.user, reverses__isnull=True).count(), 1) self.assertTrue(reverse_use(self.user, operation.pk)[1]) self.assertFalse(reverse_use(self.user, operation.pk)[1]) opened.refresh_from_db(); unopened.refresh_from_db() self.assertEqual((opened.remaining_amount, unopened.remaining_amount), (Decimal('100'), Decimal('250'))) def test_shortage_and_unknown_match_block_consumption(self): self.ingredient() self.package(amount='100') result = analyze(self.recipe, self.user, '2') self.assertFalse(result['stock_ready']) self.assertEqual(result['groups'][0]['status'], 'partial') self.assertEqual(result['groups'][0]['plan']['shortage'], Decimal('50')) with self.assertRaises(RecipeStockError): confirm(self.user, self.recipe, make_confirmation(result)) self.assertFalse(RecipeUse.objects.exists()) self.assertEqual(KitchenInventoryItem.objects.get().remaining_amount, Decimal('100')) RecipeIngredient.objects.create(recipe=self.recipe, name='Unmatched', quantity=1, unit='g') result = analyze(self.recipe, self.user, '2') self.assertEqual(result['lines'][-1]['status'], 'unknown') self.assertFalse(result['nutrition']['protein_g']['complete']) self.assertEqual(result['nutrition']['protein_g']['total'], Decimal('1.5')) def test_metric_count_and_explicit_measure_conversions(self): self.ingredient(quantity='.2', unit='kg') self.package(amount='250') milk = FoodProduct.objects.create(owner=self.user, product_name='Milk', base_unit='ml', protein_100=Decimal('3')) self.ingredient(name='Milk', quantity='.25', unit='L', product=milk) carton = self.package(product=milk, amount='1', unit='L') self.ingredient(name='Butter spoon', quantity='2', unit='tbsp', amount_per_unit=Decimal('10'), amount_per_unit_unit='g') result = analyze(self.recipe, self.user, '2') self.assertTrue(result['stock_ready']) self.assertEqual([(group['product'].product_name, group['stock_amount'], group['unit']) for group in result['groups']], [('Butter', Decimal('220'), 'g'), ('Milk', Decimal('250'), 'ml')]) self.assertEqual(result['nutrition']['protein_g']['total'], Decimal('9.7')) confirm(self.user, self.recipe, make_confirmation(result)) carton.refresh_from_db() self.assertEqual(carton.remaining_amount, Decimal('.750')) self.assertEqual(physical_amount(Decimal(2), 'pieces'), (Decimal(2), 'pieces')) self.assertEqual(physical_amount(Decimal(2), 'tsp'), (None, None)) def test_nested_subrecipe_counts_direct_ingredients_once_and_uses_yield(self): self.package(amount='250') self.ingredient(quantity='50') sauce = Recipe.objects.create(owner=self.user, title='Sauce', default_servings=2, yield_amount=Decimal('200'), yield_unit='g') self.ingredient(recipe=sauce, quantity='100') RecipeSubrecipe.objects.create(recipe=self.recipe, component=sauce, quantity=Decimal('50'), unit='g') result = analyze(self.recipe, self.user, '2') self.assertEqual(result['groups'][0]['stock_amount'], Decimal('75')) self.assertEqual(result['nutrition']['fat_g']['total'], Decimal('60')) self.assertEqual(len(result['lines']), 2) self.assertTrue(result['stock_ready']) sauce.yield_amount = None sauce.yield_unit = '' sauce.save() incomplete = analyze(self.recipe, self.user, '2') self.assertFalse(incomplete['stock_ready']) self.assertFalse(incomplete['nutrition']['fat_g']['complete']) def test_fractional_counts_and_ambiguous_names_are_unknown(self): self.package(amount='6', unit='pieces') item = self.ingredient(quantity='1', unit='pieces') result = analyze(self.recipe, self.user, '1') self.assertFalse(result['stock_ready']) self.assertEqual(result['lines'][0]['status'], 'unknown') item.delete() FoodProduct.objects.create(owner=self.user, product_name='Butter') RecipeIngredient.objects.create(recipe=self.recipe, name='Butter', quantity=1, unit='g') result = analyze(self.recipe, self.user, '2') self.assertEqual(result['lines'][0]['status'], 'unknown') def test_substitution_changes_stock_and_nutrition_without_mutating_recipe(self): original = self.ingredient() oil = FoodProduct.objects.create(owner=self.user, product_name='Olive oil', base_unit='g', fat_100=Decimal('100')) alternative = RecipeIngredientSubstitution.objects.create( ingredient=original, name='Olive oil', quantity=Decimal('100'), unit='g', product=oil) self.package(product=oil, amount='200') default = analyze(self.recipe, self.user, '2') self.assertFalse(default['stock_ready']) selected = analyze(self.recipe, self.user, '2', substitutions={str(original.pk): str(alternative.pk)}) self.assertTrue(selected['stock_ready']) self.assertEqual(selected['nutrition']['fat_g']['total'], Decimal('100')) self.assertEqual(original.quantity, Decimal('150')) self.assertEqual(selected['groups'][0]['product'], oil) def test_stale_preview_and_multi_product_failure_leave_stock_unchanged(self): self.ingredient(quantity='50') butter_package = self.package(amount='100') milk = FoodProduct.objects.create(owner=self.user, product_name='Milk', base_unit='ml') self.ingredient(name='Milk', quantity='100', unit='ml', product=milk) milk_package = self.package(product=milk, amount='200', unit='ml') result = analyze(self.recipe, self.user, '2') token = make_confirmation(result) inventory_consume(self.user, milk, 10, 'ml') with self.assertRaises(RecipeStockError): confirm(self.user, self.recipe, token) butter_package.refresh_from_db() self.assertEqual(butter_package.remaining_amount, Decimal('100')) fresh = analyze(self.recipe, self.user, '2') def fail_second(user, product, amount, unit, **kwargs): if product.pk == milk.pk: raise StockError('Injected second-product failure.') return inventory_consume(user, product, amount, unit, **kwargs) with patch('recipes.services.stock_use.consume', side_effect=fail_second): with self.assertRaises(RecipeStockError): confirm(self.user, self.recipe, make_confirmation(fresh)) butter_package.refresh_from_db(); milk_package.refresh_from_db() self.assertEqual(butter_package.remaining_amount, Decimal('100')) self.assertEqual(milk_package.remaining_amount, Decimal('190')) self.assertFalse(RecipeUse.objects.exists()) def test_web_preview_requires_explicit_confirm_and_respects_owner(self): self.ingredient(quantity='50') package = self.package(amount='100') preview_url = reverse('recipes:stock-preview', args=[self.recipe.api_id]) response = self.client.get(preview_url) self.assertEqual(response.status_code, 200) self.assertContains(response, 'Confirm and deduct stock') package.refresh_from_db() self.assertEqual(package.remaining_amount, Decimal('100')) token = response.context['confirmation'] confirm_url = reverse('recipes:stock-confirm', args=[self.recipe.api_id]) self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 302) package.refresh_from_db() self.assertEqual(package.remaining_amount, Decimal('50')) self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 302) package.refresh_from_db() self.assertEqual(package.remaining_amount, Decimal('50')) self.client.force_login(self.other) self.assertEqual(self.client.get(preview_url).status_code, 404) self.assertEqual(self.client.post(confirm_url, {'confirmation': token}).status_code, 404)