Files
Django_TasksApp/main/recipes/services/analysis.py
T
2026-10-12 09:37:04 +02:00

224 lines
12 KiB
Python

"""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}