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
+115 -17
View File
@@ -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')