Recipes phase 3
This commit is contained in:
+21
-4
@@ -4,7 +4,7 @@ from django.core.files.uploadedfile import UploadedFile
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from food.models import FoodProduct
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe
|
||||
|
||||
|
||||
class RecipeForm(forms.ModelForm):
|
||||
@@ -16,11 +16,13 @@ class RecipeForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = Recipe
|
||||
fields = ('title', 'description', 'category', 'preparation_minutes',
|
||||
'cooking_minutes', 'default_servings', 'status', 'parent',
|
||||
'cooking_minutes', 'default_servings', 'yield_amount', 'yield_unit', 'status', 'parent',
|
||||
'instructions_markdown', 'notes_markdown', 'photo')
|
||||
labels = {'instructions_markdown': 'Instructions (Markdown)',
|
||||
'notes_markdown': 'Personal notes (Markdown)',
|
||||
'default_servings': 'Servings', 'parent': 'Variation of'}
|
||||
'default_servings': 'Servings', 'parent': 'Variation of',
|
||||
'yield_amount': 'Recipe yield amount', 'yield_unit': 'Yield unit'}
|
||||
help_texts = {'yield_amount': 'Optional: total cooked weight or volume for using this recipe as a subrecipe.'}
|
||||
widgets = {
|
||||
'description': forms.Textarea(attrs={'rows': 3}),
|
||||
'instructions_markdown': forms.Textarea(attrs={'rows': 10}),
|
||||
@@ -74,9 +76,11 @@ class RecipeForm(forms.ModelForm):
|
||||
class RecipeIngredientForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = RecipeIngredient
|
||||
fields = ('name', 'quantity', 'unit', 'preparation_note', 'is_optional',
|
||||
fields = ('name', 'quantity', 'unit', 'amount_per_unit', 'amount_per_unit_unit',
|
||||
'preparation_note', 'is_optional',
|
||||
'inventory_product', 'nutrition_product', 'display_order')
|
||||
widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
|
||||
'amount_per_unit': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
|
||||
'display_order': forms.NumberInput(attrs={'min': 0})}
|
||||
|
||||
|
||||
@@ -120,3 +124,16 @@ RecipeSubrecipeFormSet = inlineformset_factory(
|
||||
Recipe, RecipeSubrecipe, form=RecipeSubrecipeForm,
|
||||
formset=OwnedSubrecipeFormSet, fk_name='recipe', extra=1, can_delete=True,
|
||||
)
|
||||
|
||||
|
||||
class RecipeSubstitutionForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = RecipeIngredientSubstitution
|
||||
fields = ('name', 'quantity', 'unit', 'product', 'amount_per_unit',
|
||||
'amount_per_unit_unit', 'display_order')
|
||||
widgets = {'quantity': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
|
||||
'amount_per_unit': forms.NumberInput(attrs={'min': '.001', 'step': '.001'})}
|
||||
|
||||
def __init__(self, *args, user, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.fields['product'].queryset = FoodProduct.objects.filter(owner=user).order_by('product_name')
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
# Generated by Django 6.1.1 on 2026-10-11 23:56
|
||||
|
||||
import django.core.validators
|
||||
import django.db.models.deletion
|
||||
import uuid
|
||||
from decimal import Decimal
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('food', '0009_backfill_food_hydration'),
|
||||
('recipes', '0002_recipe_markdown_revision'),
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='recipe',
|
||||
name='yield_amount',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='recipe',
|
||||
name='yield_unit',
|
||||
field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='recipeingredient',
|
||||
name='amount_per_unit',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='recipeingredient',
|
||||
name='amount_per_unit_unit',
|
||||
field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='recipeingredientsubstitution',
|
||||
name='amount_per_unit',
|
||||
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.001'))]),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='recipeingredientsubstitution',
|
||||
name='amount_per_unit_unit',
|
||||
field=models.CharField(blank=True, choices=[('g', 'g'), ('ml', 'ml')], max_length=2),
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='RecipeUse',
|
||||
fields=[
|
||||
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
|
||||
('recipe_title_snapshot', models.CharField(max_length=180)),
|
||||
('servings', models.DecimalField(decimal_places=2, max_digits=7)),
|
||||
('request_signature', models.CharField(max_length=64)),
|
||||
('plan_snapshot', models.JSONField(default=dict)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('undone_at', models.DateTimeField(blank=True, null=True)),
|
||||
('recipe', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='stock_uses', to='recipes.recipe')),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'ordering': ('-created_at',),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='RecipeUseLine',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('consumption', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='recipe_use_line', to='food.inventoryconsumption')),
|
||||
('recipe_use', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='recipes.recipeuse')),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -28,6 +28,9 @@ class Recipe(models.Model):
|
||||
cooking_minutes = models.PositiveIntegerField(default=0)
|
||||
default_servings = models.DecimalField(max_digits=7, decimal_places=2, default=2,
|
||||
validators=[MinValueValidator(Decimal('0.01'))])
|
||||
yield_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
yield_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True)
|
||||
category = models.CharField(max_length=80, blank=True)
|
||||
tags = models.JSONField(default=list, blank=True)
|
||||
is_favourite = models.BooleanField(default=False)
|
||||
@@ -50,6 +53,8 @@ class Recipe(models.Model):
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if bool(self.yield_amount) != bool(self.yield_unit):
|
||||
raise ValidationError({'yield_amount': 'Provide both an amount and a unit for recipe yield.'})
|
||||
if not isinstance(self.tags, list) or any(not isinstance(tag, str) for tag in self.tags):
|
||||
raise ValidationError({'tags': 'Tags must be a list of names.'})
|
||||
if self.parent_id:
|
||||
@@ -87,6 +92,9 @@ class RecipeIngredient(models.Model):
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=10, choices=Unit.choices)
|
||||
amount_per_unit = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
amount_per_unit_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True)
|
||||
display_order = models.PositiveIntegerField(default=0)
|
||||
inventory_product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
|
||||
null=True, blank=True, related_name='recipe_inventory_ingredients')
|
||||
@@ -102,6 +110,10 @@ class RecipeIngredient(models.Model):
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if bool(self.amount_per_unit) != bool(self.amount_per_unit_unit):
|
||||
raise ValidationError({'amount_per_unit': 'Provide both an amount and unit for one piece or measure.'})
|
||||
if self.amount_per_unit and self.unit not in ('pieces', 'portions', 'tsp', 'tbsp'):
|
||||
raise ValidationError({'amount_per_unit': 'Only count or measure units need this conversion.'})
|
||||
if self.recipe_id:
|
||||
for field in ('inventory_product', 'nutrition_product'):
|
||||
product = getattr(self, field)
|
||||
@@ -156,6 +168,9 @@ class RecipeIngredientSubstitution(models.Model):
|
||||
quantity = models.DecimalField(max_digits=10, decimal_places=3,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
unit = models.CharField(max_length=10, choices=RecipeIngredient.Unit.choices)
|
||||
amount_per_unit = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True,
|
||||
validators=[MinValueValidator(Decimal('0.001'))])
|
||||
amount_per_unit_unit = models.CharField(max_length=2, choices=[('g', 'g'), ('ml', 'ml')], blank=True)
|
||||
product = models.ForeignKey('food.FoodProduct', on_delete=models.SET_NULL,
|
||||
null=True, blank=True, related_name='recipe_substitutions')
|
||||
display_order = models.PositiveIntegerField(default=0)
|
||||
@@ -165,5 +180,32 @@ class RecipeIngredientSubstitution(models.Model):
|
||||
|
||||
def clean(self):
|
||||
super().clean()
|
||||
if bool(self.amount_per_unit) != bool(self.amount_per_unit_unit):
|
||||
raise ValidationError({'amount_per_unit': 'Provide both an amount and unit for one piece or measure.'})
|
||||
if self.amount_per_unit and self.unit not in ('pieces', 'portions', 'tsp', 'tbsp'):
|
||||
raise ValidationError({'amount_per_unit': 'Only count or measure units need this conversion.'})
|
||||
if self.product_id and self.ingredient_id and self.product.owner_id != self.ingredient.recipe.owner_id:
|
||||
raise ValidationError({'product': 'Choose one of your own food products.'})
|
||||
|
||||
|
||||
class RecipeUse(models.Model):
|
||||
"""One confirmed, reversible multi-product stock operation."""
|
||||
|
||||
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
|
||||
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
||||
recipe = models.ForeignKey(Recipe, on_delete=models.SET_NULL, null=True, related_name='stock_uses')
|
||||
recipe_title_snapshot = models.CharField(max_length=180)
|
||||
servings = models.DecimalField(max_digits=7, decimal_places=2)
|
||||
request_signature = models.CharField(max_length=64)
|
||||
plan_snapshot = models.JSONField(default=dict)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
undone_at = models.DateTimeField(null=True, blank=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ('-created_at',)
|
||||
|
||||
|
||||
class RecipeUseLine(models.Model):
|
||||
recipe_use = models.ForeignKey(RecipeUse, on_delete=models.CASCADE, related_name='lines')
|
||||
consumption = models.OneToOneField('food.InventoryConsumption', on_delete=models.PROTECT,
|
||||
related_name='recipe_use_line')
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""Exact recipe scaling, conservative product matching, nutrition and stock preview."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
|
||||
|
||||
from food.models import FoodProduct
|
||||
from food.services.inventory_consumption import StockError, preview
|
||||
from food.services.logging import NUTRIENTS
|
||||
|
||||
|
||||
THREE_PLACES = Decimal('0.001')
|
||||
NUTRIENT_FIELDS = NUTRIENTS[:5]
|
||||
UNITS = {'g': ('mass', Decimal(1), 'g'), 'kg': ('mass', Decimal(1000), 'g'),
|
||||
'ml': ('volume', Decimal(1), 'ml'), 'L': ('volume', Decimal(1000), 'ml'),
|
||||
'pieces': ('pieces', Decimal(1), 'pieces'),
|
||||
'portions': ('portions', Decimal(1), 'portions')}
|
||||
|
||||
|
||||
class AnalysisError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def parse_servings(value, default):
|
||||
try:
|
||||
servings = Decimal(str(default if value in (None, '') else value))
|
||||
except (InvalidOperation, TypeError, ValueError):
|
||||
raise AnalysisError('Enter a valid number of servings.') from None
|
||||
if (not servings.is_finite() or servings < Decimal('.01') or
|
||||
servings > Decimal('99999.99') or servings != servings.quantize(Decimal('.01'))):
|
||||
raise AnalysisError('Servings must be between 0.01 and 99,999.99 with at most two decimal places.')
|
||||
return servings
|
||||
|
||||
|
||||
def physical_amount(quantity, unit, amount_per_unit=None, amount_per_unit_unit=''):
|
||||
"""Return an exact amount in a compatible base unit; never guess density."""
|
||||
if amount_per_unit is not None and unit in ('pieces', 'portions', 'tsp', 'tbsp'):
|
||||
return quantity * amount_per_unit, amount_per_unit_unit
|
||||
if unit in UNITS:
|
||||
_, factor, base_unit = UNITS[unit]
|
||||
return quantity * factor, base_unit
|
||||
return None, None
|
||||
|
||||
|
||||
def _stock_quantity(value, unit):
|
||||
rounded = value.quantize(THREE_PLACES, rounding=ROUND_HALF_UP)
|
||||
if rounded <= 0:
|
||||
raise AnalysisError('The scaled stock amount is smaller than 0.001.')
|
||||
if unit in ('pieces', 'portions') and rounded != rounded.to_integral_value():
|
||||
raise AnalysisError('A fractional count cannot be deducted from stock.')
|
||||
return rounded
|
||||
|
||||
|
||||
def analyze(recipe, user, servings, *, include_optional=False, substitutions=None, lock=False):
|
||||
servings = parse_servings(servings, recipe.default_servings)
|
||||
if recipe.owner_id != user.pk:
|
||||
raise AnalysisError('Recipe not found.')
|
||||
selected = {str(key): str(value) for key, value in (substitutions or {}).items() if value}
|
||||
used_selections = set()
|
||||
products = list(FoodProduct.objects.filter(owner=user))
|
||||
unique_names = {}
|
||||
for product in products:
|
||||
key = product.product_name.strip().casefold()
|
||||
unique_names.setdefault(key, []).append(product)
|
||||
|
||||
def match(name):
|
||||
candidates = unique_names.get(name.strip().casefold(), [])
|
||||
return candidates[0] if len(candidates) == 1 else None
|
||||
|
||||
lines, groups, issues = [], {}, []
|
||||
totals = {target: Decimal(0) for _, target in NUTRIENT_FIELDS}
|
||||
known = {target: False for _, target in NUTRIENT_FIELDS}
|
||||
complete = {target: True for _, target in NUTRIENT_FIELDS}
|
||||
stock_issue = False
|
||||
|
||||
def add_ingredient(ingredient, scale, source):
|
||||
nonlocal stock_issue
|
||||
substitution_options = list(ingredient.substitutions.all())
|
||||
selected_id = selected.get(str(ingredient.pk))
|
||||
alternative = None
|
||||
if selected_id:
|
||||
used_selections.add(str(ingredient.pk))
|
||||
alternative = next((item for item in substitution_options if str(item.pk) == selected_id), None)
|
||||
if alternative is None:
|
||||
raise AnalysisError('Choose a substitution belonging to this ingredient.')
|
||||
chosen = alternative or ingredient
|
||||
name = chosen.name
|
||||
quantity = chosen.quantity * scale
|
||||
unit = chosen.unit
|
||||
item = {'ingredient': ingredient, 'name': name, 'quantity': quantity, 'unit': unit,
|
||||
'source': source, 'optional': ingredient.is_optional,
|
||||
'substitutions': substitution_options, 'selected_substitution': selected_id or '',
|
||||
'status': 'unknown', 'reason': '', 'product': None, 'stock_percent': 0}
|
||||
lines.append(item)
|
||||
if ingredient.is_optional and not include_optional:
|
||||
item['status'] = 'optional'
|
||||
item['reason'] = 'Excluded from this estimate.'
|
||||
return
|
||||
auto = match(name)
|
||||
if alternative:
|
||||
inventory_product = alternative.product or auto
|
||||
nutrition_product = alternative.product or auto
|
||||
else:
|
||||
inventory_product = ingredient.inventory_product or ingredient.nutrition_product or auto
|
||||
nutrition_product = ingredient.nutrition_product or ingredient.inventory_product or auto
|
||||
amount, base_unit = physical_amount(quantity, unit, chosen.amount_per_unit,
|
||||
chosen.amount_per_unit_unit)
|
||||
if amount is None:
|
||||
item['reason'] = 'Add an explicit amount per measure in the recipe editor.'
|
||||
issues.append(f'{name}: {item["reason"]}')
|
||||
stock_issue = True
|
||||
elif not inventory_product or inventory_product.owner_id != user.pk:
|
||||
item['reason'] = 'No unambiguous inventory product match.'
|
||||
issues.append(f'{name}: {item["reason"]}')
|
||||
stock_issue = True
|
||||
else:
|
||||
item['product'] = inventory_product
|
||||
key = (inventory_product.pk, base_unit)
|
||||
group = groups.setdefault(key, {'product': inventory_product, 'unit': base_unit,
|
||||
'amount': Decimal(0), 'lines': []})
|
||||
group['amount'] += amount
|
||||
group['lines'].append(item)
|
||||
for source_field, target_field in NUTRIENT_FIELDS:
|
||||
value = getattr(nutrition_product, source_field) if nutrition_product else None
|
||||
if (amount is None or not nutrition_product or nutrition_product.owner_id != user.pk or
|
||||
base_unit != nutrition_product.base_unit or value is None):
|
||||
complete[target_field] = False
|
||||
else:
|
||||
totals[target_field] += value * amount / Decimal(100)
|
||||
known[target_field] = True
|
||||
|
||||
def walk(current, scale, ancestors):
|
||||
nonlocal stock_issue
|
||||
if current.pk in ancestors:
|
||||
issues.append('Circular subrecipe reference detected.')
|
||||
stock_issue = True
|
||||
for target in complete:
|
||||
complete[target] = False
|
||||
return
|
||||
ancestors = ancestors | {current.pk}
|
||||
for ingredient in current.ingredients.select_related('inventory_product', 'nutrition_product').prefetch_related('substitutions__product'):
|
||||
add_ingredient(ingredient, scale, '' if current.pk == recipe.pk else current.title)
|
||||
for relation in current.subrecipes.select_related('component'):
|
||||
component = relation.component
|
||||
if component.owner_id != user.pk:
|
||||
issues.append(f'{component.title}: subrecipe is not owned by you.')
|
||||
stock_issue = True
|
||||
for target in complete:
|
||||
complete[target] = False
|
||||
continue
|
||||
if relation.unit == 'servings':
|
||||
component_scale = relation.quantity * scale / component.default_servings
|
||||
elif component.yield_amount and component.yield_unit == relation.unit:
|
||||
component_scale = relation.quantity * scale / component.yield_amount
|
||||
else:
|
||||
issues.append(f'{component.title}: set a matching recipe yield to use {relation.unit}.')
|
||||
stock_issue = True
|
||||
for target in complete:
|
||||
complete[target] = False
|
||||
continue
|
||||
walk(component, component_scale, ancestors)
|
||||
|
||||
walk(recipe, servings / recipe.default_servings, set())
|
||||
if set(selected) - used_selections:
|
||||
raise AnalysisError('A selected substitution is not part of this recipe.')
|
||||
for group in groups.values():
|
||||
try:
|
||||
group['stock_amount'] = _stock_quantity(group['amount'], group['unit'])
|
||||
group['plan'] = preview(user, group['product'], group['stock_amount'], group['unit'], lock=lock)
|
||||
for deduction in group['plan']['deductions']:
|
||||
capacity = deduction['package'].original_amount or deduction['before']
|
||||
deduction['before_percent'] = min(100, int(deduction['before'] * 100 / capacity))
|
||||
deduction['after_percent'] = min(100, int(deduction['after'] * 100 / capacity))
|
||||
available = group['plan']['total']
|
||||
shortage = group['plan']['shortage']
|
||||
group['status'] = ('available' if shortage == 0 else 'partial' if available else 'missing')
|
||||
group['percent'] = min(100, int(available * 100 / group['stock_amount']))
|
||||
except (StockError, AnalysisError) as error:
|
||||
group['status'] = 'unknown'
|
||||
group['plan'] = None
|
||||
group['percent'] = 0
|
||||
issues.append(f'{group["product"].product_name}: {error}')
|
||||
stock_issue = True
|
||||
for line in group['lines']:
|
||||
line['status'] = group['status']
|
||||
line['stock_percent'] = group['percent']
|
||||
if group['status'] == 'partial':
|
||||
line['reason'] = 'Some stock is missing.'
|
||||
elif group['status'] == 'missing':
|
||||
line['reason'] = 'No compatible stock in inventory.'
|
||||
|
||||
nutrition = {target: {'total': totals[target] if known[target] else None,
|
||||
'per_serving': totals[target] / servings if known[target] else None,
|
||||
'complete': complete[target] and known[target]}
|
||||
for _, target in NUTRIENT_FIELDS}
|
||||
nutrition_rows = [
|
||||
{'label': label, 'unit': unit, **nutrition[target]}
|
||||
for target, label, unit in (('calories_kcal', 'Calories', 'kcal'),
|
||||
('carbohydrates_g', 'Carbohydrates', 'g'),
|
||||
('protein_g', 'Protein', 'g'),
|
||||
('fat_g', 'Fat', 'g'), ('fibre_g', 'Fibre', 'g'))
|
||||
]
|
||||
stock_ready = bool(groups) and not stock_issue and all(group['status'] == 'available'
|
||||
for group in groups.values())
|
||||
snapshot = {'recipe_id': str(recipe.api_id), 'servings': str(servings),
|
||||
'include_optional': include_optional, 'substitutions': selected,
|
||||
'ingredients': [{'id': line['ingredient'].pk, 'name': line['name'],
|
||||
'quantity': str(line['quantity']), 'unit': line['unit'],
|
||||
'product_id': line['product'].pk if line['product'] else None,
|
||||
'status': line['status']} for line in lines],
|
||||
'groups': [{'product_id': group['product'].pk, 'amount': str(group['amount']),
|
||||
'stock_amount': str(group.get('stock_amount', '')),
|
||||
'unit': group['unit'],
|
||||
'deductions': [{'package_id': str(d['package'].api_id),
|
||||
'before': str(d['before']), 'after': str(d['after'])}
|
||||
for d in (group['plan'] or {}).get('deductions', [])]}
|
||||
for group in groups.values()]}
|
||||
fingerprint = hashlib.sha256(json.dumps(snapshot, sort_keys=True).encode()).hexdigest()
|
||||
return {'recipe': recipe, 'servings': servings, 'include_optional': include_optional,
|
||||
'selected_substitutions': selected, 'lines': lines, 'groups': list(groups.values()),
|
||||
'nutrition': nutrition, 'nutrition_rows': nutrition_rows,
|
||||
'issues': issues, 'stock_ready': stock_ready,
|
||||
'fingerprint': fingerprint, 'snapshot': snapshot}
|
||||
@@ -0,0 +1,93 @@
|
||||
"""Confirmed, idempotent recipe stock deductions built on the inventory service."""
|
||||
|
||||
import hashlib
|
||||
import uuid
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core import signing
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
|
||||
from food.services.inventory_consumption import StockError, consume, undo
|
||||
from recipes.models import RecipeUse, RecipeUseLine
|
||||
|
||||
from .analysis import AnalysisError, analyze
|
||||
|
||||
|
||||
SALT = 'recipes.stock-use.v1'
|
||||
|
||||
|
||||
class RecipeStockError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def make_confirmation(analysis):
|
||||
return signing.dumps({'operation_id': str(uuid.uuid4()),
|
||||
'recipe_id': str(analysis['recipe'].api_id),
|
||||
'servings': str(analysis['servings']),
|
||||
'include_optional': analysis['include_optional'],
|
||||
'substitutions': analysis['selected_substitutions'],
|
||||
'fingerprint': analysis['fingerprint']}, salt=SALT)
|
||||
|
||||
|
||||
def confirm(user, recipe, token):
|
||||
try:
|
||||
payload = signing.loads(token, salt=SALT, max_age=1800)
|
||||
operation_id = uuid.UUID(payload['operation_id'])
|
||||
except (signing.BadSignature, ValueError, KeyError, TypeError, AttributeError):
|
||||
raise RecipeStockError('This preview expired or is invalid. Review the stock again.') from None
|
||||
if payload.get('recipe_id') != str(recipe.api_id) or recipe.owner_id != user.pk:
|
||||
raise RecipeStockError('This confirmation does not belong to this recipe.')
|
||||
signature = hashlib.sha256(token.encode()).hexdigest()
|
||||
with transaction.atomic():
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
previous = RecipeUse.objects.filter(pk=operation_id).first()
|
||||
if previous:
|
||||
if previous.user_id != user.pk or previous.request_signature != signature:
|
||||
raise RecipeStockError('This confirmation was already used for another request.')
|
||||
return previous, False
|
||||
try:
|
||||
current = analyze(recipe, user, payload['servings'],
|
||||
include_optional=payload['include_optional'],
|
||||
substitutions=payload['substitutions'], lock=True)
|
||||
except (AnalysisError, KeyError, TypeError) as error:
|
||||
raise RecipeStockError(str(error)) from None
|
||||
if not current['stock_ready']:
|
||||
raise RecipeStockError('Required stock is unavailable. Review the updated preview.')
|
||||
if current['fingerprint'] != payload['fingerprint']:
|
||||
raise RecipeStockError('The recipe or stock changed. Review the updated preview.')
|
||||
operation = RecipeUse.objects.create(id=operation_id, user=user, recipe=recipe,
|
||||
recipe_title_snapshot=recipe.title,
|
||||
servings=current['servings'],
|
||||
request_signature=signature,
|
||||
plan_snapshot=current['snapshot'])
|
||||
try:
|
||||
for index, group in enumerate(current['groups']):
|
||||
consumption = consume(
|
||||
user, group['product'], group['stock_amount'], group['unit'],
|
||||
source='recipe', source_reference=str(operation.id),
|
||||
description=f'Recipe: {recipe.title}',
|
||||
idempotency_key=f'recipe:{operation.id}:{index}',
|
||||
)
|
||||
RecipeUseLine.objects.create(recipe_use=operation, consumption=consumption)
|
||||
except StockError as error:
|
||||
raise RecipeStockError(str(error)) from None
|
||||
return operation, True
|
||||
|
||||
|
||||
def reverse_use(user, operation_id):
|
||||
with transaction.atomic():
|
||||
get_user_model().objects.select_for_update().get(pk=user.pk)
|
||||
operation = RecipeUse.objects.select_for_update().filter(pk=operation_id, user=user).first()
|
||||
if operation is None:
|
||||
raise RecipeStockError('Recipe stock use not found.')
|
||||
if operation.undone_at:
|
||||
return operation, False
|
||||
try:
|
||||
for line in operation.lines.select_related('consumption').order_by('-pk'):
|
||||
undo(user, line.consumption_id)
|
||||
except StockError as error:
|
||||
raise RecipeStockError(str(error)) from None
|
||||
operation.undone_at = timezone.now()
|
||||
operation.save(update_fields=('undone_at',))
|
||||
return operation, True
|
||||
@@ -17,3 +17,6 @@ body[data-theme=dark] .recipes-layout{--recipe-surface:#222b25;--recipe-line:#43
|
||||
body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-main{border-color:var(--recipe-line);background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-ww-container,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-preview{background:var(--recipe-surface);color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .ProseMirror,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents,body[data-theme=dark] .recipes-markdown-editor .toastui-editor-md-container .CodeMirror{color:var(--recipe-ink)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-contents *{color:inherit}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-toolbar-icons{filter:invert(.85)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-defaultUI-toolbar button:hover{background:#405347}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item{color:var(--recipe-muted)}body[data-theme=dark] .recipes-markdown-editor .toastui-editor-mode-switch .tab-item.active{background:var(--recipe-surface);color:var(--recipe-ink)}
|
||||
@media(max-width:767px){.recipes-markdown-editor .toastui-editor-defaultUI-toolbar{overflow-x:auto}.recipes-markdown-editor .toastui-editor-toolbar-group{flex:none}.recipes-form-actions{flex-wrap:wrap}.recipes-save-status{width:100%;margin-left:0}}
|
||||
.recipes-related-component{padding:7px 0;border-top:1px solid var(--recipe-line)}.recipes-related-component summary{color:var(--recipe-accent);font-size:.79rem;cursor:pointer}.recipes-related-component .recipes-markdown-source{margin-top:9px;padding:9px;border-radius:8px;background:var(--recipe-soft)}
|
||||
.recipes-serving-form{display:flex;align-items:center;flex-wrap:wrap;gap:10px;margin-top:17px;padding:12px;border:1px solid var(--recipe-line);border-radius:10px;background:var(--recipe-soft);font-size:.8rem}.recipes-serving-form>label:first-child{font-weight:700}.recipes-serving-form input[type=number]{width:88px;min-height:40px;padding:7px;border:1px solid var(--recipe-line);border-radius:7px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-serving-form .recipes-checkbox{margin-left:auto}.recipes-serving-form .recipes-outline-button{min-height:40px}.recipes-stock-label{display:inline-block;color:var(--recipe-muted);font-size:.72rem;font-weight:700}.recipes-stock-label--available{color:#25714c}.recipes-stock-label--partial{color:#a36a19}.recipes-stock-label--missing{color:#b6413b}.recipes-stock-label--unknown{color:var(--recipe-muted)}.recipes-stock-label--optional{color:var(--recipe-muted)}.recipes-nutrition{margin:0}.recipes-nutrition>div{display:flex;align-items:start;justify-content:space-between;gap:7px;padding:8px 0;border-bottom:1px solid var(--recipe-line);font-size:.78rem}.recipes-nutrition>div:last-child{border:0}.recipes-nutrition dt{color:var(--recipe-muted)}.recipes-nutrition dd{margin:0;text-align:right;font-weight:700}.recipes-nutrition dd small{display:block;color:var(--recipe-muted);font-size:.7rem;font-weight:400}.recipes-stock-group{padding:9px 0;border-top:1px solid var(--recipe-line)}.recipes-stock-group>div:first-child{display:flex;justify-content:space-between;gap:7px;font-size:.78rem}.recipes-stock-group strong{overflow-wrap:anywhere}.recipes-stock-group small{display:block;margin:3px 0 7px;color:var(--recipe-muted);font-size:.72rem}.recipes-fill{height:8px;overflow:hidden;border-radius:999px;background:#d9e1d8}.recipes-fill span{display:block;height:100%;border-radius:inherit;background:#39845f}.recipes-preview-link{display:block;margin-top:12px;text-align:center}body[data-theme=dark] .recipes-stock-label--available{color:#9bdbab}body[data-theme=dark] .recipes-stock-label--partial{color:#f0bf6c}body[data-theme=dark] .recipes-stock-label--missing{color:#f3a09b}body[data-theme=dark] .recipes-fill{background:#3b4c40}body[data-theme=dark] .recipes-fill span{background:#6bb482}
|
||||
.recipes-stock-preview{max-width:1000px}.recipes-stock-preview>.recipes-panel{margin-bottom:14px}.recipes-stock-preview h2,.recipes-substitution-list h2{margin:0 0 14px;font-family:Fraunces,Georgia,serif;font-size:1.25rem}.recipes-preview-options{display:flex;align-items:end;flex-wrap:wrap;gap:14px}.recipes-preview-options>label:first-child{display:grid;gap:5px;font-size:.8rem;font-weight:700}.recipes-preview-options input[type=number],.recipes-preview-options select{min-height:42px;padding:8px;border:1px solid var(--recipe-line);border-radius:8px;color:var(--recipe-ink);background:var(--recipe-surface)}.recipes-preview-options input[type=number]{width:100px}.recipes-preview-options .recipes-checkbox{align-self:center}.recipes-preview-choices{display:flex;flex-wrap:wrap;gap:10px;width:100%}.recipes-preview-choices label{display:grid;gap:5px;min-width:220px;font-size:.8rem}.recipes-preview-group{padding:15px 0;border-top:1px solid var(--recipe-line)}.recipes-preview-group h3{display:flex;align-items:center;gap:10px;margin:0 0 4px}.recipes-preview-group p{margin:0 0 10px;color:var(--recipe-muted);font-size:.82rem}.recipes-preview-issues{padding-left:1.3rem;color:#a36a19;font-size:.82rem}.recipes-package{margin:8px 0;padding:11px;border:1px solid var(--recipe-line);border-radius:9px;background:var(--recipe-soft)}.recipes-package__heading{display:flex;justify-content:space-between;gap:12px;font-size:.83rem}.recipes-package small{display:block;margin:4px 0 8px;color:var(--recipe-muted)}.recipes-preview-confirm p{font-size:.84rem}.recipes-substitution-list{margin-top:18px}.recipes-substitution-list>div{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 0;border-top:1px solid var(--recipe-line)}.recipes-substitute-link{margin:8px 0 0;font-size:.8rem}.recipes-substitute-link a,.recipes-stock-preview .recipes-panel a{color:var(--recipe-accent)}
|
||||
@media(max-width:767px){.recipes-serving-form .recipes-checkbox{margin-left:0}.recipes-serving-form .recipes-outline-button{width:100%}.recipes-preview-options .recipes-outline-button{width:100%}.recipes-preview-choices,.recipes-preview-choices label{width:100%;min-width:0}.recipes-package__heading{flex-wrap:wrap}}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}{% if creating %}New recipe{% else %}Edit {{ recipe.title }}{% endif %} · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=3">
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/vendor/toastui-editor.min.css' %}"><link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4">
|
||||
<div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% if creating %}{% url 'recipes:list' %}{% else %}{% url 'recipes:detail' recipe.api_id %}{% endif %}">← Back to recipes</a><h1>{% if creating %}New recipe{% else %}Edit recipe{% endif %}</h1><p>Keep ingredients structured and instructions in Markdown.</p></header>
|
||||
<form method="post" enctype="multipart/form-data" class="recipes-edit-card" data-recipe-form data-autosave-url="{% if creating %}{% url 'recipes:autosave-new' %}{% else %}{% url 'recipes:autosave' recipe.api_id %}{% endif %}"{% if creating %} data-draft-id="{{ new_draft_id }}"{% endif %}>{% csrf_token %}
|
||||
{% if creating %}<input type="hidden" name="draft_id" value="{{ new_draft_id }}">{% endif %}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<div class="recipes-ingredient-form" data-ingredient-row>
|
||||
{% for hidden in ingredient.hidden_fields %}{{ hidden }}{% endfor %}
|
||||
<div class="recipes-ingredient-form__main"><div class="recipes-field"><label for="{{ ingredient.name.id_for_label }}">Ingredient name</label>{{ ingredient.name }}{{ ingredient.name.errors }}</div><div class="recipes-field"><label for="{{ ingredient.quantity.id_for_label }}">Quantity</label>{{ ingredient.quantity }}{{ ingredient.quantity.errors }}</div><div class="recipes-field"><label for="{{ ingredient.unit.id_for_label }}">Unit</label>{{ ingredient.unit }}{{ ingredient.unit.errors }}</div></div>
|
||||
<details class="recipes-ingredient-form__more"><summary>Ingredient details</summary><div class="recipes-form-grid"><div class="recipes-field"><label for="{{ ingredient.preparation_note.id_for_label }}">Preparation note</label>{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}</div><div class="recipes-field"><label for="{{ ingredient.display_order.id_for_label }}">Display order</label>{{ ingredient.display_order }}{{ ingredient.display_order.errors }}</div><div class="recipes-field"><label for="{{ ingredient.inventory_product.id_for_label }}">Inventory product</label>{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}</div><div class="recipes-field"><label for="{{ ingredient.nutrition_product.id_for_label }}">Nutrition product</label>{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}</div><label class="recipes-checkbox">{{ ingredient.is_optional }} Optional ingredient</label>{% if ingredient.DELETE %}<label class="recipes-checkbox">{{ ingredient.DELETE }} Remove ingredient</label>{% endif %}</div></details>
|
||||
<details class="recipes-ingredient-form__more"><summary>Ingredient details</summary><div class="recipes-form-grid"><div class="recipes-field"><label for="{{ ingredient.preparation_note.id_for_label }}">Preparation note</label>{{ ingredient.preparation_note }}{{ ingredient.preparation_note.errors }}</div><div class="recipes-field"><label for="{{ ingredient.display_order.id_for_label }}">Display order</label>{{ ingredient.display_order }}{{ ingredient.display_order.errors }}</div><div class="recipes-field"><label for="{{ ingredient.inventory_product.id_for_label }}">Inventory product</label>{{ ingredient.inventory_product }}{{ ingredient.inventory_product.errors }}</div><div class="recipes-field"><label for="{{ ingredient.nutrition_product.id_for_label }}">Nutrition product</label>{{ ingredient.nutrition_product }}{{ ingredient.nutrition_product.errors }}</div><div class="recipes-field"><label for="{{ ingredient.amount_per_unit.id_for_label }}">Amount per piece or measure</label>{{ ingredient.amount_per_unit }}{{ ingredient.amount_per_unit.errors }}<small>Use only when the recipe unit needs an explicit weight or volume conversion.</small></div><div class="recipes-field"><label for="{{ ingredient.amount_per_unit_unit.id_for_label }}">Conversion unit</label>{{ ingredient.amount_per_unit_unit }}{{ ingredient.amount_per_unit_unit.errors }}</div><label class="recipes-checkbox">{{ ingredient.is_optional }} Optional ingredient</label>{% if ingredient.DELETE %}<label class="recipes-checkbox">{{ ingredient.DELETE }} Remove ingredient</label>{% endif %}</div></details>
|
||||
{% if ingredient.instance.pk %}<p class="recipes-substitute-link"><a href="{% url 'recipes:substitution-add' recipe.api_id ingredient.instance.pk %}">Manage substitutes{% if ingredient.instance.substitutions.count %} ({{ ingredient.instance.substitutions.count }}){% endif %}</a></p>{% endif %}
|
||||
{% if ingredient.non_field_errors %}<div class="recipes-form-error" role="alert">{{ ingredient.non_field_errors }}</div>{% endif %}
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{% block title %}Recipes · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=3">
|
||||
<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4">
|
||||
<div class="recipes-layout {% if explicit_detail %}recipes-layout--detail{% else %}recipes-layout--list{% endif %}">
|
||||
<aside class="recipes-browser" aria-label="Recipe browser">
|
||||
<div class="recipes-browser__heading">
|
||||
@@ -39,8 +39,10 @@
|
||||
{% if selected.photo %}<img src="{% url 'recipes:photo' selected.api_id %}" alt="Photo of {{ selected.title }}">{% else %}<div class="recipes-photo-placeholder" role="img" aria-label="No recipe photo yet"><span>No photo yet</span></div>{% endif %}
|
||||
<div class="recipes-hero__copy"><p class="recipes-eyebrow">{% if selected.status == 'draft' %}Draft recipe{% else %}Recipe{% endif %}</p><h2>{{ selected.title }}</h2><p class="recipes-hero__meta">{{ selected.total_minutes }} min total · {{ selected.default_servings|floatformat:-2 }} servings</p><div class="recipes-chips">{% if selected.category %}<span>{{ selected.category }}</span>{% endif %}{% for value in selected.tags %}<span>{{ value }}</span>{% endfor %}</div>{% if selected.description %}<p class="recipes-hero__description">{{ selected.description }}</p>{% endif %}</div>
|
||||
</div>
|
||||
<form class="recipes-serving-form" method="get" action="{% url 'recipes:detail' selected.api_id %}"><label for="recipe-servings">Servings</label><input id="recipe-servings" type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><button type="submit" class="recipes-outline-button">Update</button></form>
|
||||
{% if analysis_error %}<p class="recipes-form-error" role="alert">{{ analysis_error }}</p>{% endif %}
|
||||
<div class="recipes-content-grid">
|
||||
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for ingredient in selected.ingredients.all %}<li><span>{{ ingredient.name }}{% if ingredient.preparation_note %}<small>{{ ingredient.preparation_note }}</small>{% endif %}</span><strong>{{ ingredient.quantity|floatformat:-3 }} {{ ingredient.unit }}</strong>{% if ingredient.is_optional %}<em>Optional</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
|
||||
<section class="recipes-panel" aria-labelledby="recipe-ingredients-heading"><h3 id="recipe-ingredients-heading">Ingredients</h3><ul class="recipes-ingredient-list">{% for line in analysis.lines %}<li><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}{% if line.ingredient.preparation_note %}<small>{{ line.ingredient.preparation_note }}</small>{% endif %}<small class="recipes-stock-label recipes-stock-label--{{ line.status }}">{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}</small></span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong>{% if line.optional %}<em>Optional{% if not analysis.include_optional %} · excluded{% endif %}</em>{% endif %}</li>{% empty %}<li class="recipes-muted">No ingredients added yet.</li>{% endfor %}</ul></section>
|
||||
<div class="recipes-content-stack"><section class="recipes-panel" aria-labelledby="recipe-instructions-heading"><h3 id="recipe-instructions-heading">Instructions</h3>{% if selected.instructions_markdown %}<div class="recipes-markdown-source">{{ selected.instructions_markdown|recipe_markdown }}</div>{% else %}<p class="recipes-muted">No instructions added yet.</p>{% endif %}</section>{% if selected.notes_markdown %}<section class="recipes-panel" aria-labelledby="recipe-notes-heading"><h3 id="recipe-notes-heading">Notes</h3><div class="recipes-markdown-source">{{ selected.notes_markdown|recipe_markdown }}</div></section>{% endif %}</div>
|
||||
</div>
|
||||
{% else %}
|
||||
@@ -49,9 +51,11 @@
|
||||
</section>
|
||||
|
||||
{% if selected %}<aside class="recipes-info" aria-label="Recipe information">
|
||||
<section class="recipes-panel"><h3>At a glance</h3><dl class="recipes-facts"><div><dt>Servings</dt><dd>{{ selected.default_servings|floatformat:-2 }}</dd></div><div><dt>Preparation</dt><dd>{{ selected.preparation_minutes }} min</dd></div><div><dt>Cooking</dt><dd>{{ selected.cooking_minutes }} min</dd></div><div><dt>Status</dt><dd>{{ selected.get_status_display }}</dd></div></dl></section>
|
||||
<section class="recipes-panel"><h3>At a glance</h3><dl class="recipes-facts"><div><dt>Selected servings</dt><dd>{{ analysis.servings|floatformat:-2 }}</dd></div><div><dt>Preparation</dt><dd>{{ selected.preparation_minutes }} min</dd></div><div><dt>Cooking</dt><dd>{{ selected.cooking_minutes }} min</dd></div><div><dt>Status</dt><dd>{{ selected.get_status_display }}</dd></div></dl></section>
|
||||
<section class="recipes-panel"><h3>Nutrition</h3><p class="recipes-muted">For {{ analysis.servings|floatformat:-2 }} servings. Estimates use matched product data.</p><dl class="recipes-nutrition">{% for row in analysis.nutrition_rows %}<div><dt>{{ row.label }}</dt><dd>{% if row.total is not None %}{{ row.per_serving|floatformat:1 }} {{ row.unit }} / serving<small>{{ row.total|floatformat:1 }} {{ row.unit }} total{% if not row.complete %} · incomplete{% endif %}</small>{% else %}<span aria-label="No estimate">—</span><small>Data unavailable</small>{% endif %}</dd></div>{% endfor %}</dl><p class="recipes-muted">A partial estimate excludes missing nutrient values.</p></section>
|
||||
<section class="recipes-panel"><h3>Inventory status</h3>{% for group in analysis.groups %}<div class="recipes-stock-group"><div><strong>{{ group.product.product_name }}</strong><span class="recipes-stock-label recipes-stock-label--{{ group.status }}">{{ group.status|capfirst }}</span></div><small>{% if group.plan %}{{ group.plan.total|floatformat:-3 }} / {{ group.stock_amount|floatformat:-3 }} {{ group.unit }} available{% else %}Unit conversion needed{% endif %}</small><div class="recipes-fill" role="progressbar" aria-label="{{ group.product.product_name }} available for recipe" aria-valuenow="{{ group.percent }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ group.percent }}%"></span></div></div>{% empty %}<p class="recipes-muted">Match ingredients to products to check stock.</p>{% endfor %}<a class="recipes-outline-button recipes-preview-link" href="{% url 'recipes:stock-preview' selected.api_id %}?servings={{ analysis.servings }}{% if analysis.include_optional %}&optional=1{% endif %}">Review stock and deductions</a></section>
|
||||
{% if selected.parent or selected.variations.all or selected.subrecipes.all %}<section class="recipes-panel"><h3>Related recipes</h3>{% if selected.parent %}<p>Variation of <a href="{% url 'recipes:detail' selected.parent.api_id %}">{{ selected.parent.title }}</a></p>{% endif %}{% for variation in selected.variations.all %}<p><a href="{% url 'recipes:detail' variation.api_id %}">{{ variation.title }}</a></p>{% endfor %}{% for item in selected.subrecipes.all %}<div class="recipes-related-component"><p>{{ item.quantity|floatformat:-3 }} {{ item.unit }} of <a href="{% url 'recipes:detail' item.component.api_id %}">{{ item.component.title }}</a></p>{% if item.component.instructions_markdown %}<details><summary>Show {{ item.component.title }} instructions</summary><div class="recipes-markdown-source">{{ item.component.instructions_markdown|recipe_markdown }}</div></details>{% endif %}</div>{% endfor %}</section>{% endif %}
|
||||
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form><a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
|
||||
<section class="recipes-panel"><h3>Actions</h3><a class="recipes-action" href="{% url 'recipes:edit' selected.api_id %}">Edit recipe</a><form method="post" action="{% url 'recipes:create-variation' selected.api_id %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Create variation</button></form>{% if last_use %}<form method="post" action="{% url 'recipes:stock-undo' last_use.pk %}" class="recipes-action-form">{% csrf_token %}<button type="submit" class="recipes-action">Undo last inventory use</button></form>{% endif %}<a class="recipes-action recipes-action--danger" href="{% url 'recipes:delete' selected.api_id %}">Delete recipe</a></section>
|
||||
</aside>{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Review stock · {{ recipe.title }} · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4">
|
||||
<div class="recipes-layout recipes-layout--form recipes-stock-preview">
|
||||
<header class="recipes-form-header"><a href="{% url 'recipes:detail' recipe.api_id %}">← Back to {{ recipe.title }}</a><h1>Review inventory use</h1><p>Stock changes only after you confirm below.</p></header>
|
||||
{% if error %}<p class="recipes-form-error" role="alert">{{ error }}</p>{% endif %}
|
||||
<section class="recipes-panel"><h2>Recipe amounts</h2><form method="get" class="recipes-preview-options"><label>Servings<input type="number" name="servings" min="0.01" max="99999.99" step="0.01" value="{{ analysis.servings|floatformat:-2 }}"></label><label class="recipes-checkbox"><input type="checkbox" name="optional" value="1"{% if analysis.include_optional %} checked{% endif %}> Include optional ingredients</label><div class="recipes-preview-choices">{% for line in analysis.lines %}{% if line.substitutions %}<label>{{ line.name }} alternative<select name="sub_{{ line.ingredient.pk }}"><option value="">Original ingredient</option>{% for alternative in line.substitutions %}<option value="{{ alternative.pk }}"{% if line.selected_substitution == alternative.pk|stringformat:'s' %} selected{% endif %}>{{ alternative.name }} · {{ alternative.quantity|floatformat:-3 }} {{ alternative.unit }}</option>{% endfor %}</select></label>{% endif %}{% endfor %}</div><button type="submit" class="recipes-outline-button">Update preview</button></form></section>
|
||||
<section class="recipes-panel"><h2>Ingredient checks</h2><ul class="recipes-ingredient-list">{% for line in analysis.lines %}<li><span>{{ line.name }}{% if line.source %}<small>From {{ line.source }}</small>{% endif %}<small class="recipes-stock-label recipes-stock-label--{{ line.status }}">{{ line.status|capfirst }}{% if line.reason %}: {{ line.reason }}{% endif %}</small>{% if line.ingredient.pk %}<small><a href="{% url 'recipes:substitution-add' line.ingredient.recipe.api_id line.ingredient.pk %}">Add a substitute</a></small>{% endif %}</span><strong>{{ line.quantity|floatformat:-3 }} {{ line.unit }}</strong></li>{% empty %}<li>No ingredients added yet.</li>{% endfor %}</ul><p><a href="{% url 'recipes:edit' recipe.api_id %}">Edit ingredient quantities and product matches</a></p></section>
|
||||
<section class="recipes-panel"><h2>Package deductions</h2>{% if analysis.issues %}<ul class="recipes-preview-issues">{% for issue in analysis.issues %}<li>{{ issue }}</li>{% endfor %}</ul>{% endif %}{% for group in analysis.groups %}<div class="recipes-preview-group"><h3>{{ group.product.product_name }} <span class="recipes-stock-label recipes-stock-label--{{ group.status }}">{{ group.status|capfirst }}</span></h3><p>{{ group.stock_amount|floatformat:-3 }} {{ group.unit }} needed{% if group.plan %} · {{ group.plan.total|floatformat:-3 }} {{ group.unit }} available{% if group.plan.shortage %} · {{ group.plan.shortage|floatformat:-3 }} {{ group.unit }} missing{% endif %}{% endif %}</p>{% if group.plan %}{% for deduction in group.plan.deductions %}<div class="recipes-package"><div class="recipes-package__heading"><strong>Package {{ deduction.package.api_id|stringformat:'s'|slice:':8' }}</strong><span>{{ deduction.before|floatformat:-3 }} → {{ deduction.after|floatformat:-3 }} {{ deduction.unit }}</span></div><small>Use {{ deduction.amount|floatformat:-3 }} {{ deduction.unit }}{% if deduction.package.best_before %} · Best before {{ deduction.package.best_before }}{% endif %}</small><div class="recipes-fill" role="progressbar" aria-label="Package remaining after use" aria-valuenow="{{ deduction.after_percent }}" aria-valuemin="0" aria-valuemax="100"><span style="width:{{ deduction.after_percent }}%"></span></div></div>{% empty %}<p class="recipes-muted">No compatible packages.</p>{% endfor %}{% endif %}</div>{% empty %}<p class="recipes-muted">Match ingredients to inventory products to see a package plan.</p>{% endfor %}</section>
|
||||
<section class="recipes-panel recipes-preview-confirm"><h2>Confirm inventory use</h2>{% if confirmation %}<p>This deducts the listed amounts from Kitchen Inventory. It does not log food in your diary.</p><form method="post" action="{% url 'recipes:stock-confirm' recipe.api_id %}">{% csrf_token %}<input type="hidden" name="confirmation" value="{{ confirmation }}"><button class="button" type="submit">Confirm and deduct stock</button></form>{% else %}<p>Resolve missing stock or unknown matches, then update the preview before confirming.</p>{% endif %}</section>
|
||||
</div>{% endblock %}
|
||||
@@ -0,0 +1,4 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Add substitute · {{ ingredient.name }} · Tasknest{% endblock %}
|
||||
{% block page_class %}recipes-page-content{% endblock %}
|
||||
{% block content %}<link rel="stylesheet" href="{% static 'recipes/recipes.css' %}?v=4"><div class="recipes-layout recipes-layout--form"><header class="recipes-form-header"><a href="{% url 'recipes:edit' recipe.api_id %}">← Back to recipe editor</a><h1>Substitutes for {{ ingredient.name }}</h1><p>Alternative quantities are measured for the recipe’s default servings.</p></header><form method="post" class="recipes-edit-card">{% csrf_token %}<section><h2>Add substitute</h2><div class="recipes-form-grid">{% for field in form %}<div class="recipes-field"><label for="{{ field.id_for_label }}">{{ field.label }}</label>{{ field }}{% if field.errors %}<div class="recipes-form-error" role="alert">{{ field.errors }}</div>{% endif %}</div>{% endfor %}</div></section><div class="recipes-form-actions"><button type="submit" class="button">Add substitute</button></div></form>{% if ingredient.substitutions.all %}<section class="recipes-panel recipes-substitution-list"><h2>Existing substitutes</h2>{% for item in ingredient.substitutions.all %}<div><span>{{ item.name }} · {{ item.quantity|floatformat:-3 }} {{ item.unit }}</span><form method="post" action="{% url 'recipes:substitution-delete' recipe.api_id ingredient.pk item.pk %}">{% csrf_token %}<button type="submit" class="recipes-outline-button">Remove</button></form></div>{% endfor %}</section>{% endif %}</div>{% endblock %}
|
||||
@@ -0,0 +1,203 @@
|
||||
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)
|
||||
@@ -12,6 +12,13 @@ urlpatterns = [
|
||||
path('<uuid:identifier>/edit/', views.edit, name='edit'),
|
||||
path('<uuid:identifier>/autosave/', views.autosave, name='autosave'),
|
||||
path('<uuid:identifier>/variations/new/', views.create_variation, name='create-variation'),
|
||||
path('<uuid:identifier>/stock/', views.stock_preview, name='stock-preview'),
|
||||
path('<uuid:identifier>/stock/confirm/', views.stock_confirm, name='stock-confirm'),
|
||||
path('stock-use/<uuid:identifier>/undo/', views.stock_undo, name='stock-undo'),
|
||||
path('<uuid:identifier>/ingredients/<int:ingredient_id>/substitutions/new/',
|
||||
views.substitution_add, name='substitution-add'),
|
||||
path('<uuid:identifier>/ingredients/<int:ingredient_id>/substitutions/<int:substitution_id>/delete/',
|
||||
views.substitution_delete, name='substitution-delete'),
|
||||
path('<uuid:identifier>/delete/', views.delete, name='delete'),
|
||||
path('<uuid:identifier>/favourite/', views.toggle_favourite, name='favourite'),
|
||||
path('<uuid:identifier>/photo/', views.photo, name='photo'),
|
||||
|
||||
+94
-3
@@ -11,8 +11,11 @@ from django.urls import reverse
|
||||
from django.views.decorators.http import require_http_methods, require_POST
|
||||
from PIL import Image
|
||||
|
||||
from .forms import RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet
|
||||
from .models import Recipe, RecipeIngredient, RecipeSubrecipe
|
||||
from .forms import (RecipeForm, RecipeIngredientFormSet, RecipeSubrecipeFormSet,
|
||||
RecipeSubstitutionForm)
|
||||
from .models import Recipe, RecipeIngredient, RecipeIngredientSubstitution, RecipeSubrecipe, RecipeUse
|
||||
from .services.analysis import AnalysisError, analyze
|
||||
from .services.stock_use import RecipeStockError, confirm, make_confirmation, reverse_use
|
||||
|
||||
|
||||
def _owned(user):
|
||||
@@ -39,6 +42,17 @@ def _library(request, selected=None):
|
||||
recipes = recipes[:100]
|
||||
if selected is None and recipes:
|
||||
selected = recipes[0]
|
||||
analysis = None
|
||||
analysis_error = ''
|
||||
last_use = None
|
||||
if selected:
|
||||
try:
|
||||
analysis = analyze(selected, request.user, request.GET.get('servings'),
|
||||
include_optional=request.GET.get('optional') == '1')
|
||||
except AnalysisError as error:
|
||||
analysis_error = str(error)
|
||||
analysis = analyze(selected, request.user, selected.default_servings)
|
||||
last_use = RecipeUse.objects.filter(user=request.user, recipe=selected, undone_at__isnull=True).first()
|
||||
categories = list(_owned(request.user).exclude(category='').order_by('category')
|
||||
.values_list('category', flat=True).distinct())
|
||||
tags = sorted({tag for values in _owned(request.user).values_list('tags', flat=True)
|
||||
@@ -47,6 +61,7 @@ def _library(request, selected=None):
|
||||
'recipes': recipes, 'selected': selected, 'query': query,
|
||||
'category': category, 'tag': tag, 'favourite': favourite,
|
||||
'categories': categories, 'tags': tags, 'explicit_detail': explicit_detail,
|
||||
'analysis': analysis, 'analysis_error': analysis_error, 'last_use': last_use,
|
||||
})
|
||||
|
||||
|
||||
@@ -62,6 +77,79 @@ def detail(request, identifier):
|
||||
return _library(request, recipe)
|
||||
|
||||
|
||||
@login_required
|
||||
def stock_preview(request, identifier):
|
||||
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
|
||||
selected = {key[4:]: value for key, value in request.GET.items() if key.startswith('sub_') and value}
|
||||
try:
|
||||
result = analyze(recipe, request.user, request.GET.get('servings'),
|
||||
include_optional=request.GET.get('optional') == '1',
|
||||
substitutions=selected)
|
||||
error = ''
|
||||
except AnalysisError as exc:
|
||||
error = str(exc)
|
||||
result = analyze(recipe, request.user, recipe.default_servings)
|
||||
return render(request, 'recipes/stock_preview.html', {
|
||||
'recipe': recipe, 'analysis': result, 'error': error,
|
||||
'confirmation': make_confirmation(result) if result['stock_ready'] and not error else '',
|
||||
})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def stock_confirm(request, identifier):
|
||||
recipe = get_object_or_404(_owned(request.user), api_id=identifier)
|
||||
try:
|
||||
operation, created = confirm(request.user, recipe, request.POST.get('confirmation', ''))
|
||||
messages.success(request, 'Recipe ingredients deducted from inventory.' if created
|
||||
else 'This recipe stock use was already recorded.')
|
||||
return redirect(f'{reverse("recipes:detail", args=[recipe.api_id])}?servings={operation.servings}')
|
||||
except RecipeStockError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('recipes:stock-preview', identifier=recipe.api_id)
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def stock_undo(request, identifier):
|
||||
operation = get_object_or_404(RecipeUse, pk=identifier, user=request.user)
|
||||
try:
|
||||
_, reversed_now = reverse_use(request.user, operation.pk)
|
||||
messages.success(request, 'Recipe stock use reversed.' if reversed_now
|
||||
else 'This stock use was already reversed.')
|
||||
except RecipeStockError as exc:
|
||||
messages.error(request, str(exc))
|
||||
return redirect('recipes:detail', identifier=operation.recipe.api_id) if operation.recipe else redirect('recipes:list')
|
||||
|
||||
|
||||
@login_required
|
||||
@require_http_methods(['GET', 'POST'])
|
||||
def substitution_add(request, identifier, ingredient_id):
|
||||
ingredient = get_object_or_404(RecipeIngredient, pk=ingredient_id,
|
||||
recipe__api_id=identifier, recipe__owner=request.user)
|
||||
form = RecipeSubstitutionForm(request.POST or None, user=request.user)
|
||||
if request.method == 'POST' and form.is_valid():
|
||||
substitution = form.save(commit=False)
|
||||
substitution.ingredient = ingredient
|
||||
substitution.full_clean()
|
||||
substitution.save()
|
||||
messages.success(request, 'Substitution added.')
|
||||
return redirect('recipes:edit', identifier=identifier)
|
||||
return render(request, 'recipes/substitution_form.html', {'recipe': ingredient.recipe,
|
||||
'ingredient': ingredient, 'form': form})
|
||||
|
||||
|
||||
@login_required
|
||||
@require_POST
|
||||
def substitution_delete(request, identifier, ingredient_id, substitution_id):
|
||||
item = get_object_or_404(RecipeIngredientSubstitution, pk=substitution_id,
|
||||
ingredient_id=ingredient_id, ingredient__recipe__api_id=identifier,
|
||||
ingredient__recipe__owner=request.user)
|
||||
item.delete()
|
||||
messages.success(request, 'Substitution removed.')
|
||||
return redirect('recipes:edit', identifier=identifier)
|
||||
|
||||
|
||||
def _edit(request, recipe=None, allow_draft_resume=False):
|
||||
creating = recipe is None or recipe.pk is None
|
||||
recipe = recipe or Recipe(owner=request.user)
|
||||
@@ -196,11 +284,14 @@ def create_variation(request, identifier):
|
||||
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, display_order=item.display_order,
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user