Add inventory scan staging and review workflows

This commit is contained in:
Joren de Graaf
2026-10-26 01:45:26 +01:00
parent d305a99b1b
commit 9c8162bf7e
12 changed files with 407 additions and 23 deletions
+10 -1
View File
@@ -13,7 +13,8 @@ from django.utils import timezone
from django.views.decorators.http import require_http_methods, require_POST from django.views.decorators.http import require_http_methods, require_POST
from .forms import InventoryItemForm, InventoryManualProductForm from .forms import InventoryItemForm, InventoryManualProductForm
from .models import FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation, KitchenInventoryItem from .models import (FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation,
InventoryReviewPreference, InventoryScanItem, KitchenInventoryItem)
from .services.inventory_consumption import FACTORS, StockError, consume, materialize_packages, preview, undo from .services.inventory_consumption import FACTORS, StockError, consume, materialize_packages, preview, undo
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from .services.products import local_products from .services.products import local_products
@@ -73,6 +74,12 @@ def overview(request):
if item.inner_packs_per_package and 'inner_packs' not in cards[key]['units']: if item.inner_packs_per_package and 'inner_packs' not in cards[key]['units']:
cards[key]['units'].append('inner_packs') cards[key]['units'].append('inner_packs')
recent = InventoryConsumption.objects.filter(user=request.user, reverses__isnull=True).select_related('product').prefetch_related('lines__package').order_by('-created_at')[:8] recent = InventoryConsumption.objects.filter(user=request.user, reverses__isnull=True).select_related('product').prefetch_related('lines__package').order_by('-created_at')[:8]
review_items = InventoryScanItem.objects.filter(batch__run__user=request.user)
processing_count = review_items.filter(status__in=(InventoryScanItem.Status.QUEUED,
InventoryScanItem.Status.PROCESSING)).count()
needs_review_count = review_items.filter(status__in=(InventoryScanItem.Status.NEEDS_REVIEW,
InventoryScanItem.Status.DEFERRED, InventoryScanItem.Status.FAILED)).count()
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
return render(request, 'food/inventory_overview.html', { return render(request, 'food/inventory_overview.html', {
'items': items, 'cards': list(cards.values()), 'recent_consumption': recent, 'items': items, 'cards': list(cards.values()), 'recent_consumption': recent,
'query': query, 'sort': sort, 'selected_location': location, 'query': query, 'sort': sort, 'selected_location': location,
@@ -80,6 +87,8 @@ def overview(request):
'locations': InventoryLocation.objects.filter(user=request.user), 'locations': InventoryLocation.objects.filter(user=request.user),
'categories': InventoryCategory.objects.filter(user=request.user), 'categories': InventoryCategory.objects.filter(user=request.user),
'today': timezone.localdate(), 'soon_date': timezone.localdate() + timedelta(days=14), 'today': timezone.localdate(), 'soon_date': timezone.localdate() + timedelta(days=14),
'processing_count': processing_count, 'needs_review_count': needs_review_count,
'review_mode': preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL,
}) })
+108 -4
View File
@@ -6,13 +6,14 @@ from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.urls import reverse from django.urls import reverse
from django.views.decorators.http import require_GET, require_POST from django.views.decorators.http import require_GET, require_http_methods, require_POST
from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem, from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem,
InventoryScanRun) InventoryReviewPreference, InventoryScanRun)
from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count, from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count,
confirm_scan_item, create_active_scan, discard_active_scan, approve_scan_item, approve_scan_items, confirm_scan_item, create_active_scan,
get_or_create_active_run, resume_active_run, submit_batch) defer_scan_item, discard_active_scan, get_or_create_active_run,
resume_active_run, save_review_item, submit_batch, update_review_preference)
@login_required @login_required
@@ -54,6 +55,8 @@ def create_scan(request, run_id):
item = create_active_scan(run, request.user, str(payload.get('barcode', '')).strip()) item = create_active_scan(run, request.user, str(payload.get('barcode', '')).strip())
except ScanWorkflowError as error: except ScanWorkflowError as error:
return JsonResponse({'error': str(error)}, status=400) return JsonResponse({'error': str(error)}, status=400)
if item.status == InventoryScanItem.Status.CONFIRMED:
return JsonResponse({'incremented': True, 'item': _item_json(item)})
html = render_to_string('food/partials/inventory_scan_active.html', { html = render_to_string('food/partials/inventory_scan_active.html', {
'item': item, 'locations': InventoryLocation.objects.filter(user=request.user), 'item': item, 'locations': InventoryLocation.objects.filter(user=request.user),
}, request=request) }, request=request)
@@ -126,6 +129,107 @@ def scan_queue(request, run_id):
return render(request, 'food/partials/inventory_scan_queue.html', {'run': run, 'batches': batches}) return render(request, 'food/partials/inventory_scan_queue.html', {'run': run, 'batches': batches})
@login_required
@require_http_methods(['GET', 'POST'])
def inventory_review(request):
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
mode = preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL
if request.method == 'POST' and request.POST.get('action') == 'mode':
try:
preference = update_review_preference(request.user, request.POST.get('mode'))
except ScanWorkflowError as error:
return JsonResponse({'error': str(error)}, status=400)
return redirect(f"{reverse('food:inventory-review')}?mode={preference.mode}")
if request.GET.get('mode') in InventoryReviewPreference.Mode.values:
mode = request.GET['mode']
state = 'processing' if request.GET.get('state') == 'processing' else 'review'
statuses = ((InventoryScanItem.Status.QUEUED, InventoryScanItem.Status.PROCESSING)
if state == 'processing' else
(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED))
items = (InventoryScanItem.objects.filter(batch__run__user=request.user, status__in=statuses)
.select_related('location', 'product', 'batch__run').order_by('created_at'))
context = {'mode': mode, 'items': items,
'locations': InventoryLocation.objects.filter(user=request.user),
'review_count': items.count(), 'state': state,
'approved_count': request.GET.get('approved', '')}
if request.method == 'POST' and request.POST.get('action') == 'preview':
selected_ids = request.POST.getlist('item_ids')
selected = list(items.filter(pk__in=selected_ids))
shared_location = InventoryLocation.objects.filter(user=request.user,
pk=request.POST.get('location_id')).first() if request.POST.get('location_id') else None
context.update({'preview_items': selected, 'selected_ids': [str(item.pk) for item in selected],
'shared_location_id': request.POST.get('location_id', ''),
'shared_location_name': shared_location.name if shared_location else '',
'shared_category': request.POST.get('category_name', ''), 'preview': True})
elif request.method == 'POST' and request.POST.get('action') == 'approve':
selected_ids = request.POST.getlist('item_ids')
try:
approve_scan_items(request.user, selected_ids, {
'location_id': request.POST.get('location_id'),
'category_name': request.POST.get('category_name'),
})
except (ScanWorkflowError, TypeError, ValueError) as error:
context['review_error'] = str(error)
else:
return redirect(f"{reverse('food:inventory-review')}?mode=bulk&approved={len(set(selected_ids))}")
return render(request, 'food/inventory_review.html', context)
@login_required
@require_http_methods(['GET', 'POST'])
def review_item(request, item_id):
item = get_object_or_404(InventoryScanItem.objects.select_related('batch__run', 'product', 'location'),
pk=item_id, batch__run__user=request.user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED))
locations = InventoryLocation.objects.filter(user=request.user)
nutrient_fields = ('energy_kcal_100', 'fat_100', 'saturated_fat_100', 'carbohydrates_100',
'sugars_100', 'protein_100', 'salt_100', 'fibre_100')
values = {'product_name': item.product_name, 'brand': item.brand,
'package_count': item.package_count,
'package_amount': str(item.package_amount) if item.package_amount is not None else '',
'package_unit': item.package_unit, 'category_name': item.category_name,
'notes': item.notes, 'location_id': item.location_id}
if item.product:
values.update({field: str(getattr(item.product, field)) if getattr(item.product, field) is not None else ''
for field in nutrient_fields})
else:
values.update({field: (item.source_data.get('nutrition', {}).get(field) or '')
for field in nutrient_fields})
nutrients = [{'field': field, 'label': field.removesuffix('_100').replace('_', ' ').title(),
'value': values[field]} for field in nutrient_fields]
error = ''
if request.method == 'POST':
values.update({key: request.POST.get(key, '') for key in (
'product_name', 'brand', 'package_count', 'package_amount', 'package_unit',
'category_name', 'notes', 'location_id', *nutrient_fields)})
intent = request.POST.get('action')
try:
if intent == 'defer':
save_review_item(request.user, item.pk, values)
defer_scan_item(request.user, item.pk)
return redirect('food:inventory-review')
if intent == 'approve':
approve_scan_item(request.user, item.pk, values)
return redirect('food:inventory-review')
if intent in ('save', 'mode'):
save_review_item(request.user, item.pk, values)
if intent == 'mode':
preference = update_review_preference(request.user, request.POST.get('mode'))
return redirect(f"{reverse('food:inventory-review')}?mode={preference.mode}")
item.refresh_from_db()
values['saved'] = True
except (ScanWorkflowError, TypeError, ValueError, InventoryLocation.DoesNotExist) as exc:
error = str(exc)
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
return render(request, 'food/inventory_review_item.html', {
'item': item, 'locations': locations, 'values': values, 'error': error,
'nutrition_fields': nutrient_fields, 'nutrients': nutrients,
'mode': preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL,
})
def _queue_batches(run): def _queue_batches(run):
batches = list(run.batches.select_related('location').prefetch_related(Prefetch( batches = list(run.batches.select_related('location').prefetch_related(Prefetch(
'items', queryset=InventoryScanItem.objects.exclude(status=InventoryScanItem.Status.ACTIVE) 'items', queryset=InventoryScanItem.objects.exclude(status=InventoryScanItem.Status.ACTIVE)
+119 -9
View File
@@ -64,6 +64,13 @@ def create_active_scan(run, user, barcode):
raise ScanWorkflowError('Choose a location before scanning.') raise ScanWorkflowError('Choose a location before scanning.')
if batch.items.filter(status=InventoryScanItem.Status.ACTIVE).exists(): if batch.items.filter(status=InventoryScanItem.Status.ACTIVE).exists():
raise ScanWorkflowError('Confirm or remove the active scan before scanning another item.') raise ScanWorkflowError('Confirm or remove the active scan before scanning another item.')
repeated = batch.items.select_for_update().filter(
barcode=barcode, status=InventoryScanItem.Status.CONFIRMED).order_by('-confirmed_at', '-pk').first()
if repeated:
repeated.package_count += 1
repeated.user_data = _item_data(repeated)
repeated.save(update_fields=('package_count', 'user_data'))
return repeated
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first() product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
values = {} values = {}
if product: if product:
@@ -397,8 +404,7 @@ def _send_completion_notification(run_id):
tallies = dict(run.batches.values('items__status').annotate(total=Count('items')).values_list('items__status', 'total')) tallies = dict(run.batches.values('items__status').annotate(total=Count('items')).values_list('items__status', 'total'))
succeeded = tallies.get(InventoryScanItem.Status.COMPLETE, 0) succeeded = tallies.get(InventoryScanItem.Status.COMPLETE, 0)
review = sum(tallies.get(status, 0) for status in (InventoryScanItem.Status.NEEDS_REVIEW, review = sum(tallies.get(status, 0) for status in (InventoryScanItem.Status.NEEDS_REVIEW,
InventoryScanItem.Status.DEFERRED, InventoryScanItem.Status.DEFERRED))
InventoryScanItem.Status.FAILED))
failed = tallies.get(InventoryScanItem.Status.FAILED, 0) failed = tallies.get(InventoryScanItem.Status.FAILED, 0)
run.notification_attempted_at = now # durable at-most-once delivery guard for worker restarts run.notification_attempted_at = now # durable at-most-once delivery guard for worker restarts
run.save(update_fields=('notification_attempted_at',)) run.save(update_fields=('notification_attempted_at',))
@@ -425,7 +431,8 @@ def approve_scan_item(user, item_id, values):
with transaction.atomic(): with transaction.atomic():
item = (InventoryScanItem.objects.select_for_update().select_related('batch__run__user') item = (InventoryScanItem.objects.select_for_update().select_related('batch__run__user')
.filter(pk=item_id, batch__run__user=user, .filter(pk=item_id, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED)).first()) status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED)).first())
if not item: if not item:
raise ScanWorkflowError('This staged item is no longer awaiting review.') raise ScanWorkflowError('This staged item is no longer awaiting review.')
if values.get('product_name'): if values.get('product_name'):
@@ -437,12 +444,16 @@ def approve_scan_item(user, item_id, values):
if values.get('notes') is not None: if values.get('notes') is not None:
item.notes = str(values['notes']).strip()[:4000] item.notes = str(values['notes']).strip()[:4000]
if values.get('location_id'): if values.get('location_id'):
item.location = InventoryLocation.objects.get(user=user, pk=values['location_id']) location = InventoryLocation.objects.filter(user=user, pk=values['location_id']).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
item.location = location
item.package_count = _integer(values.get('package_count', item.package_count), 'Enter a valid number of packages.', 1, 10000) item.package_count = _integer(values.get('package_count', item.package_count), 'Enter a valid number of packages.', 1, 10000)
if 'package_amount' in values: if 'package_amount' in values:
item.package_amount = _decimal_or_none(values['package_amount'], 'Enter a valid package size.') item.package_amount = _decimal_or_none(values['package_amount'], 'Enter a valid package size.')
if 'package_unit' in values: if 'package_unit' in values:
item.package_unit = str(values['package_unit']).strip()[:8] item.package_unit = str(values['package_unit']).strip()[:8]
_apply_nutrition_values(item, values)
if not item.product_name: if not item.product_name:
raise ScanWorkflowError('Enter a product name before approving.') raise ScanWorkflowError('Enter a product name before approving.')
product = item.product or FoodProduct.objects.filter(owner=user, barcode=item.barcode).first() product = item.product or FoodProduct.objects.filter(owner=user, barcode=item.barcode).first()
@@ -459,6 +470,7 @@ def approve_scan_item(user, item_id, values):
else: else:
_apply_scan_product_corrections(product, item) _apply_scan_product_corrections(product, item)
_populate_from_product(item, product) _populate_from_product(item, product)
_apply_nutrition_values(item, values, product=product)
item.product = product item.product = product
if not _valid_stock_input(item): if not _valid_stock_input(item):
raise ScanWorkflowError('Add valid package details or choose count-only stock before approving.') raise ScanWorkflowError('Add valid package details or choose count-only stock before approving.')
@@ -472,18 +484,116 @@ def approve_scan_item(user, item_id, values):
return item return item
def save_review_item(user, item_id, values):
"""Persist edits on a staged row so switching review modes cannot lose them."""
with transaction.atomic():
item = (InventoryScanItem.objects.select_for_update().filter(
pk=item_id, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED)).first())
if not item:
raise ScanWorkflowError('This staged item is no longer awaiting review.')
if values.get('product_name') is not None:
item.product_name = str(values['product_name']).strip()[:255]
if values.get('brand') is not None:
item.brand = str(values['brand']).strip()[:255]
if values.get('category_name') is not None:
item.category_name = str(values['category_name']).strip()[:100]
if values.get('notes') is not None:
item.notes = str(values['notes']).strip()[:4000]
if values.get('location_id'):
location = InventoryLocation.objects.filter(user=user, pk=values['location_id']).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
item.location = location
item.package_count = _integer(values.get('package_count', item.package_count), 'Enter a valid number of packages.', 1, 10000)
if 'package_amount' in values:
item.package_amount = _decimal_or_none(values['package_amount'], 'Enter a valid package size.')
if 'package_unit' in values:
item.package_unit = str(values['package_unit']).strip()[:8]
_apply_nutrition_values(item, values)
item.user_data = _item_data(item)
item.save()
return item
def approve_scan_items(user, item_ids, values):
"""Approve a selected group atomically after a preview has been shown."""
ids = list(dict.fromkeys(int(value) for value in item_ids))
if not ids:
raise ScanWorkflowError('Select at least one product to approve.')
with transaction.atomic():
items = list(InventoryScanItem.objects.select_for_update().filter(
pk__in=ids, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED)))
if len(items) != len(ids):
raise ScanWorkflowError('One or more selected products are no longer awaiting review. Reload and try again.')
approved = []
for item in items:
shared = dict(values)
shared.setdefault('product_name', item.product_name)
shared.setdefault('brand', item.brand)
shared.setdefault('package_count', item.package_count)
shared.setdefault('package_amount', str(item.package_amount) if item.package_amount is not None else '')
shared.setdefault('package_unit', item.package_unit)
approved.append(approve_scan_item(user, item.pk, shared))
for run_id in set(item.batch.run_id for item in approved):
_refresh_completion(run_id)
return approved
def _apply_nutrition_values(item, values, product=None):
fields = {'energy_kcal_100': 'energy_kcal_100', 'fat_100': 'fat_100',
'saturated_fat_100': 'saturated_fat_100', 'carbohydrates_100': 'carbohydrates_100',
'sugars_100': 'sugars_100', 'protein_100': 'protein_100',
'salt_100': 'salt_100', 'fibre_100': 'fibre_100'}
if not any(key in values for key in fields):
return
product = product or item.product or FoodProduct.objects.filter(owner=item.batch.run.user, barcode=item.barcode).first()
nutrition = {}
for key, field in fields.items():
if key not in values:
continue
value = values[key]
parsed = _decimal_nonnegative_or_none(value, f'Enter a valid {key.replace("_100", "").replace("_", " ")} value.')
nutrition[key] = str(parsed) if parsed is not None else None
source_data = item.source_data if isinstance(item.source_data, dict) else {}
item.source_data = {**source_data,
'nutrition': {**source_data.get('nutrition', {}), **nutrition}}
if product:
for key, value in nutrition.items():
setattr(product, key, Decimal(value) if value is not None else None)
raw_data = product.raw_data if isinstance(product.raw_data, dict) else {}
product.raw_data = {**raw_data, 'manual_nutrition_override': True}
product.save(update_fields=(*nutrition.keys(), 'raw_data', 'updated_at'))
source_nutrition = item.source_data.get('nutrition', {}) if isinstance(item.source_data, dict) else {}
item.source_data = {**(item.source_data if isinstance(item.source_data, dict) else {}),
'nutrition': {**source_nutrition, **nutrition}}
def _decimal_nonnegative_or_none(value, message):
if value in (None, ''):
return None
try:
result = Decimal(str(value))
except (InvalidOperation, TypeError, ValueError):
raise ScanWorkflowError(message) from None
if not result.is_finite() or result < 0 or result > Decimal('9999999.999'):
raise ScanWorkflowError(message)
return result.quantize(Decimal('.001'))
def defer_scan_item(user, item_id): def defer_scan_item(user, item_id):
updated = InventoryScanItem.objects.filter(pk=item_id, batch__run__user=user, updated = InventoryScanItem.objects.filter(pk=item_id, batch__run__user=user,
status=InventoryScanItem.Status.NEEDS_REVIEW).update(status=InventoryScanItem.Status.DEFERRED) status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.FAILED,
InventoryScanItem.Status.DEFERRED)).update(
status=InventoryScanItem.Status.DEFERRED)
if not updated: if not updated:
raise ScanWorkflowError('This item can no longer be deferred.') raise ScanWorkflowError('This item can no longer be deferred.')
def _apply_scan_product_corrections(product, item): def _apply_scan_product_corrections(product, item):
# Metadata corrections are limited to product identity and packaging. Nutrition remains source-owned. # This path updates identity and package metadata only; nutrition overrides remain untouched.
if (product.source == FoodProduct.Source.OPEN_FOOD_FACTS and isinstance(product.raw_data, dict) and
product.raw_data.get('manual_nutrition_override')):
return
product.product_name = item.product_name or product.product_name product.product_name = item.product_name or product.product_name
product.brand = item.brand or product.brand product.brand = item.brand or product.brand
product.package_amount = item.package_amount or product.package_amount product.package_amount = item.package_amount or product.package_amount
+6 -2
View File
@@ -183,8 +183,12 @@ def cached_product(user, barcode, *, refresh=False, wait_for_slot=False, on_requ
return product return product
_rate_limit(user.pk, 'product', 10) _rate_limit(user.pk, 'product', 10)
try: try:
data = OpenFoodFactsClient().get_product(barcode, wait_for_slot=wait_for_slot, client = OpenFoodFactsClient()
on_request_start=on_request_start) if wait_for_slot or on_request_start:
data = client.get_product(barcode, wait_for_slot=wait_for_slot,
on_request_start=on_request_start)
else:
data = client.get_product(barcode)
except OpenFoodFactsError: except OpenFoodFactsError:
if product: if product:
return product return product
+1
View File
@@ -176,6 +176,7 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
@media(max-width:800px){.inventory-scan-layout{grid-template-columns:minmax(0,1fr)}.inventory-scan-camera{position:static}.inventory-scan-page>.food-heading{align-items:flex-start;flex-direction:column}.inventory-scan-location{align-self:flex-start}} @media(max-width:800px){.inventory-scan-layout{grid-template-columns:minmax(0,1fr)}.inventory-scan-camera{position:static}.inventory-scan-page>.food-heading{align-items:flex-start;flex-direction:column}.inventory-scan-location{align-self:flex-start}}
@media(max-width:520px){.inventory-scan-page{padding:1rem .8rem 6rem}.inventory-scan-start-form{grid-template-columns:1fr}.inventory-scan-start-form label{grid-column:auto}.inventory-scan-fields--package{grid-template-columns:repeat(2,minmax(0,1fr))}.inventory-scan-fields--package label:first-child{grid-column:1/-1}.inventory-camera-label{flex-wrap:wrap}.inventory-camera-label>span:last-child{width:100%;margin-left:1.15rem;text-align:left}.inventory-scan-next-row{grid-template-columns:1fr}.inventory-scan-card-actions .button{flex:1}.inventory-scan-queue-item{align-items:flex-start}.inventory-scan-queue-item-side{font-size:.72rem}} @media(max-width:520px){.inventory-scan-page{padding:1rem .8rem 6rem}.inventory-scan-start-form{grid-template-columns:1fr}.inventory-scan-start-form label{grid-column:auto}.inventory-scan-fields--package{grid-template-columns:repeat(2,minmax(0,1fr))}.inventory-scan-fields--package label:first-child{grid-column:1/-1}.inventory-camera-label{flex-wrap:wrap}.inventory-camera-label>span:last-child{width:100%;margin-left:1.15rem;text-align:left}.inventory-scan-next-row{grid-template-columns:1fr}.inventory-scan-card-actions .button{flex:1}.inventory-scan-queue-item{align-items:flex-start}.inventory-scan-queue-item-side{font-size:.72rem}}
@media(prefers-reduced-motion:reduce){.inventory-scan-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}} @media(prefers-reduced-motion:reduce){.inventory-scan-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}}
.inventory-staging,.inventory-review-page .food-card{border:1px solid #d8e1d8;border-radius:14px;background:#fff;padding:1rem}.inventory-staging{display:grid;gap:1rem;margin:1rem 0;background:#f5f8f4}.inventory-staging-top{display:flex;align-items:center;justify-content:space-between;gap:1rem}.inventory-staging-top h2,.inventory-review-page h2{margin:.1rem 0;color:#183c2c}.inventory-staging-top p:last-child{margin:.35rem 0;color:#63776c}.inventory-kicker{margin:0;color:#247452;font-size:.75rem;font-weight:750;letter-spacing:.04em;text-transform:uppercase}.inventory-staging-counts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem}.inventory-staging-counts>a{display:flex;align-items:center;gap:.75rem;min-height:62px;padding:.6rem .8rem;border:1px solid #d8e1d8;border-radius:10px;background:white;color:#273d33;text-decoration:none}.inventory-staging-counts strong{font-size:1.45rem;color:#183c2c}.inventory-review-mode,.inventory-review-toolbar form{display:flex;align-items:center;gap:.45rem;flex-wrap:wrap}.inventory-review-mode>span,.inventory-review-toolbar>span{margin-right:.4rem;font-weight:700}.inventory-review-mode button,.inventory-review-toolbar button{min-height:42px;padding:.5rem .8rem;border:1px solid #c8d4ca;border-radius:9px;background:white;color:#183c2c;font:inherit;cursor:pointer}.inventory-review-mode button.is-selected,.inventory-review-toolbar button.is-selected{background:#e9f3ec;border-color:#247452;color:#183c2c;font-weight:700}.inventory-review-page{max-width:920px;padding-top:1.25rem}.inventory-review-page>.food-heading{margin-bottom:1rem}.inventory-review-page .food-heading h1{margin:.35rem 0;color:#183c2c}.inventory-review-page .food-heading p:last-child{color:#63776c}.inventory-review-toolbar{display:flex;justify-content:space-between;align-items:center;gap:.8rem;margin:.75rem 0}.inventory-review-list{display:grid;gap:.7rem}.inventory-review-row{display:flex;align-items:center;justify-content:space-between;gap:1rem}.inventory-review-row h2{margin:.15rem 0;font-size:1.05rem}.inventory-review-row p{margin:.25rem 0;color:#63776c}.inventory-review-row .button,.inventory-bulk-review button{min-height:44px}.inventory-review-error{color:#9b342d;font-weight:650}.inventory-review-success{color:#247452;font-weight:700}.inventory-bulk-review{display:grid;gap:.8rem;margin-top:.8rem}.inventory-bulk-review>p{margin:0;color:#63776c}.inventory-bulk-selection{display:grid;gap:.35rem;margin:0;padding:.5rem;border:1px solid #d8e1d8;border-radius:10px}.inventory-bulk-selection legend{font-weight:700}.inventory-bulk-selection label{display:flex;align-items:center;gap:.65rem;min-height:52px;padding:.4rem;border-bottom:1px solid #edf0ed}.inventory-bulk-selection input{width:20px;height:20px;flex:none}.inventory-bulk-selection label span{display:grid;gap:.2rem;min-width:0}.inventory-bulk-selection small,.inventory-review-preview span{color:#63776c}.inventory-review-shared-fields,.inventory-review-fields,.inventory-review-nutrients{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem}.inventory-review-shared-fields label,.inventory-review-fields label,.inventory-review-nutrients label{display:grid;gap:.3rem;font-weight:650}.inventory-review-fields textarea{min-height:80px}.inventory-review-fields input,.inventory-review-fields select,.inventory-review-fields textarea,.inventory-review-shared-fields input,.inventory-review-shared-fields select,.inventory-review-nutrients input{width:100%;min-width:0;min-height:44px;padding:.6rem .7rem;border:1px solid #c8d4ca;border-radius:9px;background:white;color:#19242b;font:inherit;font-weight:400;box-sizing:border-box}.inventory-review-form{display:grid;gap:1rem}.inventory-review-form .inventory-scan-nutrition p{color:#63776c}.inventory-review-actions{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}.inventory-review-actions .button{min-height:44px}.inventory-review-preview{padding:.65rem;border-bottom:1px solid #edf0ed}.inventory-review-preview>div{display:grid;gap:.2rem}.inventory-review-preview>span{text-align:right}.inventory-review-page :focus-visible,.inventory-staging :focus-visible{outline:3px solid #f2ad49;outline-offset:2px}@media(max-width:600px){.inventory-staging-top,.inventory-review-row,.inventory-review-toolbar{align-items:flex-start;flex-direction:column}.inventory-review-shared-fields,.inventory-review-fields,.inventory-review-nutrients{grid-template-columns:1fr}.inventory-review-preview{align-items:flex-start;flex-direction:column}.inventory-review-preview>span{text-align:left}.inventory-review-actions{display:grid}.inventory-review-actions .button{width:100%}}
.food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} .food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
.food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0} .food-quantity-controls{display:flex;align-items:center;gap:.35rem;white-space:nowrap}.food-quantity-controls .food-quantity{min-width:2.5ch;text-align:center}.food-quantity-controls .food-quantity-form{margin:0}
+6 -1
View File
@@ -270,7 +270,7 @@
const code = String(value || '').trim(); const code = String(value || '').trim();
if (locked || !/^[0-9]{6,64}$/.test(code)) return; if (locked || !/^[0-9]{6,64}$/.test(code)) return;
const now = Date.now(); const now = Date.now();
if (code === lastBarcode && now - lastBarcodeAt < 1800) { if (code === lastBarcode && now - lastBarcodeAt < 3000) {
say('Repeated camera detection ignored. Use + in the queue to add another package.'); say('Repeated camera detection ignored. Use + in the queue to add another package.');
return; return;
} }
@@ -283,6 +283,11 @@
body.set('barcode', code); body.set('barcode', code);
try { try {
const data = await request(root.dataset.createUrl, body); const data = await request(root.dataset.createUrl, body);
if (data.incremented) {
clearActive();
say(`${data.item.product_name || 'This product'}: repeated scan added one package. Use Remove one package in the queue to undo.`);
return;
}
activeWrap.innerHTML = data.html; activeWrap.innerHTML = data.html;
bindActiveCard(); bindActiveCard();
} catch (error) { } catch (error) {
@@ -1,7 +1,8 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Kitchen Inventory · Tasknest{% endblock %} {% block title %}Kitchen Inventory · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-nested"> {% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-1">
<div class="food-page inventory-page"><header class="food-heading"><div><h1>Kitchen Inventory</h1><p>What you have and where it lives.</p></div><div class="inventory-heading-actions"><a class="button" href="{% url 'food:inventory-add' %}">+ Add item</a><a class="button button--secondary" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a></div></header> <div class="food-page inventory-page"><header class="food-heading"><div><h1>Kitchen Inventory</h1><p>What you have and where it lives.</p></div><div class="inventory-heading-actions"><a class="button" href="{% url 'food:inventory-add' %}">+ Add item</a><a class="button button--secondary" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a></div></header>
<section class="food-card inventory-staging" id="inventory-review" aria-labelledby="inventory-staging-title"><div class="inventory-staging-top"><div><p class="inventory-kicker">Bulk scanner</p><h2 id="inventory-staging-title">Staged scan items</h2><p>Track background enrichment and finish products that need your input.</p></div><a class="button" href="{% url 'food:inventory-review' %}">Open review</a></div><div class="inventory-staging-counts"><a href="{% url 'food:inventory-review' %}?state=processing"><strong>{{ processing_count }}</strong><span>Processing</span></a><a href="{% url 'food:inventory-review' %}"><strong>{{ needs_review_count }}</strong><span>Needs Review</span></a></div><form method="post" action="{% url 'food:inventory-review' %}" class="inventory-review-mode">{% csrf_token %}<input type="hidden" name="action" value="mode"><span>Review mode</span><button name="mode" value="individual" aria-pressed="{% if review_mode == 'individual' %}true{% else %}false{% endif %}" class="{% if review_mode == 'individual' %}is-selected{% endif %}">Individual</button><button name="mode" value="bulk" aria-pressed="{% if review_mode == 'bulk' %}true{% else %}false{% endif %}" class="{% if review_mode == 'bulk' %}is-selected{% endif %}">Bulk review</button></form></section>
<form method="get" class="food-card inventory-filters" role="search" aria-label="Search kitchen inventory"> <form method="get" class="food-card inventory-filters" role="search" aria-label="Search kitchen inventory">
<div class="inventory-filter-search"><label for="inventory-search">Search inventory</label><div><input id="inventory-search" type="search" name="q" value="{{ query }}"><button class="button" type="submit">Search</button></div></div> <div class="inventory-filter-search"><label for="inventory-search">Search inventory</label><div><input id="inventory-search" type="search" name="q" value="{{ query }}"><button class="button" type="submit">Search</button></div></div>
<details class="inventory-filter-details" data-responsive-filters open><summary>More filters{% if selected_location or selected_category or opened or use_soon == '1' or sort != 'location' %} · Applied{% endif %}</summary><div class="inventory-filter-options"><label>Location<select name="location"><option value="">All locations</option>{% for location in locations %}<option value="{{ location.pk }}" {% if selected_location == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<select name="category"><option value="">All categories</option>{% for category in categories %}<option value="{{ category.pk }}" {% if selected_category == category.pk|stringformat:'s' %}selected{% endif %}>{{ category.name }}</option>{% endfor %}</select></label><label>Opened<select name="opened"><option value="">All</option><option value="yes" {% if opened == 'yes' %}selected{% endif %}>Opened</option><option value="no" {% if opened == 'no' %}selected{% endif %}>Unopened</option></select></label><label>Sort<select name="sort"><option value="location" {% if sort == 'location' %}selected{% endif %}>Location</option><option value="category" {% if sort == 'category' %}selected{% endif %}>Category</option><option value="name" {% if sort == 'name' %}selected{% endif %}>Product name</option><option value="recent" {% if sort == 'recent' %}selected{% endif %}>Recently added</option><option value="best_before" {% if sort == 'best_before' %}selected{% endif %}>Best before</option></select></label><label class="inventory-check"><input type="checkbox" name="use_soon" value="1" {% if use_soon == '1' %}checked{% endif %}> Use soon</label><button class="button" type="submit">Apply filters</button></div></details> <details class="inventory-filter-details" data-responsive-filters open><summary>More filters{% if selected_location or selected_category or opened or use_soon == '1' or sort != 'location' %} · Applied{% endif %}</summary><div class="inventory-filter-options"><label>Location<select name="location"><option value="">All locations</option>{% for location in locations %}<option value="{{ location.pk }}" {% if selected_location == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<select name="category"><option value="">All categories</option>{% for category in categories %}<option value="{{ category.pk }}" {% if selected_category == category.pk|stringformat:'s' %}selected{% endif %}>{{ category.name }}</option>{% endfor %}</select></label><label>Opened<select name="opened"><option value="">All</option><option value="yes" {% if opened == 'yes' %}selected{% endif %}>Opened</option><option value="no" {% if opened == 'no' %}selected{% endif %}>Unopened</option></select></label><label>Sort<select name="sort"><option value="location" {% if sort == 'location' %}selected{% endif %}>Location</option><option value="category" {% if sort == 'category' %}selected{% endif %}>Category</option><option value="name" {% if sort == 'name' %}selected{% endif %}>Product name</option><option value="recent" {% if sort == 'recent' %}selected{% endif %}>Recently added</option><option value="best_before" {% if sort == 'best_before' %}selected{% endif %}>Best before</option></select></label><label class="inventory-check"><input type="checkbox" name="use_soon" value="1" {% if use_soon == '1' %}checked{% endif %}> Use soon</label><button class="button" type="submit">Apply filters</button></div></details>
@@ -0,0 +1,29 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Inventory review · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-1">
<main class="food-page inventory-review-page">
<header class="food-heading"><div><a href="{% url 'food:inventory' %}">← Kitchen inventory</a><h1>{% if state == 'processing' %}Processing scan items{% else %}Additional Review Required{% endif %}</h1><p>{{ review_count }} product{{ review_count|pluralize }} {% if state == 'processing' %}are queued or being enriched.{% else %}need review. Fetched and entered information is kept on each staged item.{% endif %}</p></div></header>
{% if state != 'processing' %}<div class="inventory-review-toolbar"><div><form method="post" action="{% url 'food:inventory-review' %}">{% csrf_token %}<input type="hidden" name="action" value="mode"><button name="mode" value="individual" class="{% if mode == 'individual' %}is-selected{% endif %}" aria-pressed="{% if mode == 'individual' %}true{% else %}false{% endif %}">Individual</button><button name="mode" value="bulk" class="{% if mode == 'bulk' %}is-selected{% endif %}" aria-pressed="{% if mode == 'bulk' %}true{% else %}false{% endif %}">Bulk review</button></form></div><a href="{% url 'food:inventory' %}#inventory-review">Processing and review counts</a></div>{% endif %}
{% if approved_count %}<p class="inventory-review-success" role="status">{{ approved_count }} product{{ approved_count|pluralize }} added to inventory.</p>{% endif %}
{% if review_error %}<p class="inventory-review-error" role="alert">{{ review_error }}</p>{% endif %}
{% if mode == 'individual' or state == 'processing' %}
<section class="inventory-review-list" aria-label="Products requiring individual review">
{% for item in items %}<article class="food-card inventory-review-row"><div><p class="inventory-kicker">{{ item.get_status_display }} · {{ item.location.name }}</p><h2>{{ item.product_name|default:'Product details needed' }}</h2><p>{{ item.brand }}{% if item.brand %} · {% endif %}Barcode {{ item.barcode }}</p>{% if item.last_error %}<p class="inventory-review-error">{{ item.last_error }}</p>{% endif %}<p>{{ item.package_count }} package{{ item.package_count|pluralize }}{% if item.package_amount %} · {{ item.package_amount }} {{ item.package_unit }}{% endif %}</p></div>{% if state != 'processing' %}<a class="button" href="{% url 'food:inventory-review-item' item.pk %}">Review product</a>{% endif %}</article>{% empty %}<section class="food-card"><h2>{% if state == 'processing' %}No items processing{% else %}Nothing needs review{% endif %}</h2><p>{% if state == 'processing' %}Submitted scan batches will appear here while the worker enriches them.{% else %}Products that could not be matched or need corrections will appear here.{% endif %}</p></section>{% endfor %}
</section>
{% elif state != 'processing' %}
<form class="food-card inventory-bulk-review" method="post" action="{% url 'food:inventory-review' %}">
{% csrf_token %}<input type="hidden" name="action" value="{% if preview %}approve{% else %}preview{% endif %}">
<h2>{% if preview %}Preview selected products{% else %}Select products to review together{% endif %}</h2>
<p>{% if preview %}Review the affected rows before adding them to inventory. Individual product fields and nutrition stay unchanged.{% else %}Apply a shared storage location or category, then preview the exact products before approval.{% endif %}</p>
{% if preview %}
{% for item in preview_items %}<input type="hidden" name="item_ids" value="{{ item.pk }}"><div class="inventory-review-row inventory-review-preview"><div><strong>{{ item.product_name|default:'Product details needed' }}</strong><span>{{ item.barcode }} · {{ item.package_count }} package{{ item.package_count|pluralize }}</span></div><span>{{ shared_location_name|default:item.location.name }}{% if shared_category %} · {{ shared_category }}{% elif item.category_name %} · {{ item.category_name }}{% endif %}</span></div>{% endfor %}
<input type="hidden" name="location_id" value="{{ shared_location_id }}"><input type="hidden" name="category_name" value="{{ shared_category }}">
<div class="inventory-review-actions"><button class="button" type="submit">Approve selected products</button><a class="button button--secondary" href="{% url 'food:inventory-review' %}?mode=bulk">Back to selection</a></div>
{% else %}
<fieldset class="inventory-bulk-selection"><legend>Select staged products</legend>{% for item in items %}<label><input type="checkbox" name="item_ids" value="{{ item.pk }}"><span><strong>{{ item.product_name|default:'Product details needed' }}</strong><small>{{ item.barcode }} · {{ item.get_status_display }} · {{ item.location.name }} · {{ item.package_count }} package{{ item.package_count|pluralize }}</small></span></label>{% empty %}<p>No staged products need review.</p>{% endfor %}</fieldset>
<div class="inventory-review-shared-fields"><label>Shared location<select name="location_id"><option value="">Keep each product's location</option>{% for location in locations %}<option value="{{ location.pk }}">{{ location.name }}</option>{% endfor %}</select></label><label>Shared category<input name="category_name" maxlength="100" placeholder="Leave blank to keep each category"></label></div>
<button class="button" type="submit" {% if not items %}disabled{% endif %}>Preview affected products</button>
{% endif %}
</form>
{% endif %}
</main>{% endblock %}
@@ -0,0 +1,12 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Review {{ item.product_name|default:'scanned product' }} · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-1">
<main class="food-page inventory-review-page"><header class="food-heading"><div><a href="{% url 'food:inventory-review' %}">← Additional Review Required</a><p class="inventory-kicker">{{ item.get_status_display }} · Barcode {{ item.barcode }}</p><h1>Review scanned product</h1><p>Unknown nutrition values stay blank. You can approve without filling optional nutrition fields.</p></div></header>
{% if error %}<p class="inventory-review-error" role="alert">{{ error }}</p>{% endif %}{% if values.saved %}<p class="inventory-review-success" role="status">Your changes were saved.</p>{% endif %}
<form method="post" class="food-card inventory-review-form">{% csrf_token %}
<div class="inventory-review-toolbar"><span>Review mode</span><button type="submit" name="action" value="mode" class="{% if mode == 'individual' %}is-selected{% endif %}" aria-pressed="{% if mode == 'individual' %}true{% else %}false{% endif %}" onclick="this.form.querySelector('[name=mode]').value='individual'">Individual</button><button type="submit" name="action" value="mode" class="{% if mode == 'bulk' %}is-selected{% endif %}" aria-pressed="{% if mode == 'bulk' %}true{% else %}false{% endif %}" onclick="this.form.querySelector('[name=mode]').value='bulk'">Bulk review</button><input type="hidden" name="mode" value="{{ mode }}"></div>
<div class="inventory-review-fields"><label>Product name<input name="product_name" maxlength="255" required value="{{ values.product_name }}"></label><label>Brand<input name="brand" maxlength="255" value="{{ values.brand }}"></label><label>Storage location<select name="location_id" required>{% for location in locations %}<option value="{{ location.pk }}" {% if item.location_id == location.pk or values.location_id|stringformat:'s' == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<input name="category_name" maxlength="100" value="{{ values.category_name }}"></label>
<label>Number of packages<input type="number" name="package_count" min="1" max="10000" value="{{ values.package_count }}" required></label><label>Amount per package<input type="number" name="package_amount" min="0.001" step="0.001" value="{{ values.package_amount }}" placeholder="Unknown"></label><label>Package unit<input name="package_unit" maxlength="8" value="{{ values.package_unit }}" placeholder="e.g. g, ml, pieces"></label><label>Notes<textarea name="notes" rows="3">{{ values.notes }}</textarea></label></div>
<details class="inventory-scan-nutrition" open><summary>Nutrition per 100 g/ml (optional)</summary><p>Blank means unknown; entering 0 records a known zero.</p><div class="inventory-review-nutrients">{% for nutrient in nutrients %}<label>{{ nutrient.label }}<input type="number" min="0" step="0.001" name="{{ nutrient.field }}" value="{{ nutrient.value }}" placeholder="Unknown"></label>{% endfor %}</div></details>
<div class="inventory-review-actions"><button class="button" type="submit" name="action" value="save">Save changes</button><button class="button" type="submit" name="action" value="approve">Approve and add to inventory</button><button class="button button--secondary" type="submit" name="action" value="defer">Skip for now</button></div>
</form></main>{% endblock %}
@@ -1,7 +1,7 @@
{% extends 'planner/base.html' %}{% load static %} {% extends 'planner/base.html' %}{% load static %}
{% block title %}Bulk scan inventory · Tasknest{% endblock %} {% block title %}Bulk scan inventory · Tasknest{% endblock %}
{% block content %} {% block content %}
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-bulk-2"> <link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-bulk-3">
<main class="food-page inventory-scan-page"> <main class="food-page inventory-scan-page">
<header class="food-heading"> <header class="food-heading">
<div><a href="{% url 'food:inventory' %}">← Kitchen inventory</a><h1>Bulk scan inventory</h1><p>Scan packages into a location, then review your session queue.</p></div> <div><a href="{% url 'food:inventory' %}">← Kitchen inventory</a><h1>Bulk scan inventory</h1><p>Scan packages into a location, then review your session queue.</p></div>
@@ -65,5 +65,5 @@
</div> </div>
{% endif %} {% endif %}
</main> </main>
<script src="{% static 'food/scanner.js' %}?v=20261026-bulk-2" defer></script> <script src="{% static 'food/scanner.js' %}?v=20261026-bulk-3" defer></script>
{% endblock %} {% endblock %}
+110 -3
View File
@@ -8,11 +8,11 @@ from django.urls import reverse
from django.utils import timezone from django.utils import timezone
from food.models import (FoodProduct, InventoryLocation, InventoryScanBatch, from food.models import (FoodProduct, InventoryLocation, InventoryScanBatch,
InventoryScanItem, InventoryScanRun, InventoryReviewPreference, InventoryScanItem, InventoryScanRun,
KitchenInventoryItem, OpenFoodFactsRequest) KitchenInventoryItem, OpenFoodFactsRequest)
from food.services.inventory_scanner import (ScanWorkflowError, from food.services.inventory_scanner import (ScanWorkflowError,
confirm_scan_item, create_active_scan, get_or_create_active_run, adjust_confirmed_count, approve_scan_item, approve_scan_items, confirm_scan_item, create_active_scan, get_or_create_active_run,
process_next_scan_item, submit_batch) process_next_scan_item, save_review_item, submit_batch, update_review_preference)
from food.services.off_rate_limit import OpenFoodFactsRateLimited, off_http_request from food.services.off_rate_limit import OpenFoodFactsRateLimited, off_http_request
from food.services.openfoodfacts import OpenFoodFactsTransientError from food.services.openfoodfacts import OpenFoodFactsTransientError
@@ -90,6 +90,19 @@ class InventoryScanQueueTests(TestCase):
self.assertEqual(item.status, InventoryScanItem.Status.QUEUED) self.assertEqual(item.status, InventoryScanItem.Status.QUEUED)
self.assertGreaterEqual(item.next_attempt_at, timezone.now() + timedelta(seconds=29)) self.assertGreaterEqual(item.next_attempt_at, timezone.now() + timedelta(seconds=29))
def test_tenth_actual_transient_request_moves_item_to_review(self):
run, item = self._confirmed_item(barcode='87654321')
submit_batch(self.user, batch_id=item.batch_id, finish=True)
InventoryScanItem.objects.filter(pk=item.pk).update(attempts=9)
def transient_request(*args, **kwargs):
kwargs['on_request_start']()
raise OpenFoodFactsTransientError('temporary failure')
with patch('food.services.inventory_scanner.cached_product', side_effect=transient_request):
process_next_scan_item()
item.refresh_from_db()
self.assertEqual(item.attempts, 10)
self.assertEqual(item.status, InventoryScanItem.Status.NEEDS_REVIEW)
def test_unknown_product_moves_to_review_without_losing_user_fields(self): def test_unknown_product_moves_to_review_without_losing_user_fields(self):
run, item = self._confirmed_item(barcode='87654321') run, item = self._confirmed_item(barcode='87654321')
submit_batch(self.user, batch_id=item.batch_id, finish=True) submit_batch(self.user, batch_id=item.batch_id, finish=True)
@@ -121,6 +134,76 @@ class OpenFoodFactsGlobalLimitTests(TestCase):
self.assertEqual(OpenFoodFactsRequest.objects.count(), 1) self.assertEqual(OpenFoodFactsRequest.objects.count(), 1)
class InventoryReviewServiceTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='review-owner', password='test-password')
self.fridge = InventoryLocation.objects.create(user=self.user, name='Fridge')
self.shelf = InventoryLocation.objects.create(user=self.user, name='Shelf')
def _staged_item(self, barcode):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, barcode)
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk,
'product_name': 'Review beans', 'package_count': 2})
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None):
process_next_scan_item()
item.refresh_from_db()
return item
def test_mode_preference_persists_and_review_edits_are_saved(self):
item = self._staged_item('87654321')
self.assertEqual(update_review_preference(self.user, 'bulk').mode, 'bulk')
saved = save_review_item(self.user, item.pk, {'product_name': 'Edited beans',
'package_count': '3', 'location_id': self.shelf.pk, 'energy_kcal_100': '0'})
self.assertEqual((saved.product_name, saved.package_count, saved.location),
('Edited beans', 3, self.shelf))
self.assertEqual(saved.source_data['nutrition']['energy_kcal_100'], '0.000')
self.assertEqual(InventoryReviewPreference.objects.get(user=self.user).mode, 'bulk')
def test_repeated_confirmed_barcode_increments_pending_package_with_undo(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, '87654321')
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk, 'product_name': 'Beans'})
repeated = create_active_scan(run, self.user, '87654321')
self.assertEqual(repeated.pk, item.pk)
self.assertEqual(repeated.package_count, 2)
adjusted = adjust_confirmed_count(self.user, item.pk, -1)
self.assertEqual(adjusted.package_count, 1)
def test_individual_approval_keeps_unknown_nutrition_null_and_zero_known(self):
item = self._staged_item('87654321')
approved = approve_scan_item(self.user, item.pk, {
'product_name': 'Review beans', 'package_count': '2', 'location_id': self.fridge.pk,
'energy_kcal_100': '0', 'fat_100': '',
})
approved.product.refresh_from_db()
self.assertEqual(approved.status, InventoryScanItem.Status.COMPLETE)
self.assertEqual(approved.product.energy_kcal_100, Decimal('0.000'))
self.assertIsNone(approved.product.fat_100)
stock = KitchenInventoryItem.objects.get(product=approved.product)
self.assertEqual(stock.quantity, 2)
def test_bulk_approval_applies_shared_fields_to_selected_items_atomically(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
items = []
for barcode, name in (('87654321', 'Beans'), ('87654322', 'Rice')):
item = create_active_scan(run, self.user, barcode)
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk, 'product_name': name})
items.append(item)
submit_batch(self.user, batch_id=items[0].batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None), \
patch('food.services.inventory_scanner._send_completion_notification'):
process_next_scan_item()
process_next_scan_item()
approved = approve_scan_items(self.user, [item.pk for item in items], {
'location_id': self.shelf.pk, 'category_name': 'Dry goods'})
self.assertEqual(len(approved), 2)
self.assertTrue(all(item.status == InventoryScanItem.Status.COMPLETE for item in approved))
self.assertTrue(all(item.inventory_item.location == self.shelf for item in approved))
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.user, category__name='Dry goods').count(), 2)
@override_settings(SECURE_SSL_REDIRECT=False) @override_settings(SECURE_SSL_REDIRECT=False)
class InventoryScanWorkflowViewTests(TestCase): class InventoryScanWorkflowViewTests(TestCase):
def setUp(self): def setUp(self):
@@ -170,3 +253,27 @@ class InventoryScanWorkflowViewTests(TestCase):
self.client.force_login(self.other) self.client.force_login(self.other)
self.assertEqual(self.client.get(reverse('food:inventory-scan-queue', args=[run.api_id])).status_code, 404) self.assertEqual(self.client.get(reverse('food:inventory-scan-queue', args=[run.api_id])).status_code, 404)
self.assertEqual(self.client.post(reverse('food:inventory-scan-discard', args=[item.pk])).status_code, 400) self.assertEqual(self.client.post(reverse('food:inventory-scan-discard', args=[item.pk])).status_code, 400)
def test_review_mode_switch_saves_edits_and_bulk_preview_shows_selected_products(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, '1234567890123')
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk, 'product_name': 'Lentils'})
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None):
process_next_scan_item()
item.refresh_from_db()
response = self.client.post(reverse('food:inventory-review-item', args=[item.pk]), {
'action': 'mode', 'mode': 'bulk', 'product_name': 'Green lentils', 'brand': '',
'location_id': self.pantry.pk, 'category_name': 'Pulses', 'package_count': '1',
'package_amount': '', 'package_unit': '', 'notes': '',
})
self.assertRedirects(response, reverse('food:inventory-review') + '?mode=bulk', fetch_redirect_response=False)
item.refresh_from_db()
self.assertEqual((item.product_name, item.location, item.category_name),
('Green lentils', self.pantry, 'Pulses'))
response = self.client.post(reverse('food:inventory-review'), {
'action': 'preview', 'item_ids': [str(item.pk)], 'location_id': self.fridge.pk,
'category_name': 'Dry goods',
})
self.assertContains(response, 'Preview selected products')
self.assertContains(response, 'Green lentils')
+2
View File
@@ -26,6 +26,8 @@ urlpatterns = [
path('inventory/scan/items/<int:item_id>/discard/', scan_views.discard_scan, name='inventory-scan-discard'), path('inventory/scan/items/<int:item_id>/discard/', scan_views.discard_scan, name='inventory-scan-discard'),
path('inventory/scan/items/<int:item_id>/count/', scan_views.adjust_scan_count, name='inventory-scan-count'), path('inventory/scan/items/<int:item_id>/count/', scan_views.adjust_scan_count, name='inventory-scan-count'),
path('inventory/scan/batches/<int:batch_id>/submit/', scan_views.submit_scan_batch, name='inventory-scan-submit'), path('inventory/scan/batches/<int:batch_id>/submit/', scan_views.submit_scan_batch, name='inventory-scan-submit'),
path('inventory/review/', scan_views.inventory_review, name='inventory-review'),
path('inventory/review/items/<int:item_id>/', scan_views.review_item, name='inventory-review-item'),
path('', views.diary, name='diary'), path('', views.diary, name='diary'),
path('add/', views.add_food, name='add'), path('add/', views.add_food, name='add'),
path('search/openfoodfacts/', views.external_search, name='external-search'), path('search/openfoodfacts/', views.external_search, name='external-search'),