import json from django.contrib.auth.decorators import login_required from django.db.models import Prefetch from django.http import JsonResponse from django.shortcuts import get_object_or_404, redirect, render from django.template.loader import render_to_string from django.urls import reverse from django.views.decorators.http import require_GET, require_http_methods, require_POST from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem, InventoryReviewPreference, InventoryScanRun) from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count, approve_scan_item, approve_scan_items, confirm_scan_item, create_active_scan, defer_scan_item, discard_active_scan, get_or_create_active_run, resume_active_run, save_review_item, submit_batch, update_review_preference) @login_required def scanner(request): run = resume_active_run(request.user) draft_batch = run.batches.filter(status=InventoryScanBatch.Status.DRAFT).first() if run else None active_item = draft_batch.items.filter(status=InventoryScanItem.Status.ACTIVE).first() if draft_batch else None queued_count = sum(batch.items.exclude(status=InventoryScanItem.Status.ACTIVE).count() for batch in run.batches.all()) if run else 0 queue_batches = _queue_batches(run) if run else [] return render(request, 'food/inventory_scanner.html', { 'run': run, 'draft_batch': draft_batch, 'active_item': active_item, 'locations': InventoryLocation.objects.filter(user=request.user), 'queued_count': queued_count, 'queue_batches': queue_batches, }) @login_required @require_POST def start_run(request): try: run = get_or_create_active_run(request.user, request.POST.get('location_id')) except (ScanWorkflowError, TypeError, ValueError) as error: return render(request, 'food/inventory_scanner.html', { 'locations': InventoryLocation.objects.filter(user=request.user), 'start_error': str(error), }, status=400) return redirect('food:scanner-inventory') @login_required @require_POST def create_scan(request, run_id): run = get_object_or_404(InventoryScanRun, api_id=run_id, user=request.user, status=InventoryScanRun.Status.ACTIVE) payload, error = _payload(request) if error: return JsonResponse({'error': error}, status=400) try: item = create_active_scan(run, request.user, str(payload.get('barcode', '')).strip()) except ScanWorkflowError as error: 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', { 'item': item, 'locations': InventoryLocation.objects.filter(user=request.user), }, request=request) return JsonResponse({'item': _item_json(item), 'existing': bool(item.source_data.get('cached')), 'html': html}) @login_required @require_POST def confirm_scan(request, item_id): payload, error = _payload(request) if error: return JsonResponse({'error': error}, status=400) payload['opened'] = str(payload.get('opened', '')).lower() in {'true', '1', 'yes', 'on'} try: item = confirm_scan_item(request.user, item_id, payload) except (ScanWorkflowError, TypeError, ValueError) as error: return JsonResponse({'error': str(error)}, status=400) return JsonResponse({'item': _item_json(item)}) @login_required @require_POST def discard_scan(request, item_id): try: discard_active_scan(request.user, item_id) except ScanWorkflowError as error: return JsonResponse({'error': str(error)}, status=400) return JsonResponse({'ok': True}) @login_required @require_POST def adjust_scan_count(request, item_id): payload, error = _payload(request) if error: return JsonResponse({'error': error}, status=400) try: item = adjust_confirmed_count(request.user, item_id, int(payload.get('delta', 0))) except (ScanWorkflowError, TypeError, ValueError) as error: return JsonResponse({'error': str(error)}, status=400) return JsonResponse({'ok': True, 'deleted': item is None, 'item': _item_json(item) if item else None}) @login_required @require_POST def submit_scan_batch(request, batch_id): payload, error = _payload(request) if error: return JsonResponse({'error': error}, status=400) finish = str(payload.get('finish', '')).lower() in {'true', '1', 'yes', 'on'} try: run = submit_batch(request.user, batch_id=batch_id, next_location_id=payload.get('next_location_id'), finish=finish) except (ScanWorkflowError, TypeError, ValueError) as error: return JsonResponse({'error': str(error)}, status=400) if finish: return JsonResponse({'ok': True, 'redirect': reverse('food:inventory')}) next_batch = run.batches.get(status=InventoryScanBatch.Status.DRAFT) return JsonResponse({'ok': True, 'batch_id': next_batch.pk, 'location_id': next_batch.location_id, 'location': next_batch.location.name, 'submit_url': reverse('food:inventory-scan-submit', args=[next_batch.pk])}) @login_required @require_GET def scan_queue(request, run_id): run = get_object_or_404(InventoryScanRun, api_id=run_id, user=request.user) batches = _queue_batches(run) 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): batches = list(run.batches.select_related('location').prefetch_related(Prefetch( 'items', queryset=InventoryScanItem.objects.exclude(status=InventoryScanItem.Status.ACTIVE) .select_related('location', 'product'), to_attr='queue_items')).all()) return batches def _payload(request): if request.content_type == 'application/json': try: payload = json.loads(request.body or b'{}') if not isinstance(payload, dict): return {}, 'Invalid request body.' return payload, None except (json.JSONDecodeError, UnicodeDecodeError): return {}, 'Invalid request body.' return request.POST.dict(), None def _item_json(item): return { 'id': item.pk, 'barcode': item.barcode, 'status': item.status, '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, 'location_id': item.location_id, 'location': item.location.name, 'cached': bool(item.source_data.get('cached')), }