"""Atomic package allocation shared by the web inventory and MCP API.""" import hashlib from decimal import Decimal, InvalidOperation, ROUND_HALF_UP 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)), 'inner_packs': ('inner_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 _nested_amount_for_pieces(item, piece_count): """Return the rounded package-unit balance implied by whole nested pieces.""" full_packs, loose_pieces = divmod(piece_count, item.pieces_per_inner_pack) amount = item.inner_pack_amount * full_packs if loose_pieces: amount += (item.inner_pack_amount * loose_pieces / item.pieces_per_inner_pack).quantize( Decimal('.001'), rounding=ROUND_HALF_UP) return amount def _nested_count_for_amount(item, remaining_amount): """Find an exact whole-piece balance for a measured remainder.""" low, high = 0, item.remaining_pieces while low < high: middle = (low + high) // 2 if _nested_amount_for_pieces(item, middle) < remaining_amount: low = middle + 1 else: high = middle for candidate in (low, low - 1): if 0 <= candidate <= item.remaining_pieces and _nested_amount_for_pieces(item, candidate) == remaining_amount: return candidate raise StockError('This measured amount does not match a whole number of nested pieces.') 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.pieces_per_package is not None: item.original_amount = Decimal(item.pieces_per_package) item.remaining_amount = Decimal(item.remaining_pieces) item.inventory_unit = 'pieces' 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, pieces_per_package=item.pieces_per_package, remaining_pieces=item.pieces_per_package, piece_amount=item.piece_amount, inner_packs_per_package=item.inner_packs_per_package, pieces_per_inner_pack=item.pieces_per_inner_pack, inner_pack_amount=item.inner_pack_amount, inner_pack_label=item.inner_pack_label, piece_label=item.piece_label, 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 = [] missing_piece_amount = False for item in items: available, kind, native_unit = _package_stock(item) if dimension == 'inner_packs' and item.inner_packs_per_package: available = Decimal(item.remaining_pieces // item.pieces_per_inner_pack) kind = 'inner_packs' if dimension == 'pieces' and item.pieces_per_package is not None: if item.inner_packs_per_package is None and kind != 'pieces' and item.piece_amount is None: missing_piece_amount = True continue available = Decimal(item.remaining_pieces) kind = 'pieces' if kind == dimension and available > 0: compatible.append((item, available, native_unit)) if not compatible and missing_piece_amount: raise StockError('Set an explicit amount per piece before consuming this weighed package by pieces.') 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_factor = FACTORS[native_unit][1] before_native = item.remaining_amount if item.remaining_amount is not None else Decimal(item.quantity) before_pieces = item.remaining_pieces after_pieces = before_pieces if item.inner_packs_per_package is not None and dimension in ('pieces', 'inner_packs'): piece_count = int(take) * (item.pieces_per_inner_pack if dimension == 'inner_packs' else 1) after_pieces = before_pieces - piece_count native = before_native - _nested_amount_for_pieces(item, after_pieces) elif dimension == 'pieces' and FACTORS[native_unit][0] != 'pieces': native = item.piece_amount * take if take == item.remaining_pieces: native = before_native # The last piece takes the precise residual. elif native > before_native: raise StockError('The amount per piece exceeds remaining package stock.') else: native = take / native_factor if before_pieces is not None and item.inner_packs_per_package is None: if dimension == 'pieces': after_pieces -= int(take) elif take == available: after_pieces = 0 elif item.piece_amount is None: raise StockError('Set an explicit amount per piece before partially consuming measured stock.') else: piece_count = native / item.piece_amount if piece_count != piece_count.to_integral_value(): raise StockError('This amount does not correspond to whole pieces at the configured amount per piece.') if piece_count > before_pieces: raise StockError('The amount exceeds the remaining piece count.') after_pieces -= int(piece_count) elif before_pieces is not None and item.inner_packs_per_package is not None and dimension not in ('pieces', 'inner_packs'): after_pieces = 0 if take == available else _nested_count_for_amount(item, before_native - native) if native != native.quantize(Decimal('.001')): raise StockError('The piece conversion needs more than three decimal places; use a measured amount instead.') nested_balance = None if item.inner_packs_per_package is not None: full_inner, loose = divmod(after_pieces, item.pieces_per_inner_pack) balance = [] if full_inner: label = item.inner_pack_label or 'inner pack' balance.append(f'{full_inner} unopened {label}{"s" if full_inner != 1 else ""}') if loose: label = item.inner_pack_label or 'inner pack' piece_label = item.piece_label or 'piece' balance.append(f'1 opened {label} with {loose} {piece_label}{"s" if loose != 1 else ""} left') nested_balance = ' + '.join(balance) if balance else 'no inner packs remaining' deductions.append({'package': item, 'amount': native, 'unit': native_unit, 'before': before_native, 'after': before_native - native, 'before_pieces': before_pieces, 'after_pieces': after_pieces, 'after_inner_pack_balance': nested_balance}) 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'] item.remaining_pieces = deduction['after_pieces'] 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', 'remaining_pieces', '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, before_pieces=deduction['before_pieces'], after_pieces=deduction['after_pieces']) 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.remaining_pieces != line.after_pieces: raise StockError('Piece count 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.remaining_pieces = line.before_pieces item.archived_at = None item.opened, item.opened_at = line.before_opened, line.before_opened_at item.save(update_fields=('quantity', 'remaining_amount', 'remaining_pieces', '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, before_pieces=line.after_pieces, after_pieces=line.before_pieces) return reversal