diff --git a/main/MCP.md b/main/MCP.md index 6a38b9d..5314d8d 100644 --- a/main/MCP.md +++ b/main/MCP.md @@ -62,6 +62,10 @@ Image interpretation belongs to the AI client. For a grocery photograph, identif For ambiguous candidates, ask the user to select one or supply more identifying details. Report batch item statuses individually: `added`, `needs_review`, or `skipped`. A batch can return `partial_success`; successful items remain added while failed items do not leave partial product or inventory writes. A changed payload with the same idempotency key returns a conflict. +## Partial inventory use + +`inventory_get_stock` returns owned products, remaining totals, and individual packages. Use a product ID for a definite match; a text query returns candidates. `inventory_preview_consumption` is read only and shows package deductions and any shortage. `inventory_consume` requires a product ID, positive decimal amount, compatible unit, and idempotency key. It uses opened packages first, then best-before date and age. Set `allow_partial` only after the user explicitly accepts a shortage. `inventory_undo_consumption` records a reversal when the affected package quantities have not changed. All four tools enforce the existing inventory read or write scopes through the HTTP API. + Example tool arguments: ```json diff --git a/main/food/api.py b/main/food/api.py index b24cb69..694a5ae 100644 --- a/main/food/api.py +++ b/main/food/api.py @@ -26,6 +26,7 @@ from .services.logging import apply_product_snapshot from .services.openfoodfacts import OpenFoodFactsError from .services.product_resolution import (create_manual, external_matches, import_off, local_matches, match_data) +from .services.inventory_consumption import FACTORS, StockError, consume as consume_stock, preview as preview_stock, stock as stock_packages, undo as undo_stock SCOPES = {'food:read', 'food:write', 'inventory:read', 'inventory:write'} NUTRIENTS = ('calories_kcal', 'carbohydrates_g', 'protein_g', 'fat_g', 'fibre_g', 'sugars_g', 'salt_g') @@ -200,6 +201,8 @@ def _inventory_data(item): 'location': item.location.name, 'category': item.category.name if item.category else None, 'notes': item.notes, 'opened': item.opened, 'remaining_amount': str(item.remaining_amount) if item.remaining_amount is not None else None, + 'original_amount': str(item.original_amount) if item.original_amount is not None else None, + 'unit': item.inventory_unit or 'packs', 'status': item.package_status, 'best_before': item.best_before.isoformat() if item.best_before else None, 'added_at': item.added_at.isoformat(), 'updated_at': item.updated_at.isoformat()} @@ -547,9 +550,12 @@ def inventory_list(request): def _save_inventory(request, data, item=None): + creating = item is None + was_count_only = item is not None and item.original_amount is None if item is None: item = KitchenInventoryItem(user=request.api_user) - allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount'} + allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount', + 'original_amount', 'unit', 'purchase_batch'} if set(data) - allowed: raise ValueError('Unknown inventory fields.') if 'product_id' in data: @@ -579,14 +585,35 @@ def _save_inventory(request, data, item=None): raise ValueError('opened must be a boolean.') item.opened = data['opened'] if 'remaining_amount' in data: - item.remaining_amount = (_decimal(data['remaining_amount'], 'remaining_amount') - if data['remaining_amount'] is not None else None) + new_remaining = (_decimal(data['remaining_amount'], 'remaining_amount') + if data['remaining_amount'] is not None else None) + if not creating and new_remaining != item.remaining_amount: + raise ValueError('Use inventory consumption or undo to change remaining stock.') + item.remaining_amount = new_remaining + if 'original_amount' in data: + new_original = _decimal(data['original_amount'], 'original_amount') if data['original_amount'] is not None else None + if not creating and not was_count_only and new_original != item.original_amount: + raise ValueError('Existing package size cannot be changed.') + item.original_amount = new_original + if 'unit' in data: + if not creating and not was_count_only and data['unit'] != item.inventory_unit: + raise ValueError('Existing package unit cannot be changed.') + item.inventory_unit = str(data['unit']) + if 'purchase_batch' in data: + item.purchase_batch = str(data['purchase_batch'])[:100] if 'best_before' in data: item.best_before = _date(data['best_before'], request.api_user) if data['best_before'] else None if not item.product_id or not item.location_id: raise ValueError('product_id and location are required.') + if creating and item.original_amount is None and item.product.package_amount: + item.original_amount, item.inventory_unit = item.product.package_amount, item.product.package_unit + if item.original_amount is not None and item.remaining_amount is None: + item.remaining_amount = item.original_amount item.full_clean() item.save() + if creating or (was_count_only and item.original_amount is not None): + from .services.inventory_consumption import materialize_packages + materialize_packages(item) return item, None @@ -601,17 +628,20 @@ def inventory_create(request): @api_view('inventory:read', ('GET',)) def inventory_detail(request, identifier): - item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first() + item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier, + archived_at__isnull=True).select_related('product', 'location', 'category').first() return JsonResponse(_inventory_data(item)) if item else error('inventory_item_not_found', 'Inventory item not found.', 404) @api_view('inventory:write', ('PATCH', 'DELETE')) def inventory_change(request, identifier): - item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier).select_related('product', 'location', 'category').first() + item = KitchenInventoryItem.objects.filter(user=request.api_user, api_id=identifier, + archived_at__isnull=True).select_related('product', 'location', 'category').first() if item is None: return error('inventory_item_not_found', 'Inventory item not found.', 404) if request.method == 'DELETE': - item.delete() + item.archived_at = timezone.now() + item.save(update_fields=('archived_at', 'updated_at')) return JsonResponse({'deleted': True}) item, failure = _save_inventory(request, _json(request), item) return failure or JsonResponse(_inventory_data(item)) @@ -695,3 +725,93 @@ def inventory_item(request, identifier): if request.method == 'GET': return inventory_detail.__wrapped__(request, identifier) return inventory_change.__wrapped__(request, identifier) + + +def _stock_product(request, identifier): + return FoodProduct.objects.filter(owner=request.api_user, api_id=_uuid(identifier)).first() + + +def _stock_result(plan): + return {'requested': str(plan['requested']), 'unit': plan['unit'], + 'available': str(plan['total']), 'shortage': str(plan['shortage']), + 'deductions': [{'package_id': str(row['package'].api_id), + 'amount': str(row['amount']), 'unit': row['unit'], + 'before': str(row['before']), 'after': str(row['after'])} + for row in plan['deductions']]} + + +@api_view('inventory:read', ('GET',)) +def inventory_stock(request): + identifier = request.GET.get('product_id') + if identifier: + product = _stock_product(request, identifier) + if product is None: + return error('product_not_found', 'Product not found.', 404) + products = [product] + else: + query = request.GET.get('query', '').strip()[:100] + if not query: + return error('product_required', 'Provide product_id or query.') + products = list(FoodProduct.objects.filter(owner=request.api_user, + inventory_items__archived_at__isnull=True).filter( + Q(product_name__icontains=query) | Q(barcode=query)).distinct()[:20]) + result = [] + location = request.GET.get('location_id') + for product in products: + packages = stock_packages(request.api_user, product, location) + groups = {} + for item in packages: + unit = item.inventory_unit or 'packs' + amount = item.remaining_amount if item.remaining_amount is not None else Decimal(item.quantity) + dimension, factor = FACTORS[unit] + base_unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, unit) + groups[base_unit] = groups.get(base_unit, Decimal(0)) + amount * factor + result.append({'product_id': str(product.api_id), 'product_name': product.product_name, + 'totals': {unit: str(amount) for unit, amount in groups.items()}, + 'available': any(amount > 0 for amount in groups.values()), + 'packages': [_inventory_data(item) for item in packages]}) + return JsonResponse({'count': len(result), 'products': result}) + + +@api_view('inventory:read', ('POST',)) +def inventory_preview(request): + try: + data = _json(request) + product = _stock_product(request, data['product_id']) + if product is None: + return error('product_not_found', 'Product not found.', 404) + plan = preview_stock(request.api_user, product, data['amount'], data['unit'], data.get('package_id')) + return JsonResponse(_stock_result(plan)) + except (StockError, KeyError, ValueError) as exc: + return error('invalid_consumption', str(exc)) + + +@api_view('inventory:write', ('POST',)) +def inventory_consume(request): + try: + data = _json(request) + product = _stock_product(request, data['product_id']) + if product is None: + return error('product_not_found', 'Product not found.', 404) + key = request.headers.get('Idempotency-Key', '') + if not key: + return error('idempotency_key_required', 'Provide an Idempotency-Key.') + operation = consume_stock(request.api_user, product, data['amount'], data['unit'], + package_id=data.get('package_id'), source='mcp', + source_reference=data.get('source_reference', ''), + description=data.get('description', ''), idempotency_key=key, + allow_partial=data.get('allow_partial') is True) + return JsonResponse({'transaction_id': str(operation.pk), 'amount': str(operation.amount), + 'unit': operation.unit, 'deductions': [{'package_id': str(line.package.api_id), + 'amount': str(line.amount), 'unit': line.unit} for line in operation.lines.select_related('package')]}) + except (StockError, KeyError, ValueError) as exc: + return error('invalid_consumption', str(exc)) + + +@api_view('inventory:write', ('POST',)) +def inventory_undo(request, identifier): + try: + reversal = undo_stock(request.api_user, identifier) + return JsonResponse({'transaction_id': str(reversal.pk), 'reverses': str(reversal.reverses_id)}) + except (StockError, ValueError) as exc: + return error('cannot_undo', str(exc)) diff --git a/main/food/api_schema.py b/main/food/api_schema.py index 91c2c25..725b16c 100644 --- a/main/food/api_schema.py +++ b/main/food/api_schema.py @@ -86,6 +86,10 @@ def schema(request): 'patch': operation('Update own inventory item', 'inventory:write', INVENTORY), 'delete': operation('Delete own inventory item', 'inventory:write'), }, + '/kitchen/stock/': {'get': operation('Read product stock and packages', 'inventory:read')}, + '/kitchen/consumption/preview/': {'post': operation('Preview package deductions without changing stock', 'inventory:read')}, + '/kitchen/consumption/': {'post': operation('Consume stock atomically with Idempotency-Key', 'inventory:write')}, + '/kitchen/consumption/{id}/undo/': {'post': operation('Undo a safe consumption transaction', 'inventory:write')}, }, } for path, methods in document['paths'].items(): @@ -94,6 +98,9 @@ def schema(request): 'schema': {'type': 'string', 'format': 'uuid'}}] if 'post' in methods: methods['post']['responses']['201'] = methods['post']['responses'].pop('200') + for path in ('/kitchen/consumption/preview/', '/kitchen/consumption/', + '/kitchen/consumption/{id}/undo/'): + document['paths'][path]['post']['responses']['200'] = document['paths'][path]['post']['responses'].pop('201') document['paths']['/food/today/']['get']['parameters'] = [{ 'name': 'date', 'in': 'query', 'required': False, 'description': 'Local calendar date; defaults to today in the user time zone.', diff --git a/main/food/api_urls.py b/main/food/api_urls.py index 0204543..8987e16 100644 --- a/main/food/api_urls.py +++ b/main/food/api_urls.py @@ -17,4 +17,8 @@ urlpatterns = [ path('kitchen/items/', api.inventory_collection), path('kitchen/import-groceries/', api.inventory_import_groceries), path('kitchen/items//', api.inventory_item), + path('kitchen/stock/', api.inventory_stock), + path('kitchen/consumption/preview/', api.inventory_preview), + path('kitchen/consumption/', api.inventory_consume), + path('kitchen/consumption//undo/', api.inventory_undo), ] diff --git a/main/food/forms.py b/main/food/forms.py index ae22d11..496f9f7 100644 --- a/main/food/forms.py +++ b/main/food/forms.py @@ -147,16 +147,36 @@ class InventoryItemForm(forms.ModelForm): class Meta: model = KitchenInventoryItem - fields = ('quantity', 'opened', 'best_before', 'notes') + fields = ('quantity', 'original_amount', 'inventory_unit', 'opened', 'best_before', 'notes') widgets = {'quantity': forms.NumberInput(attrs={'min': 1, 'step': 1}), + 'original_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}), 'best_before': forms.DateInput(attrs={'type': 'date'}), 'notes': forms.Textarea(attrs={'rows': 2})} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) + self.fields['inventory_unit'] = forms.ChoiceField(required=False, label='Package unit', + choices=[('', 'Count only (unknown size)')] + [(unit, unit) for unit in + ('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions')]) + self.fields['original_amount'].label = 'Amount per package' if self.instance.pk: self.fields['location_name'].initial = self.instance.location.name self.fields['category_name'].initial = self.instance.category.name if self.instance.category else '' + self.fields['inventory_unit'].initial = self.instance.inventory_unit + + def clean(self): + data = super().clean() + if bool(data.get('original_amount')) != bool(data.get('inventory_unit')): + raise forms.ValidationError('Enter both package amount and unit, or leave both blank.') + if data.get('original_amount') and self.instance.remaining_amount is None: + self.instance.remaining_amount = data['original_amount'] + if self.instance.pk and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount: + raise forms.ValidationError('Existing package sizes cannot be changed after tracking starts.') + if self.instance.pk and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit: + raise forms.ValidationError('Existing package units cannot be changed after tracking starts.') + if self.instance.pk and self.instance.original_amount and data.get('quantity') != 1: + raise forms.ValidationError('A tracked package has a quantity of one.') + return data def clean_location_name(self): value = ' '.join(self.cleaned_data['location_name'].split()) diff --git a/main/food/inventory.py b/main/food/inventory.py index ef0e354..c6deb7c 100644 --- a/main/food/inventory.py +++ b/main/food/inventory.py @@ -1,4 +1,6 @@ from datetime import timedelta +from decimal import Decimal +import re from django.contrib import messages from django.contrib.auth.decorators import login_required @@ -11,7 +13,8 @@ from django.utils import timezone from django.views.decorators.http import require_http_methods, require_POST from .forms import InventoryItemForm, InventoryManualProductForm -from .models import FoodProduct, InventoryCategory, InventoryLocation, KitchenInventoryItem +from .models import FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation, KitchenInventoryItem +from .services.inventory_consumption import FACTORS, StockError, consume, materialize_packages, preview, undo from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search from .services.products import local_products @@ -44,9 +47,26 @@ def overview(request): 'category': ('category__name', 'product__product_name'), 'name': ('product__product_name',), 'recent': ('-added_at',), 'best_before': (F('best_before').asc(nulls_last=True), 'product__product_name')} - items = items.order_by(*orderings.get(sort, orderings['location'])) + items = list(items.order_by(*orderings.get(sort, orderings['location']))) + cards = {} + for item in items: + native_unit = item.inventory_unit or 'packs' + dimension, factor = FACTORS[native_unit] + unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, native_unit) + key = (item.product_id, dimension) + if key not in cards: + choices = {'mg': ('mg', 'g', 'kg'), 'g': ('mg', 'g', 'kg'), 'kg': ('mg', 'g', 'kg'), + 'ml': ('ml', 'L'), 'L': ('ml', 'L')} + cards[key] = {'product': item.product, 'unit': unit, 'packages': [], 'total': Decimal(0), + 'units': choices.get(unit, (unit,)), + 'count_unit': dimension in ('pieces', 'packs', 'portions')} + cards[key]['packages'].append(item) + cards[key]['total'] += (item.remaining_amount if item.remaining_amount is not None + else Decimal(item.quantity)) * factor + recent = InventoryConsumption.objects.filter(user=request.user, reverses__isnull=True).select_related('product').prefetch_related('lines__package').order_by('-created_at')[:8] return render(request, 'food/inventory_overview.html', { - 'items': items, 'query': query, 'sort': sort, 'selected_location': location, + 'items': items, 'cards': list(cards.values()), 'recent_consumption': recent, + 'query': query, 'sort': sort, 'selected_location': location, 'selected_category': category, 'opened': opened, 'use_soon': request.GET.get('use_soon'), 'locations': InventoryLocation.objects.filter(user=request.user), 'categories': InventoryCategory.objects.filter(user=request.user), @@ -61,7 +81,9 @@ def add(request): product = get_object_or_404(FoodProduct, owner=request.user, pk=product_id) if product_id else None query = request.GET.get('q', '').strip()[:100] products = local_products(request.user, query) - form = InventoryItemForm(request.POST or None, initial={'quantity': 1, 'location_name': request.session.get('inventory_location', '')}) if product else None + form = InventoryItemForm(request.POST or None, initial={'quantity': 1, 'location_name': request.session.get('inventory_location', ''), + 'original_amount': product.package_amount if product else None, + 'inventory_unit': product.package_unit if product else ''}) if product else None existing = _owned_items(request.user).filter(product=product) if product else [] if request.method == 'POST': if not product: @@ -75,8 +97,20 @@ def add(request): category, _ = InventoryCategory.objects.get_or_create(user=request.user, name__iexact=category_name, defaults={'name': category_name}) item = form.save(commit=False) item.user, item.product, item.location, item.category = request.user, product, location, category + if item.original_amount is not None: + item.remaining_amount = item.original_amount + if item.quantity > 1: + count = item.quantity + item.quantity = 1 + else: + count = 1 + else: + count = 1 item.full_clean() item.save() + if count > 1: + item.quantity = count + materialize_packages(item) request.session['inventory_location'] = location.name messages.success(request, f'{product.product_name} added. Scan the next item when ready.') return redirect('food:inventory-add') @@ -127,6 +161,15 @@ def manual(request): if request.method == 'POST' and form.is_valid(): product = form.save(commit=False) product.owner = request.user + match = re.fullmatch(r'\s*(\d+(?:[.,]\d+)?)\s*(kg|g|ml|l)\s*', product.package_quantity, re.I) + if match: + amount = Decimal(match.group(1).replace(',', '.')) + unit = match.group(2).lower() + if unit in ('kg', 'l'): + amount *= 1000 + unit = 'g' if unit == 'kg' else 'ml' + if 0 < amount <= Decimal('9999999.999') and amount == amount.quantize(Decimal('.001')): + product.package_amount, product.package_unit = amount, unit product.save() return redirect(f"{reverse('food:inventory-add')}?product={product.pk}") return render(request, 'food/inventory_manual.html', {'form': form}) @@ -136,6 +179,7 @@ def manual(request): @require_http_methods(['GET', 'POST']) def edit(request, pk): item = get_object_or_404(_owned_items(request.user), pk=pk) + was_count_only = item.original_amount is None form = InventoryItemForm(request.POST or None, instance=item) if request.method == 'POST' and form.is_valid(): with transaction.atomic(): @@ -146,8 +190,12 @@ def edit(request, pk): category, _ = InventoryCategory.objects.get_or_create(user=request.user, name__iexact=category_name, defaults={'name': category_name}) item = form.save(commit=False) item.location, item.category = location, category + if item.original_amount is not None and item.remaining_amount is None: + item.remaining_amount = item.original_amount item.full_clean() item.save() + if was_count_only and item.original_amount is not None: + materialize_packages(item) return redirect('food:inventory') return render(request, 'food/inventory_edit.html', {'item': item, 'form': form, 'locations': InventoryLocation.objects.filter(user=request.user), @@ -157,20 +205,27 @@ def edit(request, pk): @login_required @require_POST def change_quantity(request, pk): + action = request.POST.get('action') + if action == 'used': + item = get_object_or_404(_owned_items(request.user), pk=pk) + try: + consume(request.user, item.product, item.remaining_amount if item.original_amount is not None else 1, + item.inventory_unit or 'packs', package_id=item.api_id) + messages.success(request, f'{item.product.product_name} used.') + except StockError as exc: + messages.error(request, str(exc)) + return redirect('food:inventory') + if action != 'increase': + return HttpResponseBadRequest('Invalid action.') with transaction.atomic(): item = get_object_or_404(KitchenInventoryItem.objects.select_for_update(), pk=pk, user=request.user, archived_at__isnull=True) - action = request.POST.get('action') - if action == 'increase': - item.quantity += 1 - elif action == 'used': - if item.quantity == 1: - item.archived_at = timezone.now() - messages.success(request, f'{item.product.product_name} used up.') - else: - item.quantity -= 1 + if item.original_amount is not None: + KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location, + category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount, + inventory_unit=item.inventory_unit, best_before=item.best_before) else: - return HttpResponseBadRequest('Invalid action.') - item.save() + item.quantity += 1 + item.save(update_fields=('quantity', 'updated_at')) return redirect('food:inventory') @@ -179,7 +234,50 @@ def change_quantity(request, pk): def add_existing(request, pk): with transaction.atomic(): item = get_object_or_404(KitchenInventoryItem.objects.select_for_update(), pk=pk, user=request.user, archived_at__isnull=True) - item.quantity += 1 - item.save(update_fields=('quantity', 'updated_at')) + if item.original_amount is not None: + KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location, + category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount, + inventory_unit=item.inventory_unit, best_before=item.best_before) + else: + item.quantity += 1 + item.save(update_fields=('quantity', 'updated_at')) messages.success(request, f'{item.product.product_name} quantity increased.') return redirect('food:inventory-add') + + +@login_required +@require_POST +def preview_consumption(request, pk): + product = get_object_or_404(FoodProduct, pk=pk, owner=request.user) + try: + plan = preview(request.user, product, request.POST.get('amount'), + request.POST.get('unit'), request.POST.get('package_id') or None) + except StockError as exc: + return render(request, 'food/partials/inventory_preview.html', {'error': str(exc)}) + return render(request, 'food/partials/inventory_preview.html', + {'plan': plan, 'product': product, 'package_id': request.POST.get('package_id', '')}) + + +@login_required +@require_POST +def use_amount(request, pk): + product = get_object_or_404(FoodProduct, pk=pk, owner=request.user) + try: + operation = consume(request.user, product, request.POST.get('amount'), request.POST.get('unit'), + package_id=request.POST.get('package_id') or None, + allow_partial=request.POST.get('allow_partial') == 'yes') + messages.success(request, f'Used {operation.amount} {operation.unit} of {product.product_name}.') + except StockError as exc: + messages.error(request, str(exc)) + return redirect('food:inventory') + + +@login_required +@require_POST +def undo_consumption(request, identifier): + try: + undo(request.user, identifier) + messages.success(request, 'Consumption undone.') + except StockError as exc: + messages.error(request, str(exc)) + return redirect('food:inventory') diff --git a/main/food/migrations/0006_inventory_packages_consumption.py b/main/food/migrations/0006_inventory_packages_consumption.py new file mode 100644 index 0000000..681d1ac --- /dev/null +++ b/main/food/migrations/0006_inventory_packages_consumption.py @@ -0,0 +1,90 @@ +# Generated by Django 6.1.1 on 2026-10-11 13:22 + +import django.core.validators +import django.db.models.deletion +import uuid +from django.conf import settings +from django.db import migrations, models + + +def backfill_packages(apps, schema_editor): + Item = apps.get_model('food', 'KitchenInventoryItem') + for item in Item.objects.select_related('product').all().iterator(): + amount = item.product.package_amount + unit = item.product.package_unit + if not amount or not unit: + continue # Unknown-size legacy entries remain count based. + count = item.quantity + remaining = item.remaining_amount if item.remaining_amount is not None else amount + Item.objects.filter(pk=item.pk).update(quantity=1, original_amount=amount, + remaining_amount=remaining, inventory_unit=unit) + for _ in range(count - 1): + copy = Item.objects.create(user_id=item.user_id, product_id=item.product_id, quantity=1, + location_id=item.location_id, category_id=item.category_id, notes=item.notes, + opened=False, original_amount=amount, remaining_amount=amount, + inventory_unit=unit, best_before=item.best_before, archived_at=item.archived_at) + Item.objects.filter(pk=copy.pk).update(added_at=item.added_at, updated_at=item.updated_at) + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0005_package_contents'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name='kitcheninventoryitem', + name='inventory_unit', + field=models.CharField(blank=True, max_length=8), + ), + migrations.AddField( + model_name='kitcheninventoryitem', + name='opened_at', + field=models.DateTimeField(blank=True, null=True), + ), + migrations.AddField( + model_name='kitcheninventoryitem', + name='original_amount', + field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)]), + ), + migrations.AddField( + model_name='kitcheninventoryitem', + name='purchase_batch', + field=models.CharField(blank=True, max_length=100), + ), + migrations.CreateModel( + name='InventoryConsumption', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])), + ('unit', models.CharField(max_length=8)), + ('source', models.CharField(choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')], max_length=16)), + ('source_reference', models.CharField(blank=True, max_length=255)), + ('description', models.CharField(blank=True, max_length=255)), + ('idempotency_key', models.CharField(blank=True, max_length=128)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('product', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='food.foodproduct')), + ('reverses', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='reversal', to='food.inventoryconsumption')), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + migrations.CreateModel( + name='InventoryConsumptionLine', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('amount', models.DecimalField(decimal_places=3, max_digits=10, validators=[django.core.validators.MinValueValidator(0.001)])), + ('unit', models.CharField(max_length=8)), + ('before_amount', models.DecimalField(decimal_places=3, max_digits=10)), + ('after_amount', models.DecimalField(decimal_places=3, max_digits=10)), + ('package', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='consumption_lines', to='food.kitcheninventoryitem')), + ('transaction', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='lines', to='food.inventoryconsumption')), + ], + ), + migrations.AddConstraint( + model_name='inventoryconsumption', + constraint=models.UniqueConstraint(condition=models.Q(('idempotency_key', ''), _negated=True), fields=('user', 'idempotency_key'), name='food_unique_consumption_key'), + ), + migrations.RunPython(backfill_packages, migrations.RunPython.noop), + ] diff --git a/main/food/migrations/0007_inventory_reversal_state.py b/main/food/migrations/0007_inventory_reversal_state.py new file mode 100644 index 0000000..e90fd30 --- /dev/null +++ b/main/food/migrations/0007_inventory_reversal_state.py @@ -0,0 +1,28 @@ +# Generated by Django 6.1.1 on 2026-10-11 13:27 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('food', '0006_inventory_packages_consumption'), + ] + + operations = [ + migrations.AddField( + model_name='inventoryconsumption', + name='request_signature', + field=models.CharField(blank=True, max_length=64), + ), + migrations.AddField( + model_name='inventoryconsumptionline', + name='before_opened', + field=models.BooleanField(default=False), + ), + migrations.AddField( + model_name='inventoryconsumptionline', + name='before_opened_at', + field=models.DateTimeField(blank=True, null=True), + ), + ] diff --git a/main/food/models.py b/main/food/models.py index 2ea37e6..7b9aca6 100644 --- a/main/food/models.py +++ b/main/food/models.py @@ -5,6 +5,7 @@ from django.core.exceptions import ValidationError from django.core.validators import MinValueValidator from django.db import models from django.db.models import Q +from django.utils import timezone NON_NEGATIVE = [MinValueValidator(0)] @@ -172,6 +173,10 @@ class KitchenInventoryItem(models.Model): notes = models.TextField(blank=True) opened = models.BooleanField(default=False) remaining_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE) + original_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE) + inventory_unit = models.CharField(max_length=8, blank=True) + opened_at = models.DateTimeField(null=True, blank=True) + purchase_batch = models.CharField(max_length=100, blank=True) best_before = models.DateField(null=True, blank=True) archived_at = models.DateTimeField(null=True, blank=True) added_at = models.DateTimeField(auto_now_add=True) @@ -179,10 +184,16 @@ class KitchenInventoryItem(models.Model): def clean(self): super().clean() - if self.remaining_amount is not None and (not self.product_id or self.quantity != 1 or not self.opened or - not self.product.package_amount or - self.remaining_amount > self.product.package_amount): - raise ValidationError({'remaining_amount': 'Remaining contents require one opened package with a known package size.'}) + if (self.original_amount is None) != (self.remaining_amount is None): + raise ValidationError('Original and remaining quantities must be supplied together.') + was_count_only = self.pk and KitchenInventoryItem.objects.filter(pk=self.pk, original_amount__isnull=True).exists() + if self.original_amount is not None and ((self.pk is not None and self.quantity != 1 and not was_count_only) or + self.inventory_unit not in ('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions') or + self.remaining_amount > self.original_amount): + raise ValidationError('A package needs one valid unit and remaining quantity within its original quantity.') + if (self.original_amount is not None and self.remaining_amount is not None and + 0 < self.remaining_amount < self.original_amount and not self.opened): + raise ValidationError({'opened': 'A partly used package must be opened.'}) if self.user_id and self.product_id and self.product.owner_id != self.user_id: raise ValidationError({'product': 'Choose one of your own products.'}) if self.user_id and self.location_id and self.location.user_id != self.user_id: @@ -190,6 +201,52 @@ class KitchenInventoryItem(models.Model): if self.user_id and self.category_id and self.category.user_id != self.user_id: raise ValidationError({'category': 'Choose one of your own categories.'}) + def save(self, *args, **kwargs): + if self.opened and self.opened_at is None: + self.opened_at = timezone.now() + super().save(*args, **kwargs) + + @property + def percentage_remaining(self): + if self.original_amount: + return int(self.remaining_amount * 100 / self.original_amount) + return 100 + + @property + def package_status(self): + if self.remaining_amount == 0: + return 'depleted' + return 'opened' if self.opened else 'unopened' + + +class InventoryConsumption(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT) + amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) + unit = models.CharField(max_length=8) + source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')]) + source_reference = models.CharField(max_length=255, blank=True) + description = models.CharField(max_length=255, blank=True) + idempotency_key = models.CharField(max_length=128, blank=True) + request_signature = models.CharField(max_length=64, blank=True) + reverses = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True, related_name='reversal') + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + constraints = [models.UniqueConstraint(fields=('user', 'idempotency_key'), condition=~Q(idempotency_key=''), name='food_unique_consumption_key')] + + +class InventoryConsumptionLine(models.Model): + transaction = models.ForeignKey(InventoryConsumption, on_delete=models.CASCADE, related_name='lines') + package = models.ForeignKey(KitchenInventoryItem, on_delete=models.PROTECT, related_name='consumption_lines') + amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE) + unit = models.CharField(max_length=8) + before_amount = models.DecimalField(max_digits=10, decimal_places=3) + after_amount = models.DecimalField(max_digits=10, decimal_places=3) + before_opened = models.BooleanField(default=False) + before_opened_at = models.DateTimeField(null=True, blank=True) + class PersonalAccessToken(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='personal_access_tokens') diff --git a/main/food/services/inventory_consumption.py b/main/food/services/inventory_consumption.py new file mode 100644 index 0000000..77f300e --- /dev/null +++ b/main/food/services/inventory_consumption.py @@ -0,0 +1,187 @@ +"""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 diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index c16db1e..56b6339 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -61,3 +61,5 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .food-help-popover li{margin:.25rem 0} .food-help-popover .food-help-tip{margin-top:.75rem;color:var(--food-muted)} @media(max-width:600px){.food-help-popover{top:auto!important;left:12px!important;right:12px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;max-height:min(70dvh,560px)}} + +.inventory-product-card{display:grid;gap:.8rem}.inventory-product-heading{display:flex;align-items:center;gap:1rem;min-width:0}.inventory-product-heading img{width:68px;height:68px;object-fit:contain;background:white;border-radius:.6rem}.inventory-product-heading h2{margin:0}.inventory-product-heading p{margin:.25rem 0;overflow-wrap:anywhere}.inventory-packages summary,.inventory-use summary{cursor:pointer;min-height:44px;align-content:center;font-weight:650}.inventory-package-list{display:grid;gap:.65rem;margin:.6rem 0}.inventory-package{display:flex;align-items:center;gap:.8rem;padding:.65rem;border:1px solid var(--food-border);border-radius:.7rem;min-width:0}.inventory-package>div:last-child{min-width:0}.inventory-package p{margin:.2rem 0}.inventory-package small{color:var(--food-muted)}.inventory-package-fill{flex:none;position:relative;width:42px;height:64px;border:2px solid var(--food-muted);border-radius:.3rem;overflow:hidden;background:var(--food-progress-track)}.inventory-package-fill span{position:absolute;bottom:0;left:0;right:0;background:var(--food-green);transition:height .25s ease}.inventory-use-form{display:flex;flex-wrap:wrap;gap:.6rem;align-items:end}.inventory-use-form label{display:grid;gap:.25rem;flex:1;min-width:100px}.inventory-use-form input,.inventory-use-form select{max-width:100%;min-height:44px}.inventory-use-form button{min-height:44px}.inventory-preview{border:1px solid var(--food-border);border-radius:.7rem;padding:.8rem;margin-top:.7rem}.inventory-preview h3{margin:0}.inventory-preview form{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}.inventory-preview form button,.inventory-history button{min-height:44px}.inventory-preview [role=alert]{color:#e9aa72}.inventory-history ul{padding-left:1.2rem}.inventory-history li{margin:.4rem 0}.inventory-history li form{display:inline-block;margin-left:.5rem}@media(max-width:480px){.inventory-product-heading{align-items:flex-start}.inventory-use-form{display:grid;grid-template-columns:1fr 1fr}.inventory-use-form label:nth-child(3){grid-column:1/-1}.inventory-use-form button{grid-column:1/-1}}@media(prefers-reduced-motion:reduce){.inventory-package-fill span{transition:none}} diff --git a/main/food/templates/food/inventory_overview.html b/main/food/templates/food/inventory_overview.html index 879ddee..257fd0c 100644 --- a/main/food/templates/food/inventory_overview.html +++ b/main/food/templates/food/inventory_overview.html @@ -1,6 +1,12 @@ {% extends 'planner/base.html' %}{% load static %} {% block title %}Kitchen Inventory · Tasknest{% endblock %} -{% block content %} +{% block content %}

Kitchen Inventory

What you have and where it lives.

+ Add item
-{% for item in items %}{% if sort == 'location' %}{% ifchanged item.location_id %}

{{ item.location.name }}

{% endifchanged %}{% endif %}
{% if item.product.image_url %}{% endif %}

{{ item.product.product_name }}

{% if item.product.brand %}

{{ item.product.brand }}

{% endif %}

Qty: {{ item.quantity }} · {{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}

{% if item.opened %}Opened{% endif %}{% if item.best_before %}{% if item.best_before < today %}Expired{% elif item.best_before <= soon_date %}Use soon{% else %}Best before{% endif %} {{ item.best_before }}{% endif %}
{% csrf_token %}
Edit
{% empty %}

No inventory items found.

Add your first item
{% endfor %}
{% endblock %} +{% for card in cards %}
+
{% if card.product.image_url %}{% endif %}

{{ card.product.product_name }}

{% if card.product.brand %}

{{ card.product.brand }}

{% endif %}

{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining · {{ card.packages|length }} package{{ card.packages|length|pluralize }}

+
View packages
{% for item in card.packages %}
Pack {{ forloop.counter }} · {{ item.package_status|title }}

{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}

{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}
{% endfor %}
+
Use amount
{% csrf_token %}
+
{% empty %}

No inventory items found.

Add your first item
{% endfor %} +{% if recent_consumption %}

Recent use

    {% for entry in recent_consumption %}
  • {{ entry.created_at|date:'j M, H:i' }} · {{ entry.product.product_name }} · {{ entry.amount|floatformat:-3 }} {{ entry.unit }}
    Package changes
      {% for line in entry.lines.all %}
    • Pack {{ line.package.pk }}: {{ line.before_amount|floatformat:-3 }} → {{ line.after_amount|floatformat:-3 }} {{ line.unit }}
    • {% endfor %}
    {% if not entry.reversal %}
    {% csrf_token %}
    {% else %} · Undone{% endif %}
  • {% endfor %}
{% endif %} +{% endblock %} diff --git a/main/food/templates/food/partials/inventory_preview.html b/main/food/templates/food/partials/inventory_preview.html new file mode 100644 index 0000000..adada62 --- /dev/null +++ b/main/food/templates/food/partials/inventory_preview.html @@ -0,0 +1 @@ +{% if error %}

{{ error }}

{% elif plan %}

Consumption preview

Available: {{ plan.total|floatformat:-3 }} {{ plan.unit }}

    {% for deduction in plan.deductions %}
  • {{ deduction.package.location.name }} · Pack {{ deduction.package.pk }}: −{{ deduction.amount|floatformat:-3 }} {{ deduction.unit }} ({{ deduction.after|floatformat:-3 }} left)
  • {% endfor %}
{% if plan.shortage %}

Shortage: {{ plan.shortage|floatformat:-3 }} {{ plan.unit }}. Choose a partial use explicitly or cancel.

{% endif %}
{% csrf_token %}{% if plan.shortage %}{% endif %}
{% endif %} diff --git a/main/food/test_api.py b/main/food/test_api.py index 9ac13aa..b5383f8 100644 --- a/main/food/test_api.py +++ b/main/food/test_api.py @@ -186,14 +186,42 @@ class FoodApiTests(TestCase): self.assertEqual(len(candidates.json()['candidates']), 2) self.assertEqual(FoodProduct.objects.filter(owner=self.a, product_name='Yoghurt').count(), 2) product = FoodProduct.objects.filter(owner=self.a, brand='Store A').first() - invalid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id), + created = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id), 'quantity': 2, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'}) - self.assertEqual(invalid.status_code, 400) + self.assertEqual(created.status_code, 201) + self.assertEqual(KitchenInventoryItem.objects.filter(user=self.a, product=product).count(), 2) valid = self.call('post', '/api/v1/kitchen/items/', {'product_id': str(product.api_id), 'quantity': 1, 'location': 'Fridge', 'opened': True, 'remaining_amount': '350'}) self.assertEqual(valid.status_code, 201, valid.content) self.assertEqual(valid.json()['remaining_amount'], '350') + def test_inventory_stock_preview_consume_idempotency_undo_and_scopes(self): + product = FoodProduct.objects.create(owner=self.a, product_name='Stock butter', + package_amount=Decimal('250'), package_unit='g') + location = InventoryLocation.objects.create(user=self.a, name='Fridge') + for _ in range(2): + KitchenInventoryItem.objects.create(user=self.a, product=product, location=location, + original_amount=Decimal('250'), remaining_amount=Decimal('250'), inventory_unit='g') + base = '/api/v1/kitchen/' + stock = self.call('get', f'{base}stock/?product_id={product.api_id}').json() + self.assertEqual(stock['products'][0]['totals'], {'g': '500.000'}) + payload = {'product_id': str(product.api_id), 'amount': '300', 'unit': 'g'} + preview = self.call('post', f'{base}consumption/preview/', payload).json() + self.assertEqual([row['amount'] for row in preview['deductions']], ['250.000', '50.000']) + self.assertEqual(self.call('post', f'{base}consumption/', payload).status_code, 400) + result = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1') + self.assertEqual(result.status_code, 200, result.content) + again = self.call('post', f'{base}consumption/', payload, HTTP_IDEMPOTENCY_KEY='stock-1') + self.assertEqual(result.json(), again.json()) + self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '200.000'}) + self.assertEqual(self.call('post', f'{base}consumption/{result.json()["transaction_id"]}/undo/', {}).status_code, 200) + self.assertEqual(self.call('get', f'{base}stock/?product_id={product.api_id}').json()['products'][0]['totals'], {'g': '500.000'}) + self.assertEqual(self.call('get', f'{base}stock/?product_id={self.product_b.api_id}').status_code, 404) + _, read_secret = create_token(self.a, 'Inventory read', ['inventory:read']) + self.assertEqual(self.call('post', f'{base}consumption/preview/', payload, token=read_secret).status_code, 200) + self.assertEqual(self.call('post', f'{base}consumption/', payload, token=read_secret, + HTTP_IDEMPOTENCY_KEY='read-cannot-write').status_code, 403) + def test_barcode_mismatch_does_not_reuse_similar_product(self): FoodProduct.objects.create(owner=self.a, product_name='Milk', brand='Example', barcode='11111', package_amount=Decimal('1000'), package_unit='ml', package_quantity='1000 ml') diff --git a/main/food/test_inventory.py b/main/food/test_inventory.py index 04f2918..bebce4e 100644 --- a/main/food/test_inventory.py +++ b/main/food/test_inventory.py @@ -4,7 +4,7 @@ from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse -from .models import FoodProduct, KitchenInventoryItem +from .models import FoodProduct, InventoryLocation, KitchenInventoryItem class KitchenInventoryTests(TestCase): @@ -43,3 +43,28 @@ class KitchenInventoryTests(TestCase): product = FoodProduct.objects.get(owner=self.user, product_name='Loose onions') self.assertRedirects(response, f"{reverse('food:inventory-add')}?product={product.pk}", fetch_redirect_response=False) self.assertContains(self.client.get(reverse('food:add'), {'q': 'Loose onions'}), 'Loose onions') + + def test_manual_product_size_creates_independent_packages(self): + self.client.post(reverse('food:inventory-manual'), {'product_name': 'Butter block', + 'brand': '', 'barcode': '', 'package_quantity': '250 g'}) + product = FoodProduct.objects.get(owner=self.user, product_name='Butter block') + self.assertEqual((product.package_amount, product.package_unit), (250, 'g')) + response = self.client.post(reverse('food:inventory-add'), {'product': product.pk, + 'quantity': 2, 'original_amount': '250', 'inventory_unit': 'g', + 'location_name': 'Fridge'}) + self.assertEqual(response.status_code, 302) + self.assertEqual(list(KitchenInventoryItem.objects.filter(product=product) + .values_list('quantity', 'original_amount', 'remaining_amount', 'inventory_unit')), + [(1, 250, 250, 'g'), (1, 250, 250, 'g')]) + + def test_legacy_count_gets_split_when_size_is_supplied(self): + location = InventoryLocation.objects.create(user=self.user, name='Pantry') + item = KitchenInventoryItem.objects.create(user=self.user, product=self.product, + location=location, quantity=3) + response = self.client.post(reverse('food:inventory-edit', args=[item.pk]), { + 'quantity': 3, 'original_amount': '6', 'inventory_unit': 'pieces', + 'location_name': 'Pantry'}) + self.assertEqual(response.status_code, 302) + self.assertEqual(list(KitchenInventoryItem.objects.filter(product=self.product) + .values_list('quantity', 'original_amount', 'remaining_amount', 'inventory_unit')), + [(1, 6, 6, 'pieces')] * 3) diff --git a/main/food/test_inventory_consumption.py b/main/food/test_inventory_consumption.py new file mode 100644 index 0000000..bd398ef --- /dev/null +++ b/main/food/test_inventory_consumption.py @@ -0,0 +1,172 @@ +from decimal import Decimal + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.utils import timezone + +from .models import FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem +from .services.inventory_consumption import StockError, consume, normalized, preview, undo + + +class InventoryConsumptionTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='stock-owner') + self.other = get_user_model().objects.create_user(username='stock-other') + self.product = FoodProduct.objects.create(owner=self.user, product_name='Butter', package_amount=250, package_unit='g') + self.location = InventoryLocation.objects.create(user=self.user, name='Fridge') + + def package(self, amount='250', remaining='250', opened=False, best_before=None): + return KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location, + original_amount=Decimal(amount), remaining_amount=Decimal(remaining), inventory_unit='g', + opened=opened, best_before=best_before) + + def test_partial_across_packages_and_undo(self): + first, second = self.package(), self.package() + one = consume(self.user, self.product, '150', 'g') + first.refresh_from_db(); second.refresh_from_db() + self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250'))) + self.assertTrue(first.opened) + two = consume(self.user, self.product, '150', 'g') + first.refresh_from_db(); second.refresh_from_db() + self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('0'), Decimal('200'))) + self.assertIsNotNone(first.archived_at) + self.assertEqual(list(two.lines.values_list('amount', flat=True)), [Decimal('100'), Decimal('50')]) + with self.assertRaises(StockError): + undo(self.user, one.pk) + undo(self.user, two.pk) + first.refresh_from_db(); second.refresh_from_db() + self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250'))) + undo(self.user, one.pk) + first.refresh_from_db() + self.assertFalse(first.opened) + self.assertEqual(first.remaining_amount, Decimal('250')) + + def test_priority_shortage_and_target(self): + late = self.package(best_before=timezone.localdate() + timezone.timedelta(days=10)) + early = self.package(best_before=timezone.localdate() + timezone.timedelta(days=1)) + opened = self.package(remaining='80', opened=True) + plan = preview(self.user, self.product, '100', 'g') + self.assertEqual([row['package'].pk for row in plan['deductions']], [opened.pk, early.pk]) + self.assertEqual(preview(self.user, self.product, '300', 'g', package_id=late.api_id)['shortage'], Decimal('50')) + with self.assertRaises(StockError): + consume(self.user, self.product, '300', 'g', package_id=late.api_id) + late.refresh_from_db() + self.assertEqual(late.remaining_amount, Decimal('250')) + + def test_units_idempotency_isolation_and_validation(self): + package = self.package() + self.assertEqual(normalized('0.25', 'kg')[0], Decimal('250')) + self.assertEqual(normalized('1', 'L')[0], Decimal('1000')) + operation = consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp') + self.assertEqual(consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp').pk, operation.pk) + self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 1) + with self.assertRaises(StockError): + consume(self.user, self.product, '.2', 'kg', idempotency_key='use-once', source='mcp') + with self.assertRaises(StockError): + preview(self.other, self.product, 1, 'g') + for amount, unit in [('-1', 'g'), ('0', 'g'), ('1.0001', 'g'), ('1', 'ml')]: + if unit == 'ml': + self.assertEqual(preview(self.user, self.product, amount, unit)['shortage'], Decimal(1)) + else: + with self.assertRaises(StockError): + preview(self.user, self.product, amount, unit) + package.refresh_from_db() + self.assertEqual(package.remaining_amount, Decimal('150')) + + def test_count_based_legacy_stock(self): + item = KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location, quantity=3) + operation = consume(self.user, self.product, 2, 'packs') + item.refresh_from_db() + self.assertEqual(item.quantity, 1) + undo(self.user, operation.pk) + item.refresh_from_db() + self.assertEqual(item.quantity, 3) + + def test_volume_count_and_explicit_partial_use(self): + milk = FoodProduct.objects.create(owner=self.user, product_name='Milk') + carton = KitchenInventoryItem.objects.create(user=self.user, product=milk, location=self.location, + original_amount=Decimal('1'), remaining_amount=Decimal('1'), inventory_unit='L') + consume(self.user, milk, '250', 'ml') + carton.refresh_from_db() + self.assertEqual(carton.remaining_amount, Decimal('.750')) + self.assertEqual(preview(self.user, milk, '1', 'L')['shortage'], Decimal('.250')) + with self.assertRaises(StockError): + consume(self.user, milk, '1', 'L') + operation = consume(self.user, milk, '1', 'L', allow_partial=True) + self.assertEqual(operation.amount, Decimal('.750')) + carton.refresh_from_db() + self.assertEqual(carton.remaining_amount, Decimal(0)) + eggs = FoodProduct.objects.create(owner=self.user, product_name='Eggs') + box = KitchenInventoryItem.objects.create(user=self.user, product=eggs, location=self.location, + original_amount=Decimal('6'), remaining_amount=Decimal('6'), inventory_unit='pieces') + consume(self.user, eggs, 2, 'pieces') + box.refresh_from_db() + self.assertEqual(box.remaining_amount, Decimal(4)) + with self.assertRaises(StockError): + consume(self.user, eggs, '.5', 'pieces') + + +from django.db import connection +from django.db.migrations.executor import MigrationExecutor +from django.test import TransactionTestCase + + +class InventoryMigrationTests(TransactionTestCase): + migrate_from = ('food', '0005_package_contents') + migrate_to = ('food', '0007_inventory_reversal_state') + + def test_existing_counts_split_only_when_package_size_known(self): + executor = MigrationExecutor(connection) + executor.migrate([self.migrate_from]) + old = executor.loader.project_state([self.migrate_from]).apps + User = old.get_model('auth', 'User') + Product = old.get_model('food', 'FoodProduct') + Location = old.get_model('food', 'InventoryLocation') + Item = old.get_model('food', 'KitchenInventoryItem') + user = User.objects.create(username='migration-stock-user') + location = Location.objects.create(user_id=user.pk, name='Pantry') + known = Product.objects.create(owner_id=user.pk, product_name='Butter', + package_amount=Decimal('250'), package_unit='g') + unknown = Product.objects.create(owner_id=user.pk, product_name='Loose eggs') + Item.objects.create(user_id=user.pk, product_id=known.pk, location_id=location.pk, + quantity=2, opened=True, remaining_amount=Decimal('100')) + Item.objects.create(user_id=user.pk, product_id=unknown.pk, location_id=location.pk, quantity=6) + executor = MigrationExecutor(connection) + executor.migrate([self.migrate_to]) + new = executor.loader.project_state([self.migrate_to]).apps + migrated = list(new.get_model('food', 'KitchenInventoryItem').objects.filter( + user_id=user.pk, product_id=known.pk).order_by('pk')) + self.assertEqual([(i.original_amount, i.remaining_amount, i.quantity, i.location_id) + for i in migrated], [(Decimal('250'), Decimal('100'), 1, location.pk), + (Decimal('250'), Decimal('250'), 1, location.pk)]) + legacy = new.get_model('food', 'KitchenInventoryItem').objects.get(user_id=user.pk, product_id=unknown.pk) + self.assertEqual((legacy.quantity, legacy.original_amount), (6, None)) + + +from concurrent.futures import ThreadPoolExecutor +from django.db import OperationalError, close_old_connections + + +class ConcurrentInventoryConsumptionTests(TransactionTestCase): + def test_competing_requests_do_not_overconsume(self): + user = get_user_model().objects.create_user(username='parallel-stock-user') + product = FoodProduct.objects.create(owner=user, product_name='One carton') + location = InventoryLocation.objects.create(user=user, name='Fridge') + item = KitchenInventoryItem.objects.create(user=user, product=product, location=location, + original_amount=Decimal('100'), remaining_amount=Decimal('100'), inventory_unit='ml') + + def use(): + close_old_connections() + try: + return consume(user, product, 80, 'ml').pk + except (StockError, OperationalError): + return None + finally: + close_old_connections() + + with ThreadPoolExecutor(max_workers=2) as pool: + results = list(pool.map(lambda _: use(), range(2))) + item.refresh_from_db() + self.assertEqual(sum(result is not None for result in results), 1) + self.assertEqual(item.remaining_amount, Decimal('20')) + self.assertEqual(InventoryConsumption.objects.filter(user=user).count(), 1) diff --git a/main/food/urls.py b/main/food/urls.py index ad45158..b04af7e 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -15,6 +15,9 @@ urlpatterns = [ path('inventory//edit/', inventory.edit, name='inventory-edit'), path('inventory//quantity/', inventory.change_quantity, name='inventory-quantity'), path('inventory//add-one/', inventory.add_existing, name='inventory-add-one'), + path('inventory/product//preview/', inventory.preview_consumption, name='inventory-preview'), + path('inventory/product//use/', inventory.use_amount, name='inventory-use'), + path('inventory/consumption//undo/', inventory.undo_consumption, name='inventory-undo'), path('', views.diary, name='diary'), path('add/', views.add_food, name='add'), path('search/openfoodfacts/', views.external_search, name='external-search'), diff --git a/main/mcp_server/server.py b/main/mcp_server/server.py index 9ca1415..1c9e580 100644 --- a/main/mcp_server/server.py +++ b/main/mcp_server/server.py @@ -384,6 +384,32 @@ def create_server() -> MCPServer: await api_request('DELETE', f'kitchen/items/{item_id}/') return {'success': True, 'removed_item_id': item_id} + @server.tool(structured_output=True, description='Read stock for an owned product ID or search query, optionally limited to a location ID. Returns package details and remaining totals. Does not change stock.') + async def inventory_get_stock(product_id: str | None = None, query: str | None = None, + location_id: int | None = None) -> dict[str, Any]: + params = {'product_id': product_id, 'query': query, 'location_id': location_id} + return await api_request('GET', 'kitchen/stock/', params={k: v for k, v in params.items() if v is not None}) + + @server.tool(structured_output=True, description='Preview exact package deductions for one owned product without changing stock. A shortage is reported rather than silently consumed.') + async def inventory_preview_consumption(product_id: str, amount: Decimal, unit: str, + package_id: str | None = None) -> dict[str, Any]: + return await api_request('POST', 'kitchen/consumption/preview/', payload={ + 'product_id': product_id, 'amount': str(amount), 'unit': unit, 'package_id': package_id}) + + @server.tool(structured_output=True, description='Consume an exact quantity from owned inventory packages atomically. Requires a unique idempotency key. If stock is short, preview first and use allow_partial only with explicit user choice.') + async def inventory_consume(product_id: str, amount: Decimal, unit: str, idempotency_key: str, + package_id: str | None = None, source_reference: str = '', + description: str = '', allow_partial: bool = False) -> dict[str, Any]: + return await api_request('POST', 'kitchen/consumption/', payload={ + 'product_id': product_id, 'amount': str(amount), 'unit': unit, + 'package_id': package_id, 'source_reference': source_reference, + 'description': description, 'allow_partial': allow_partial}, + idempotency_key=idempotency_key) + + @server.tool(structured_output=True, description='Undo a previous owned inventory consumption transaction when its affected packages have not changed since. Records an auditable reversal.') + async def inventory_undo_consumption(transaction_id: str) -> dict[str, Any]: + return await api_request('POST', f'kitchen/consumption/{transaction_id}/undo/', payload={}) + return server diff --git a/main/mcp_server/tests.py b/main/mcp_server/tests.py index 30ad653..c916ab1 100644 --- a/main/mcp_server/tests.py +++ b/main/mcp_server/tests.py @@ -157,7 +157,7 @@ class McpHttpTests(LiveServerTestCase): async def check(client): names = {tool.name for tool in (await client.list_tools()).tools} - self.assertEqual(len(names), 16) + self.assertEqual(len(names), 20) self.assertTrue({'food_lookup_product', 'food_create_product', 'food_import_product', 'inventory_import_groceries'} <= names) today = (await client.call_tool('food_get_today')).structured_content @@ -253,5 +253,19 @@ class McpHttpTests(LiveServerTestCase): self.assertEqual(batch['items'][0]['status'], 'added') again = (await client.call_tool('inventory_import_groceries', batch_args)).structured_content self.assertEqual(again['items'][0]['inventory_item_id'], batch['items'][0]['inventory_item_id']) - self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 1) + self.assertEqual((await client.call_tool('inventory_list')).structured_content['count'], 2) + stock = (await client.call_tool('inventory_get_stock', {'product_id': created['product_id']})).structured_content + self.assertEqual(stock['products'][0]['totals']['ml'], '2000.000') + preview = (await client.call_tool('inventory_preview_consumption', { + 'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml'})).structured_content + self.assertEqual([row['amount'] for row in preview['deductions']], ['1000.000', '250.000']) + used = (await client.call_tool('inventory_consume', { + 'product_id': created['product_id'], 'amount': '1250', 'unit': 'ml', + 'idempotency_key': 'mcp-use-oat'})).structured_content + self.assertEqual(used['amount'], '1250.000') + self.assertEqual((await client.call_tool('inventory_get_stock', { + 'product_id': created['product_id']})).structured_content['products'][0]['totals']['ml'], '750.000') + undone = (await client.call_tool('inventory_undo_consumption', { + 'transaction_id': used['transaction_id']})).structured_content + self.assertEqual(undone['reverses'], used['transaction_id']) asyncio.run(self._client(self.secret, check))