Added inventory amount per food package management

This commit is contained in:
Joren de Graaf
2026-10-11 15:46:22 +02:00
parent 400e8254c0
commit cb12c23732
19 changed files with 927 additions and 35 deletions
+126 -6
View File
@@ -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))