"""Atomic package allocation shared by the web inventory and MCP API.""" import hashlib from decimal import Decimal, InvalidOperation from django.contrib.auth import get_user_model from django.db import transaction from django.utils import timezone from food.models import FoodProduct, InventoryConsumption, InventoryConsumptionLine, KitchenInventoryItem FACTORS = {'mg': ('mass', Decimal('.001')), '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 StockError(ValueError): pass def normalized(amount, unit): if unit not in FACTORS: raise StockError('Unsupported unit.') try: input_value = Decimal(str(amount)) value = input_value * FACTORS[unit][1] except (InvalidOperation, TypeError): raise StockError('Enter a valid amount.') from None if (not value.is_finite() or value <= 0 or value > Decimal('9999999.999') or input_value != input_value.quantize(Decimal('.001')) or value != value.quantize(Decimal('.001'))): raise StockError('Enter a positive amount with at most three decimal places in the base unit.') if FACTORS[unit][0] in ('pieces', 'packs', 'portions') and value != value.to_integral_value(): raise StockError('Count units must be whole numbers.') return value, FACTORS[unit][0] def _package_stock(item): if item.original_amount is None: return Decimal(item.quantity), 'packs', 'packs' unit = item.inventory_unit return item.remaining_amount * FACTORS[unit][1], FACTORS[unit][0], unit def stock(user, product, location_id=None, lock=False): if product.owner_id != user.pk: raise StockError('Product not found.') qs = KitchenInventoryItem.objects.filter(user=user, product=product, archived_at__isnull=True) if location_id is not None: qs = qs.filter(location_id=location_id) if lock: qs = qs.select_for_update() return list(qs.order_by('pk')) def materialize_packages(item): """Turn a newly added count into separate packages when a size is known.""" if item.original_amount is None and item.product.package_amount and item.product.package_unit: item.original_amount = item.product.package_amount item.remaining_amount = item.product.package_amount item.inventory_unit = item.product.package_unit if item.original_amount is None: return item count = item.quantity item.quantity = 1 item.full_clean() item.save() for _ in range(count - 1): KitchenInventoryItem.objects.create(user=item.user, product=item.product, quantity=1, location=item.location, category=item.category, notes=item.notes, opened=False, original_amount=item.original_amount, remaining_amount=item.original_amount, inventory_unit=item.inventory_unit, best_before=item.best_before, purchase_batch=item.purchase_batch) return item def preview(user, product, amount, unit, package_id=None, location_id=None, lock=False): requested, dimension = normalized(amount, unit) items = stock(user, product, location_id, lock) if package_id is not None: items = [item for item in items if str(item.api_id) == str(package_id)] if not items: raise StockError('Package not found.') compatible = [] for item in items: available, kind, native_unit = _package_stock(item) if kind == dimension and available > 0: compatible.append((item, available, native_unit)) compatible.sort(key=lambda row: (not row[0].opened, row[0].best_before is None, row[0].best_before or timezone.datetime.max.date(), row[0].added_at, row[0].pk)) total = sum((row[1] for row in compatible), Decimal(0)) left = requested deductions = [] for item, available, native_unit in compatible: if left <= 0: break take = min(left, available) native = take / FACTORS[native_unit][1] deductions.append({'package': item, 'amount': native, 'unit': native_unit, 'before': available / FACTORS[native_unit][1], 'after': (available - take) / FACTORS[native_unit][1]}) left -= take factor = FACTORS[unit][1] return {'requested': requested / factor, 'unit': unit, 'total': total / factor, 'shortage': max(left, Decimal(0)) / factor, 'deductions': deductions} def consume(user, product, amount, unit, *, package_id=None, source='manual', source_reference='', description='', idempotency_key='', allow_partial=False): if source not in ('manual', 'mcp', 'recipe'): raise StockError('Invalid source.') if idempotency_key and len(idempotency_key) > 128: raise StockError('Idempotency key is too long.') requested, _ = normalized(amount, unit) signature = hashlib.sha256(f'{product.pk}|{requested}|{unit}|{package_id or ""}|{source}|{source_reference}|{description}|{allow_partial}'.encode()).hexdigest() with transaction.atomic(): # Serializes even on databases where select_for_update on inventory rows is limited. get_user_model().objects.select_for_update().get(pk=user.pk) if idempotency_key: previous = InventoryConsumption.objects.filter(user=user, idempotency_key=idempotency_key).first() if previous: if previous.request_signature != signature: raise StockError('Idempotency key was used for another request.') return previous plan = preview(user, product, amount, unit, package_id, lock=True) if plan['shortage'] and not allow_partial: raise StockError(f"Insufficient stock: shortage {plan['shortage']} {unit}.") if not plan['deductions']: raise StockError('No compatible stock available.') consumed = plan['requested'] - plan['shortage'] operation = InventoryConsumption.objects.create(user=user, product=product, amount=consumed, unit=unit, source=source, source_reference=source_reference[:255], description=description[:255], idempotency_key=idempotency_key, request_signature=signature) for deduction in plan['deductions']: item = deduction['package'] before_opened, before_opened_at = item.opened, item.opened_at if item.original_amount is None: item.quantity = int(deduction['after']) or 1 else: item.remaining_amount = deduction['after'] if deduction['after'] == 0: item.archived_at = timezone.now() elif not item.opened: item.opened = True item.opened_at = timezone.now() item.save(update_fields=('quantity', 'remaining_amount', 'opened', 'opened_at', 'archived_at', 'updated_at')) InventoryConsumptionLine.objects.create(transaction=operation, package=item, amount=deduction['amount'], unit=deduction['unit'], before_amount=deduction['before'], after_amount=deduction['after'], before_opened=before_opened, before_opened_at=before_opened_at) return operation def undo(user, operation_id): with transaction.atomic(): get_user_model().objects.select_for_update().get(pk=user.pk) operation = InventoryConsumption.objects.filter(user=user, pk=operation_id).first() if not operation or operation.reverses_id or hasattr(operation, 'reversal'): raise StockError('Consumption cannot be undone.') lines = list(operation.lines.select_related('package').order_by('pk')) for line in lines: item = KitchenInventoryItem.objects.select_for_update().get(pk=line.package_id) current = Decimal(item.quantity) if item.original_amount is None and not item.archived_at else ( Decimal(0) if item.original_amount is None else item.remaining_amount) if current != line.after_amount: raise StockError('Package changed since this consumption. Undo it in reverse order.') if item.archived_at is not None and line.after_amount != 0: raise StockError('Package was removed after this consumption.') reversal = InventoryConsumption.objects.create(user=user, product=operation.product, amount=operation.amount, unit=operation.unit, source=operation.source, description=f'Undo {operation.pk}', reverses=operation) for line in lines: item = line.package if item.original_amount is None: item.quantity = int(line.before_amount) else: item.remaining_amount = line.before_amount item.archived_at = None item.opened, item.opened_at = line.before_opened, line.before_opened_at item.save(update_fields=('quantity', 'remaining_amount', 'archived_at', 'opened', 'opened_at', 'updated_at')) InventoryConsumptionLine.objects.create(transaction=reversal, package=item, amount=line.amount, unit=line.unit, before_amount=line.after_amount, after_amount=line.before_amount) return reversal