269 lines
14 KiB
Python
269 lines
14 KiB
Python
"""Owner-scoped grocery mutations and conservative recipe import."""
|
|
from decimal import Decimal, InvalidOperation
|
|
|
|
from django.db import transaction
|
|
from django.db.models import Q
|
|
from django.utils import timezone
|
|
|
|
from food.models import FoodProduct, InventoryLocation, KitchenInventoryItem
|
|
from recipes.models import Recipe
|
|
from recipes.services.analysis import AnalysisError, analyze, physical_amount
|
|
from .models import GroceryItem, GroceryRecipeDemand, GrocerySource
|
|
|
|
UNIT_FACTORS = {'g': ('mass', Decimal(1)), 'kg': ('mass', Decimal(1000)),
|
|
'ml': ('volume', Decimal(1)), 'L': ('volume', Decimal(1000)),
|
|
'pieces': ('pieces', Decimal(1)), 'packs': ('packs', Decimal(1)),
|
|
'portions': ('portions', Decimal(1))}
|
|
|
|
|
|
class GroceryError(ValueError):
|
|
pass
|
|
|
|
|
|
def amount(value):
|
|
try:
|
|
number = Decimal(str(value))
|
|
if not number.is_finite() or number <= 0 or number > Decimal('9999999.999') or number != number.quantize(Decimal('.001')):
|
|
raise GroceryError('Enter a positive quantity with at most three decimal places.')
|
|
return number
|
|
except (InvalidOperation, TypeError, ValueError):
|
|
raise GroceryError('Enter a valid positive quantity.') from None
|
|
|
|
|
|
def product_for(user, identifier):
|
|
if not identifier:
|
|
return None
|
|
return FoodProduct.objects.filter(owner=user, api_id=identifier).first() or _raise('Product not found.')
|
|
|
|
|
|
def _raise(message):
|
|
raise GroceryError(message)
|
|
|
|
|
|
@transaction.atomic
|
|
def add(user, *, name, quantity, unit, category='', product=None, notes='', idempotency_key=''):
|
|
name = str(name).strip()
|
|
if not name or len(name) > 180:
|
|
raise GroceryError('Enter a name of at most 180 characters.')
|
|
if unit not in dict(GroceryItem._meta.get_field('unit').choices):
|
|
raise GroceryError('Choose a supported unit.')
|
|
if product and product.owner_id != user.pk:
|
|
raise GroceryError('Product not found.')
|
|
if len(category) > 80 or len(idempotency_key) > 100:
|
|
raise GroceryError('Category or idempotency key is too long.')
|
|
quantity = amount(quantity)
|
|
if idempotency_key:
|
|
existing = GroceryItem.objects.filter(user=user, idempotency_key=idempotency_key).first()
|
|
if existing:
|
|
if (existing.name, existing.quantity, existing.unit, existing.category, existing.product_id, existing.notes) != (name, quantity, unit, category, product.pk if product else None, notes):
|
|
raise GroceryError('Idempotency key was used with different item details.')
|
|
return existing
|
|
if not idempotency_key and unit in UNIT_FACTORS:
|
|
kind, factor = UNIT_FACTORS[unit]
|
|
candidates = GroceryItem.objects.select_for_update().filter(user=user,
|
|
status=GroceryItem.Status.NEEDED, category=category)
|
|
for existing in candidates:
|
|
if ((product and existing.product_id != product.pk) or
|
|
(not product and (existing.product_id or existing.name.casefold() != name.casefold())) or
|
|
existing.unit not in UNIT_FACTORS or UNIT_FACTORS[existing.unit][0] != kind):
|
|
continue
|
|
converted = quantity * factor / UNIT_FACTORS[existing.unit][1]
|
|
if converted != converted.quantize(Decimal('.001')):
|
|
continue
|
|
existing.quantity += converted
|
|
if notes and notes not in existing.notes:
|
|
existing.notes = '\n'.join(filter(None, (existing.notes, notes)))
|
|
existing.full_clean()
|
|
existing.save()
|
|
return existing
|
|
item = GroceryItem(user=user, name=name, quantity=quantity, unit=unit,
|
|
category=category, product=product, notes=notes,
|
|
idempotency_key=idempotency_key)
|
|
item.full_clean()
|
|
item.save()
|
|
return item
|
|
|
|
|
|
def edit(user, identifier, changes):
|
|
with transaction.atomic():
|
|
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier).first()
|
|
if item is None:
|
|
raise GroceryError('Grocery item not found.')
|
|
allowed = {'name', 'quantity', 'unit', 'category', 'notes', 'status', 'product_id'}
|
|
if set(changes) - allowed:
|
|
raise GroceryError('Unsupported grocery field.')
|
|
for key, value in changes.items():
|
|
if key == 'quantity':
|
|
value = amount(value)
|
|
elif key == 'product_id':
|
|
item.product = product_for(user, value)
|
|
continue
|
|
elif key == 'status':
|
|
if value not in GroceryItem.Status.values:
|
|
raise GroceryError('Invalid purchase status.')
|
|
item.purchased_at = timezone.now() if value == GroceryItem.Status.PURCHASED else None
|
|
elif key == 'name':
|
|
value = str(value).strip()
|
|
setattr(item, key, value)
|
|
item.full_clean()
|
|
item.save()
|
|
return item
|
|
|
|
|
|
def search(user, *, query='', category='', product=None, status='needed'):
|
|
items = GroceryItem.objects.filter(user=user).select_related('product').prefetch_related('sources__recipe')
|
|
if query:
|
|
items = items.filter(Q(name__icontains=query) | Q(notes__icontains=query))
|
|
if category:
|
|
items = items.filter(category=category)
|
|
if product:
|
|
items = items.filter(product=product)
|
|
if status != 'all':
|
|
if status not in GroceryItem.Status.values:
|
|
raise GroceryError('Invalid purchase status.')
|
|
items = items.filter(status=status)
|
|
return items
|
|
|
|
|
|
@transaction.atomic
|
|
def add_purchased_to_inventory(user, identifier, *, product, location):
|
|
"""Explicitly convert one purchased grocery row into owned kitchen stock."""
|
|
item = GroceryItem.objects.select_for_update().filter(user=user, pk=identifier,
|
|
status=GroceryItem.Status.PURCHASED).first()
|
|
if item is None:
|
|
raise GroceryError('Purchased grocery item not found.')
|
|
if item.inventory_transferred_at:
|
|
raise GroceryError('This grocery item was already added to inventory.')
|
|
if product.owner_id != user.pk:
|
|
raise GroceryError('Product not found.')
|
|
location_name = ' '.join(location.split())
|
|
if not location_name or len(location_name) > 100:
|
|
raise GroceryError('Enter a kitchen location.')
|
|
place, _ = InventoryLocation.objects.get_or_create(user=user, name__iexact=location_name,
|
|
defaults={'name': location_name})
|
|
if item.unit in ('pieces', 'packs'):
|
|
if item.quantity != item.quantity.to_integral_value():
|
|
raise GroceryError('Count units must be whole numbers.')
|
|
if item.quantity > 1000:
|
|
raise GroceryError('Transfer at most 1,000 count units at a time.')
|
|
stock = KitchenInventoryItem(user=user, product=product, location=place,
|
|
quantity=1 if item.unit == 'pieces' else int(item.quantity))
|
|
if item.unit == 'pieces':
|
|
stock.original_amount = Decimal(1)
|
|
stock.remaining_amount = Decimal(1)
|
|
stock.inventory_unit = 'pieces'
|
|
elif item.unit in ('g', 'kg', 'ml', 'L'):
|
|
factor = Decimal(1000) if item.unit in ('kg', 'L') else Decimal(1)
|
|
stock = KitchenInventoryItem(user=user, product=product, location=place, quantity=1,
|
|
original_amount=item.quantity * factor, remaining_amount=item.quantity * factor,
|
|
inventory_unit='g' if item.unit in ('g', 'kg') else 'ml')
|
|
else:
|
|
raise GroceryError('Set a weight, volume, or whole count before adding to inventory.')
|
|
stock.full_clean()
|
|
stock.save()
|
|
if item.unit == 'packs':
|
|
from food.services.inventory_consumption import materialize_packages
|
|
materialize_packages(stock)
|
|
if item.unit == 'pieces':
|
|
for _ in range(int(item.quantity) - 1):
|
|
KitchenInventoryItem.objects.create(user=user, product=product, location=place,
|
|
quantity=1, original_amount=Decimal(1), remaining_amount=Decimal(1),
|
|
inventory_unit='pieces')
|
|
# Keep the purchased grocery row for history; prevent duplicate transfer with a durable link.
|
|
item.inventory_transfer = stock
|
|
item.inventory_transferred_at = timezone.now()
|
|
item.save(update_fields=['inventory_transfer', 'inventory_transferred_at', 'updated_at'])
|
|
return stock
|
|
|
|
|
|
def _compatible(item, name, product, unit):
|
|
if product:
|
|
if item.product_id != product.pk:
|
|
return False
|
|
elif item.product_id or item.name.casefold() != name.casefold():
|
|
return False
|
|
return item.unit == unit
|
|
|
|
|
|
def recipe_preview(user, recipe, servings=None, *, include_optional=False, substitutions=None):
|
|
if recipe.owner_id != user.pk:
|
|
raise GroceryError('Recipe not found.')
|
|
try:
|
|
result = analyze(recipe, user, servings, include_optional=include_optional,
|
|
substitutions=substitutions or {})
|
|
except AnalysisError as exc:
|
|
raise GroceryError(str(exc)) from exc
|
|
proposed = []
|
|
existing = list(search(user))
|
|
demands = list(GroceryRecipeDemand.objects.filter(user=user))
|
|
for line in result['lines']:
|
|
if line['status'] == 'optional':
|
|
continue
|
|
product = line['product']
|
|
raw_quantity, raw_unit = line['quantity'], line['unit']
|
|
chosen = next((s for s in line['substitutions'] if str(s.pk) == line['selected_substitution']), None) or line['ingredient']
|
|
normalized, unit = physical_amount(raw_quantity, raw_unit, chosen.amount_per_unit,
|
|
chosen.amount_per_unit_unit)
|
|
if normalized is None:
|
|
normalized, unit = raw_quantity, raw_unit
|
|
group = next((g for g in result['groups'] if product and g['product'].pk == product.pk and g['unit'] == unit), None)
|
|
stock = group['plan']['total'] if group and group['plan'] else None
|
|
# Allocate known stock and existing list coverage across lines once, including repeat ingredients.
|
|
related = [item for item in existing if _compatible(item, line['name'], product, unit)]
|
|
matching_demands = [d for d in demands if d.unit == unit and
|
|
((product and d.product_id == product.pk) or
|
|
(not product and not d.product_id and d.name.casefold() == line['name'].casefold()))]
|
|
prior = sum((d.quantity for d in matching_demands), Decimal(0))
|
|
same_recipe = sum((d.quantity for d in matching_demands if d.recipe_id == recipe.pk and
|
|
d.ingredient_id == line['ingredient'].pk), Decimal(0))
|
|
additional = max(Decimal(0), normalized - same_recipe)
|
|
previous = [p for p in proposed if p['product_id'] == (product.pk if product else None) and
|
|
p['unit'] == unit]
|
|
used_stock = sum((p['stock_used'] for p in previous), Decimal(0))
|
|
stock_used = min(additional, max(Decimal(0), stock - prior - used_stock)) if stock is not None else Decimal(0)
|
|
listed = sum((item.quantity for item in related), Decimal(0))
|
|
prior_unmet = max(Decimal(0), prior - (stock or Decimal(0)))
|
|
used_list = sum((p['list_used'] for p in previous if p['name'].casefold() == line['name'].casefold()), Decimal(0))
|
|
list_used = min(additional - stock_used, max(Decimal(0), listed - prior_unmet - used_list))
|
|
missing = max(Decimal(0), additional - stock_used - list_used)
|
|
uncertain = stock is None or not product
|
|
proposed.append({'ingredient': line['ingredient'], 'name': line['name'], 'quantity': normalized,
|
|
'unit': unit, 'product': product, 'product_id': product.pk if product else None,
|
|
'selected_substitution': line['selected_substitution'],
|
|
'stock_used': stock_used, 'list_used': list_used, 'missing': missing,
|
|
'uncertain': uncertain, 'reason': line['reason'] or ('Stock quantity or product match is unknown.' if uncertain else ''),
|
|
'source': line['source']})
|
|
return {'recipe': recipe, 'servings': result['servings'], 'lines': proposed,
|
|
'substitutions': result['selected_substitutions'], 'include_optional': include_optional,
|
|
'requires_review': any(line['uncertain'] for line in proposed)}
|
|
|
|
|
|
@transaction.atomic
|
|
def apply_recipe(user, recipe, servings=None, *, include_optional=False, substitutions=None,
|
|
confirmed_uncertain=False):
|
|
# Lock the user's rows before recalculating coverage to avoid concurrent duplicate additions.
|
|
list(GroceryItem.objects.select_for_update().filter(user=user))
|
|
plan = recipe_preview(user, recipe, servings, include_optional=include_optional,
|
|
substitutions=substitutions)
|
|
if plan['requires_review'] and not confirmed_uncertain:
|
|
raise GroceryError('Review uncertain ingredients before adding them.')
|
|
for line in plan['lines']:
|
|
if line['missing'] > 0:
|
|
item = next((item for item in search(user) if _compatible(item, line['name'], line['product'], line['unit'])
|
|
and item.category == recipe.category), None)
|
|
if item:
|
|
item.quantity += line['missing']
|
|
item.full_clean()
|
|
item.save()
|
|
else:
|
|
item = add(user, name=line['name'], quantity=line['missing'], unit=line['unit'],
|
|
category=recipe.category, product=line['product'])
|
|
GrocerySource.objects.update_or_create(item=item, recipe=recipe, ingredient=line['ingredient'],
|
|
selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
|
|
defaults={'requested_quantity': line['quantity'], 'requested_unit': line['unit']})
|
|
GroceryRecipeDemand.objects.update_or_create(user=user, recipe=recipe,
|
|
ingredient=line['ingredient'], selection_key=str(plan['substitutions'].get(str(line['ingredient'].pk), '')),
|
|
defaults={'name': line['name'], 'product': line['product'], 'quantity': line['quantity'],
|
|
'unit': line['unit']})
|
|
return plan
|