From d305a99b1b4bc1b802596280631bd17739f119ae Mon Sep 17 00:00:00 2001 From: Joren de Graaf Date: Mon, 26 Oct 2026 01:19:55 +0100 Subject: [PATCH] Add continuous inventory barcode scanning workflow --- main/food/scan_views.py | 156 +++++++++ main/food/services/inventory_scanner.py | 31 +- main/food/static/food/food.css | 85 +++++ main/food/static/food/scanner.js | 321 +++++++++++++++++- .../templates/food/inventory_scanner.html | 69 ++++ .../food/partials/inventory_scan_active.html | 36 ++ .../food/partials/inventory_scan_queue.html | 23 ++ main/food/test_inventory_scanner.py | 54 ++- main/food/urls.py | 10 +- main/food/views.py | 2 +- 10 files changed, 776 insertions(+), 11 deletions(-) create mode 100644 main/food/scan_views.py create mode 100644 main/food/templates/food/inventory_scanner.html create mode 100644 main/food/templates/food/partials/inventory_scan_active.html create mode 100644 main/food/templates/food/partials/inventory_scan_queue.html diff --git a/main/food/scan_views.py b/main/food/scan_views.py new file mode 100644 index 0000000..2a9c8aa --- /dev/null +++ b/main/food/scan_views.py @@ -0,0 +1,156 @@ +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_POST + +from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem, + InventoryScanRun) +from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count, + confirm_scan_item, create_active_scan, discard_active_scan, + get_or_create_active_run, resume_active_run, submit_batch) + + +@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) + 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}) + + +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')), + } diff --git a/main/food/services/inventory_scanner.py b/main/food/services/inventory_scanner.py index e390776..ea0626b 100644 --- a/main/food/services/inventory_scanner.py +++ b/main/food/services/inventory_scanner.py @@ -7,6 +7,7 @@ from django.core.exceptions import ValidationError from django.db import IntegrityError, connections, transaction from django.db.models import F, Q from django.utils import timezone +from django.utils.dateparse import parse_date from food.models import (FoodProduct, InventoryCategory, InventoryLocation, InventoryReviewPreference, InventoryScanBatch, @@ -100,7 +101,10 @@ def confirm_scan_item(user, item_id, values): item.inner_pack_amount = _decimal_or_none(values.get('inner_pack_amount'), 'Enter a valid inner pack amount.') item.inner_pack_label = str(values.get('inner_pack_label', '')).strip()[:40] item.piece_label = str(values.get('piece_label', '')).strip()[:40] - item.best_before = values.get('best_before') or None + best_before = str(values.get('best_before', '')).strip() + item.best_before = parse_date(best_before) if best_before else None + if best_before and item.best_before is None: + raise ScanWorkflowError('Enter a valid best-before date.') item.opened = bool(values.get('opened')) item.user_data = _item_data(item) item.status = InventoryScanItem.Status.CONFIRMED @@ -136,6 +140,7 @@ def adjust_confirmed_count(user, item_id, delta): def submit_batch(user, *, batch_id, next_location_id=None, finish=False): + run_id = None with transaction.atomic(): batch = (InventoryScanBatch.objects.select_for_update().select_related('run') .filter(pk=batch_id, run__user=user).first()) @@ -149,13 +154,22 @@ def submit_batch(user, *, batch_id, next_location_id=None, finish=False): if batch.items.filter(status=InventoryScanItem.Status.ACTIVE).exists(): raise ScanWorkflowError('Confirm or remove the active item before saving this batch.') items = batch.items.filter(status=InventoryScanItem.Status.CONFIRMED) - if not items.exists(): + has_items = items.exists() + prior_submissions = run.batches.exclude(pk=batch.pk).filter( + status__in=(InventoryScanBatch.Status.QUEUED, InventoryScanBatch.Status.COMPLETE)).exists() + if not has_items and not (finish and prior_submissions): raise ScanWorkflowError('Confirm at least one item before saving this batch.') now = timezone.now() - items.update(status=InventoryScanItem.Status.QUEUED, next_attempt_at=now) - batch.status = InventoryScanBatch.Status.QUEUED - batch.submitted_at = now - batch.save(update_fields=('status', 'submitted_at')) + if has_items: + items.update(status=InventoryScanItem.Status.QUEUED, next_attempt_at=now) + batch.status = InventoryScanBatch.Status.QUEUED + batch.submitted_at = now + batch.save(update_fields=('status', 'submitted_at')) + else: + batch.status = InventoryScanBatch.Status.COMPLETE + batch.submitted_at = now + batch.completed_at = now + batch.save(update_fields=('status', 'submitted_at', 'completed_at')) if finish: run.status = InventoryScanRun.Status.PROCESSING run.submitted_at = now @@ -168,7 +182,10 @@ def submit_batch(user, *, batch_id, next_location_id=None, finish=False): next_sequence = (run.batches.order_by('-sequence').values_list('sequence', flat=True).first() or 0) + 1 InventoryScanBatch.objects.create(run=run, location=location, sequence=next_sequence) run.save(update_fields=('selected_location',)) - return run + run_id = run.pk + if finish: + _refresh_completion(run_id) + return InventoryScanRun.objects.get(pk=run_id) def _claim_next_item(): diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index 94f7db3..cd77dad 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -91,6 +91,91 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .inventory-heading-actions{display:flex;align-items:center;justify-content:flex-end;gap:.5rem;flex-wrap:wrap} .inventory-heading-actions .button{min-height:44px} @media(max-width:600px){.inventory-page>.food-heading{align-items:flex-start;flex-wrap:wrap}.inventory-heading-actions{justify-content:flex-start;width:100%}} + +/* Continuous inventory scan-in */ +.inventory-scan-page{max-width:1120px;padding-top:1.25rem} +.inventory-scan-page>.food-heading{align-items:flex-end;margin-bottom:1rem} +.inventory-scan-page>.food-heading h1{margin:.35rem 0;color:#183c2c} +.inventory-scan-location{display:inline-flex;align-items:center;min-height:42px;padding:.55rem .9rem;background:#e9f3ec;border:1px solid #d8e1d8;border-radius:999px;color:#247452;font-weight:700} +.inventory-scan-start{max-width:620px;margin:2rem auto;background:#fff;border:1px solid #d8e1d8;border-radius:16px} +.inventory-scan-start-form{display:grid;grid-template-columns:1fr auto;align-items:end;gap:.65rem 1rem;margin-top:1.25rem} +.inventory-scan-start-form label{grid-column:1/-1;font-weight:700} +.inventory-scan-start-form select,.inventory-scan-next-row select{min-height:46px;border:1px solid #b9c9bd;border-radius:10px;padding:.65rem;background:#fff;color:#19242b} +.inventory-scan-layout{display:grid;grid-template-columns:minmax(300px,.9fr) minmax(360px,1.1fr);gap:1rem;align-items:start} +.inventory-scan-camera,.inventory-scan-active,.inventory-scan-queue,.inventory-scan-controls{border:1px solid #d8e1d8;border-radius:14px} +.inventory-scan-camera{position:sticky;top:1rem;background:#fff;padding:1rem} +.inventory-camera-label{display:flex;align-items:center;gap:.55rem;margin-bottom:.8rem;color:#183c2c} +.inventory-camera-label>span:last-child{margin-left:auto;color:#63776c;font-size:.8rem;text-align:right} +.inventory-camera-indicator{width:.55rem;height:.55rem;border-radius:50%;background:#247452;box-shadow:0 0 0 4px #e9f3ec} +.inventory-scan-camera .food-camera-frame{aspect-ratio:4/3;background:#17382d;border-radius:14px} +.inventory-scan-camera .food-scan-guide{inset:26% 10%;border-color:#91d9ae} +.inventory-scan-camera [data-scanner-status]{min-height:1.5rem;color:#4e6c59} +.inventory-scan-manual{margin-top:1rem;padding-top:1rem;border-top:1px solid #e3e9e4} +.inventory-scan-manual>div{display:flex;gap:.5rem;margin-top:.35rem} +.inventory-scan-manual input{flex:1;width:100%;min-width:0} +.inventory-scan-camera [hidden]{display:none!important} +.inventory-scan-right{display:grid;gap:.8rem;min-width:0} +.inventory-scan-active{margin:0;background:#fff;padding:1.15rem;box-shadow:0 5px 20px #183c2c0a} +.inventory-scan-active-heading{display:flex;align-items:center;gap:.5rem;color:#247452;font-size:.82rem} +.inventory-scan-active-heading p{margin:0;overflow-wrap:anywhere} +.inventory-scan-status-dot{width:.55rem;height:.55rem;flex:none;border-radius:50%;background:#247452} +.inventory-scan-active form{display:grid;gap:.75rem} +.inventory-scan-active form>label,.inventory-scan-active .inventory-scan-product-title{display:grid;gap:.3rem;color:#273d33;font-size:.9rem;font-weight:650} +.inventory-scan-active input,.inventory-scan-active select,.inventory-scan-active textarea{width:100%;min-width:0;min-height:44px;padding:.6rem .7rem;border:1px solid #c8d4ca;border-radius:9px;background:#fff;color:#19242b;font:inherit;font-weight:400} +.inventory-scan-active textarea{min-height:64px;resize:vertical} +.inventory-scan-fields{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem} +.inventory-scan-fields--package{grid-template-columns:.75fr 1fr 1fr} +.inventory-scan-fields label{display:grid;gap:.3rem;min-width:0;color:#273d33;font-size:.85rem;font-weight:650} +.inventory-scan-active .inventory-scan-fields input,.inventory-scan-active .inventory-scan-fields select{font-weight:400} +.inventory-scan-total{margin:0;color:#4e6c59;font-size:.85rem} +.inventory-scan-more,.inventory-scan-nutrition{padding:.65rem .75rem;border:1px solid #e2e9e3;border-radius:10px;background:#f8faf8;color:#273d33} +.inventory-scan-more summary,.inventory-scan-nutrition summary{cursor:pointer;font-weight:700} +.inventory-scan-more .inventory-scan-fields{margin-top:.8rem} +.inventory-scan-checkbox{display:flex!important;align-items:center;gap:.55rem;min-height:44px} +.inventory-scan-checkbox input{width:20px!important;min-height:20px!important} +.inventory-scan-nutrition dl{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.35rem .8rem;margin:.75rem 0 0} +.inventory-scan-nutrition dl div{display:flex;justify-content:space-between;gap:.5rem;border-bottom:1px solid #e5ebe6;padding:.25rem 0;font-size:.8rem} +.inventory-scan-nutrition dt{color:#63776c}.inventory-scan-nutrition dd{margin:0;font-weight:700} +.inventory-scan-meta,.inventory-scan-hint,.inventory-scan-note{margin:0;color:#63776c;font-size:.78rem} +.inventory-scan-card-actions{display:flex;gap:.5rem;flex-wrap:wrap} +.inventory-scan-card-actions .button{min-height:46px} +.inventory-scan-active :focus-visible,.inventory-scan-camera :focus-visible,.inventory-scan-controls :focus-visible,.inventory-scan-queue :focus-visible{outline:3px solid #f2ad49;outline-offset:2px} +.inventory-scan-queue{margin:0;background:#fff;padding:1rem} +.inventory-scan-queue-heading,.inventory-scan-batch-heading{display:flex;align-items:center;justify-content:space-between;gap:.75rem} +.inventory-scan-queue-heading h2{margin:0;color:#183c2c;font-size:1.15rem} +.inventory-kicker{margin:0;color:#63776c;font-size:.7rem;font-weight:800;letter-spacing:.08em;text-transform:uppercase} +.inventory-scan-queue-heading>span,.inventory-scan-batch-heading>span{color:#63776c;font-size:.78rem} +.inventory-scan-batch{margin-top:.75rem} +.inventory-scan-batch-heading{padding:.35rem 0;border-bottom:1px solid #e3e9e4} +.inventory-scan-batch-heading h3{margin:0;color:#247452;font-size:.9rem} +.inventory-scan-queue-item{display:flex;align-items:center;justify-content:space-between;gap:.7rem;padding:.7rem .1rem;border-bottom:1px solid #edf0ed} +.inventory-scan-queue-item-main{display:flex;align-items:center;gap:.6rem;min-width:0} +.inventory-scan-queue-item-main>div{display:grid;gap:.15rem;min-width:0} +.inventory-scan-queue-item-main strong{color:#183c2c;overflow-wrap:anywhere} +.inventory-scan-queue-item-main small,.inventory-scan-queue-item-side small{color:#63776c;font-size:.74rem;overflow-wrap:anywhere} +.inventory-scan-queue-state{width:.55rem;height:.55rem;flex:none;border-radius:50%;background:#aab5ac} +.inventory-scan-queue-state--complete{background:#247452} +.inventory-scan-queue-state--processing,.inventory-scan-queue-state--queued{background:#d99427} +.inventory-scan-queue-state--needs_review,.inventory-scan-queue-state--failed{background:#bd554d} +.inventory-scan-queue-item-side{display:grid;justify-items:end;gap:.15rem;flex:none;color:#273d33;font-size:.78rem} +.inventory-scan-count-controls{display:flex;align-items:center;gap:.3rem;margin-top:.2rem} +.inventory-scan-count-controls button{width:36px;height:36px;border:1px solid #c8d4ca;border-radius:9px;background:#f8faf8;color:#183c2c;font-size:1.2rem;cursor:pointer} +.inventory-scan-empty{margin:.8rem 0;color:#63776c;font-size:.85rem} +.inventory-scan-controls{margin:0;background:#e9f3ec;padding:1rem;color:#4e6c59} +.inventory-scan-controls>p:first-child{margin:.1rem 0 .85rem;font-size:.85rem} +.inventory-scan-controls form{display:grid;gap:.5rem} +.inventory-scan-controls label{font-size:.85rem;font-weight:700} +.inventory-scan-next-row{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:.5rem} +.inventory-scan-next-row select{min-width:0} +.inventory-scan-done{width:100%;background:#183c2c} +.inventory-scan-controls button:disabled{opacity:.52;cursor:not-allowed} +.inventory-scan-error{color:#9b342d;font-weight:700} +.inventory-scan-loading{min-height:140px;display:grid;align-content:center;color:#4e6c59} +.inventory-scan-skeleton{min-height:100px;display:grid;align-content:center;color:#63776c;border-style:dashed} +.inventory-scan-skeleton[hidden]{display:none!important} +@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(prefers-reduced-motion:reduce){.inventory-scan-page *{scroll-behavior:auto!important;animation:none!important;transition:none!important}} .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} diff --git a/main/food/static/food/scanner.js b/main/food/static/food/scanner.js index c88d7df..635bd82 100644 --- a/main/food/static/food/scanner.js +++ b/main/food/static/food/scanner.js @@ -1,6 +1,10 @@ (() => { - const root = document.querySelector('[data-food-scanner]'); + const root = document.querySelector('[data-food-scanner], [data-inventory-scanner]'); if (!root) return; + if (root.hasAttribute('data-inventory-scanner')) { + initInventoryScanner(root); + return; + } const video = root.querySelector('[data-scanner-video]'); const status = root.querySelector('[data-scanner-status]'); const startButton = root.querySelector('[data-scanner-start]'); @@ -141,4 +145,319 @@ root.querySelector('[data-scanner-close]').addEventListener('click', stop); document.addEventListener('visibilitychange', () => { if (document.hidden) stop(); }); window.addEventListener('pagehide', stop); + + function initInventoryScanner(root) { + const video = root.querySelector('[data-scanner-video]'); + const status = root.querySelector('[data-scanner-status]'); + const startButton = root.querySelector('[data-scanner-start]'); + const stopButton = root.querySelector('[data-scanner-stop]'); + const manualForm = root.querySelector('[data-scanner-form]'); + const barcodeInput = root.querySelector('[data-scanner-barcode]'); + const activeWrap = root.querySelector('[data-scan-active-wrap]'); + const queue = root.querySelector('[data-scan-queue]'); + const submitForm = root.querySelector('[data-scan-submit]'); + const cameraFormats = ['ean_13', 'ean_8', 'upc_a', 'upc_e', 'code_128']; + let stream = null; + let zxingControls = null; + let nativeFrame = null; + let nativeTimeout = null; + let generation = 0; + let activeItemId = activeWrap.querySelector('[data-scan-active][data-item-id]')?.dataset.itemId || null; + let locked = Boolean(activeItemId); + let opening = false; + let fallbackStarted = false; + let nativeScan = null; + let lastBarcode = ''; + let lastBarcodeAt = 0; + let queueRefreshTimer = null; + + const say = (message) => { status.textContent = message; }; + const csrf = () => root.querySelector('input[name="csrfmiddlewaretoken"]')?.value || + document.querySelector('input[name="csrfmiddlewaretoken"]')?.value || ''; + const request = async (url, body) => { + const response = await fetch(url, { method: 'POST', body, credentials: 'same-origin', + headers: { 'X-CSRFToken': csrf(), 'X-Requested-With': 'XMLHttpRequest' } }); + const data = await response.json().catch(() => ({})); + if (!response.ok) throw new Error(data.error || 'The scan could not be saved. Try again.'); + return data; + }; + const refreshQueue = async () => { + try { + const response = await fetch(root.dataset.queueUrl, { credentials: 'same-origin', + headers: { 'X-Requested-With': 'XMLHttpRequest' } }); + if (!response.ok) return; + const html = await response.text(); + const temporary = document.createElement('div'); + temporary.innerHTML = html; + if (queue.innerHTML !== temporary.innerHTML) queue.innerHTML = temporary.innerHTML; + updateQueueCount(); + } catch (error) { /* Keep the locally visible queue; the next poll will retry. */ } + }; + const updateQueueCount = () => { + const count = queue.querySelectorAll('[data-queue-item]').length; + const label = root.querySelector('[data-scan-queue-count]'); + if (label) label.textContent = `${count} queued item${count === 1 ? '' : 's'}`; + const draft = queue.querySelector('[data-batch-status="draft"]'); + const currentHasItems = Boolean(draft?.querySelector('[data-queue-status="confirmed"]')); + const previousHasItems = Array.from(queue.querySelectorAll('[data-batch-status="queued"], [data-batch-status="complete"]')) + .some(batch => batch.querySelector('[data-queue-item]')); + submitForm.querySelector('[data-scan-next]').disabled = !currentHasItems; + submitForm.querySelector('[data-scan-done]').disabled = !(currentHasItems || previousHasItems); + }; + const clearActive = () => { + activeItemId = null; + activeWrap.innerHTML = '

Scan a product to begin.

'; + locked = false; + resumeDetection(); + refreshQueue(); + setTimeout(updateLeaveWarning, 50); + }; + const updateTotal = (form) => { + const count = Number(form.elements.package_count?.value || 1); + const amount = form.elements.package_amount?.value; + const unit = form.elements.package_unit?.value; + const total = form.querySelector('[data-scan-total]'); + if (total) total.textContent = `${count} × ${amount || 'unknown'} ${unit || ''}`.trim(); + }; + const bindActiveCard = () => { + const card = activeWrap.querySelector('[data-scan-active][data-item-id]'); + if (!card) return; + activeItemId = card.dataset.itemId; + locked = true; + const form = card.querySelector('[data-scan-confirm]'); + updateTotal(form); + form.addEventListener('input', () => updateTotal(form)); + form.addEventListener('change', () => updateTotal(form)); + form.addEventListener('submit', async (event) => { + event.preventDefault(); + const submit = form.querySelector('[type="submit"]'); + const errorNode = form.querySelector('[data-scan-item-error]'); + submit.disabled = true; + errorNode.hidden = true; + try { + const data = await request(form.action, new FormData(form)); + clearActive(); + say(`${data.item.product_name} added to this session. ${stream ? 'Camera is still active.' : 'Start the camera or continue with manual barcodes.'}`); + } catch (error) { + errorNode.textContent = error.message; + errorNode.hidden = false; + submit.disabled = false; + } + }); + card.querySelector('[data-scan-discard]')?.addEventListener('click', async () => { + if (!confirm('Remove this unconfirmed barcode scan?')) return; + try { + await request(`/food/inventory/scan/items/${activeItemId}/discard/`, new FormData(form)); + clearActive(); + say('Unconfirmed scan removed. Camera is still active.'); + } catch (error) { + const errorNode = form.querySelector('[data-scan-item-error]'); + errorNode.textContent = error.message; + errorNode.hidden = false; + } + }); + let touchStart = null; + card.addEventListener('pointerdown', (event) => { touchStart = { x: event.clientX, y: event.clientY }; }); + card.addEventListener('pointerup', (event) => { + if (touchStart && touchStart.x - event.clientX > 80 && + Math.abs(touchStart.y - event.clientY) < 100 && form.checkValidity()) form.requestSubmit(); + touchStart = null; + }); + setTimeout(() => form.querySelector('[name="product_name"]')?.focus({ preventScroll: true }), 0); + updateLeaveWarning(); + }; + const showDetectedBarcode = async (value) => { + const code = String(value || '').trim(); + if (locked || !/^[0-9]{6,64}$/.test(code)) return; + const now = Date.now(); + if (code === lastBarcode && now - lastBarcodeAt < 1800) { + say('Repeated camera detection ignored. Use + in the queue to add another package.'); + return; + } + lastBarcode = code; + lastBarcodeAt = now; + locked = true; + activeWrap.innerHTML = `

Barcode detected · ${code}

Preparing product card…

`; + say(`Barcode ${code} detected. Review the package details below.`); + const body = new FormData(); + body.set('barcode', code); + try { + const data = await request(root.dataset.createUrl, body); + activeWrap.innerHTML = data.html; + bindActiveCard(); + } catch (error) { + activeWrap.innerHTML = ''; + activeWrap.querySelector('[role="alert"]').textContent = error.message; + activeItemId = null; + locked = false; + resumeDetection(); + } + }; + const loadZXing = () => new Promise((resolve, reject) => { + if (window.ZXingBrowser) return resolve(window.ZXingBrowser); + const script = document.createElement('script'); + script.src = root.dataset.zxingUrl; + script.onload = () => window.ZXingBrowser ? resolve(window.ZXingBrowser) : reject(new Error('Scanner library unavailable')); + script.onerror = () => reject(new Error('Scanner library unavailable')); + document.head.append(script); + }); + const startFallback = async (token) => { + if (token !== generation || !stream || fallbackStarted) return; + fallbackStarted = true; + if (nativeFrame !== null) cancelAnimationFrame(nativeFrame); + nativeFrame = null; + if (nativeTimeout !== null) clearTimeout(nativeTimeout); + nativeTimeout = null; + try { + const zxing = await loadZXing(); + if (token !== generation || !stream) return; + const reader = new zxing.BrowserMultiFormatOneDReader(); + const controls = await reader.decodeFromStream(stream, video, (result, error, activeControls) => { + if (result) { + zxingControls = activeControls; + showDetectedBarcode(result.getText()); + } + }); + if (token !== generation || !stream) controls.stop(); + else zxingControls = controls; + } catch (error) { + say('Scanner unavailable. Enter the barcode manually.'); + stopCamera(); + } + }; + const beginNativeDetection = async (token) => { + if (!('BarcodeDetector' in window)) return false; + try { + const supported = await window.BarcodeDetector.getSupportedFormats(); + const usable = cameraFormats.filter((format) => supported.includes(format)); + if (!usable.length || token !== generation) return false; + const detector = new window.BarcodeDetector({ formats: usable }); + nativeScan = async () => { + if (token !== generation || locked || fallbackStarted || !stream) return; + try { + const hits = await detector.detect(video); + if (token !== generation || locked || fallbackStarted) return; + if (hits.length) { showDetectedBarcode(hits[0].rawValue); return; } + } catch (error) { + startFallback(token); + return; + } + nativeFrame = requestAnimationFrame(nativeScan); + }; + nativeTimeout = setTimeout(() => { if (token === generation) startFallback(token); }, 12000); + nativeFrame = requestAnimationFrame(nativeScan); + return true; + } catch (error) { return false; } + }; + const resumeDetection = () => { + if (!stream || locked || fallbackStarted || !nativeScan || nativeFrame !== null) return; + nativeFrame = requestAnimationFrame(nativeScan); + }; + const stopCamera = () => { + generation += 1; + if (nativeFrame !== null) cancelAnimationFrame(nativeFrame); + nativeFrame = null; + if (nativeTimeout !== null) clearTimeout(nativeTimeout); + nativeTimeout = null; + zxingControls?.stop(); + zxingControls = null; + stream?.getTracks().forEach((track) => track.stop()); + stream = null; + fallbackStarted = false; + nativeScan = null; + video.pause(); + video.srcObject = null; + startButton.hidden = false; + stopButton.hidden = true; + opening = false; + }; + const openCamera = async () => { + if (opening || stream) return; + opening = true; + fallbackStarted = false; + const token = ++generation; + startButton.hidden = true; + say('Requesting camera…'); + try { + if (!navigator.mediaDevices?.getUserMedia) throw new Error('Camera API unavailable'); + const acquired = await navigator.mediaDevices.getUserMedia({ video: { facingMode: { ideal: 'environment' } } }); + if (token !== generation) { acquired.getTracks().forEach((track) => track.stop()); return; } + stream = acquired; + video.srcObject = stream; + await video.play(); + opening = false; + stopButton.hidden = false; + say(locked ? 'Camera live. Confirm the active item to scan the next one.' : 'Camera live. Align a barcode inside the frame.'); + if (!(await beginNativeDetection(token))) await startFallback(token); + } catch (error) { + stopCamera(); + say('Camera unavailable or permission denied. Enter the barcode manually.'); + barcodeInput.focus(); + } + }; + const updateLeaveWarning = () => { + const pending = Boolean(activeItemId || queue.querySelector('[data-queue-item][data-queue-status="confirmed"]')); + root.dataset.hasPending = pending ? 'true' : 'false'; + }; + + startButton.addEventListener('click', openCamera); + stopButton.addEventListener('click', () => { stopCamera(); say('Camera paused.'); startButton.focus(); }); + manualForm.addEventListener('submit', (event) => { + event.preventDefault(); + if (!barcodeInput.reportValidity()) return; + showDetectedBarcode(barcodeInput.value); + barcodeInput.value = ''; + }); + activeWrap.addEventListener('submit', (event) => { + if (event.target.matches('[data-scan-confirm]')) return; + }); + queue.addEventListener('click', async (event) => { + const button = event.target.closest('[data-scan-count]'); + if (!button) return; + const row = button.closest('[data-queue-item]'); + const delta = Number(button.dataset.scanCount); + if (delta < 0 && row.querySelector('.inventory-scan-queue-item-side span')?.textContent.trim() === '1 package' && + !confirm('Remove this item from the unsaved batch?')) return; + const body = new FormData(); body.set('delta', String(delta)); + try { + await request(`/food/inventory/scan/items/${row.dataset.itemId}/count/`, body); + await refreshQueue(); + say(delta > 0 ? 'Package count increased.' : 'Package count updated. Use + to undo.'); + } catch (error) { say(error.message); } + }); + submitForm.querySelector('[data-scan-next]').addEventListener('click', async () => { + const body = new FormData(submitForm); + try { + const data = await request(submitForm.action, body); + submitForm.action = data.submit_url; + root.dataset.submitUrl = data.submit_url; + root.dataset.batchId = String(data.batch_id); + document.querySelector('[data-scan-current-location]').textContent = `Scanning into: ${data.location}`; + await refreshQueue(); + say(`Saved this batch. Now scanning into ${data.location}. ${stream ? 'Camera is still active.' : 'Start the camera or continue with manual barcodes.'}`); + } catch (error) { say(error.message); } + }); + submitForm.querySelector('[data-scan-done]').addEventListener('click', async () => { + if (!confirm('Finish this scan run and send confirmed items for background processing?')) return; + const body = new FormData(submitForm); body.set('finish', 'true'); + try { + const data = await request(submitForm.action, body); + location.assign(data.redirect); + } catch (error) { say(error.message); } + }); + const leaveLink = document.querySelector('.inventory-scan-page .food-heading a[href]'); + leaveLink?.addEventListener('click', (event) => { + if (root.dataset.hasPending === 'true' && + !confirm('Leave the scanner? Your active and confirmed items are saved and will be here when you return.')) event.preventDefault(); + }); + window.addEventListener('beforeunload', (event) => { + if (root.dataset.hasPending === 'true') { event.preventDefault(); event.returnValue = ''; } + }); + window.addEventListener('pagehide', stopCamera); + queueRefreshTimer = setInterval(refreshQueue, 5000); + if (activeItemId) bindActiveCard(); + updateQueueCount(); + updateLeaveWarning(); + void queueRefreshTimer; + } })(); diff --git a/main/food/templates/food/inventory_scanner.html b/main/food/templates/food/inventory_scanner.html new file mode 100644 index 0000000..e69af25 --- /dev/null +++ b/main/food/templates/food/inventory_scanner.html @@ -0,0 +1,69 @@ +{% extends 'planner/base.html' %}{% load static %} +{% block title %}Bulk scan inventory · Tasknest{% endblock %} +{% block content %} + +
+
+
← Kitchen inventory

Bulk scan inventory

Scan packages into a location, then review your session queue.

+ {% if run %}{{ draft_batch.location.name }}{% endif %} +
+ {% if not run %} +
+

Choose a starting location

+

Your session is saved as you scan, so you can return to it after navigating away.

+ {% if start_error %}{% endif %} + {% if locations %} +
+ {% csrf_token %} + + +
+ {% else %} +

You need an inventory location before you can scan.

Add an inventory location + {% endif %} +
+ {% else %} +
+
+
Camera scannerCamera stays on while you confirm packages
+
+

Camera is off. Start the camera or enter a barcode.

+
+
+
+
+

Product data from Open Food Facts.

+
+
+
+ {% if active_item %}{% include 'food/partials/inventory_scan_active.html' with item=active_item locations=locations %}{% else %} + + {% endif %} +
+
+

Current session

Scan queue

{{ queued_count }} queued item{{ queued_count|pluralize }}
+
+ {% include 'food/partials/inventory_scan_queue.html' with run=run batches=queue_batches %} +
+
+
+

The camera remains active as items move into the queue. Use the package controls to correct repeated scans or undo a count.

+
+ {% csrf_token %} +
+ +
+

Processing runs in the background. Items without a confirmed product or valid package setup appear in Needs Review.

+
+
+
+ {% endif %} +
+ +{% endblock %} diff --git a/main/food/templates/food/partials/inventory_scan_active.html b/main/food/templates/food/partials/inventory_scan_active.html new file mode 100644 index 0000000..8e92814 --- /dev/null +++ b/main/food/templates/food/partials/inventory_scan_active.html @@ -0,0 +1,36 @@ +
+

Barcode detected · {{ item.barcode }}

+
+ {% csrf_token %} +
+ +
+ + + +
+

Total: {{ item.package_count }} × {{ item.package_amount|default:'unknown' }} {{ item.package_unit }}

+
Piece and inner pack details +
+ + + + + + + +
+
+
+ + + + +
+ + {% if item.source_data.nutrition %}
Open Food Facts nutrition · unknown values stay blank
{% for name,value in item.source_data.nutrition.items %}
{{ name|cut:'_100'|title }}
{% if value is None %}Unknown{% else %}{{ value }}{% endif %}
{% endfor %}
{% else %}

Nutrition will be fetched in the background. Missing values remain unknown.

{% endif %} +
+

You can also swipe this card left to confirm. Keyboard users can submit with Enter.

+ +
+
diff --git a/main/food/templates/food/partials/inventory_scan_queue.html b/main/food/templates/food/partials/inventory_scan_queue.html new file mode 100644 index 0000000..2b243e0 --- /dev/null +++ b/main/food/templates/food/partials/inventory_scan_queue.html @@ -0,0 +1,23 @@ +
+ {% for batch in batches %} +
+

{{ batch.location.name }}

{{ batch.get_status_display }}
+ {% for item in batch.queue_items %} +
+
{{ item.product_name|default:'Product details needed' }}{{ item.barcode }} · {{ item.get_status_display }}{% if item.last_error %} · {{ item.last_error }}{% endif %}
+
+ {{ item.package_count }} package{{ item.package_count|pluralize }} + {% if item.package_amount %}{{ item.package_amount }} {{ item.package_unit }}{% endif %} + {% if batch.status == 'draft' and item.status == 'confirmed' %} +
+ + {{ item.package_count }} + +
+ {% endif %} +
+
+ {% empty %}

No confirmed items in this location batch yet.

{% endfor %} +
+ {% empty %}

Your saved batches will appear here.

{% endfor %} +
diff --git a/main/food/test_inventory_scanner.py b/main/food/test_inventory_scanner.py index 15df235..c4d0fe1 100644 --- a/main/food/test_inventory_scanner.py +++ b/main/food/test_inventory_scanner.py @@ -3,7 +3,8 @@ from decimal import Decimal from unittest.mock import patch from django.contrib.auth import get_user_model -from django.test import TestCase +from django.test import TestCase, override_settings +from django.urls import reverse from django.utils import timezone from food.models import (FoodProduct, InventoryLocation, InventoryScanBatch, @@ -118,3 +119,54 @@ class OpenFoodFactsGlobalLimitTests(TestCase): with off_http_request('product', wait=False): raise RuntimeError('network error after request start') self.assertEqual(OpenFoodFactsRequest.objects.count(), 1) + + +@override_settings(SECURE_SSL_REDIRECT=False) +class InventoryScanWorkflowViewTests(TestCase): + def setUp(self): + self.user = get_user_model().objects.create_user(username='scanner-web', password='test-password') + self.other = get_user_model().objects.create_user(username='scanner-web-other', password='test-password') + self.fridge = InventoryLocation.objects.create(user=self.user, name='Fridge') + self.pantry = InventoryLocation.objects.create(user=self.user, name='Pantry') + self.client.force_login(self.user) + + def test_scanner_page_starts_and_resumes_a_persisted_session(self): + response = self.client.get(reverse('food:scanner-inventory')) + self.assertContains(response, 'Choose a starting location') + response = self.client.post(reverse('food:inventory-scan-start'), {'location_id': self.fridge.pk}) + self.assertRedirects(response, reverse('food:scanner-inventory'), fetch_redirect_response=False) + run = InventoryScanRun.objects.get(user=self.user) + response = self.client.get(reverse('food:scanner-inventory')) + self.assertContains(response, 'Camera scanner') + self.assertContains(response, 'Fridge') + self.assertContains(response, str(run.api_id)) + + def test_confirm_save_next_location_and_done_endpoints(self): + run = get_or_create_active_run(self.user, self.fridge.pk) + response = self.client.post(reverse('food:inventory-scan-create', args=[run.api_id]), + {'barcode': '1234567890123'}) + self.assertEqual(response.status_code, 200) + item_id = response.json()['item']['id'] + self.assertIn('Confirm & keep scanning', response.json()['html']) + response = self.client.post(reverse('food:inventory-scan-confirm', args=[item_id]), { + 'location_id': self.fridge.pk, 'product_name': 'Black beans', 'package_count': '2', + 'package_amount': '', 'package_unit': '', 'opened': '', + }) + self.assertEqual(response.status_code, 200) + item = InventoryScanItem.objects.get(pk=item_id) + response = self.client.post(reverse('food:inventory-scan-submit', args=[item.batch_id]), + {'next_location_id': self.pantry.pk}) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['location'], 'Pantry') + next_batch = run.batches.get(status=InventoryScanBatch.Status.DRAFT) + response = self.client.post(reverse('food:inventory-scan-submit', args=[next_batch.pk]), {'finish': 'true'}) + self.assertEqual(response.json()['redirect'], reverse('food:inventory')) + run.refresh_from_db() + self.assertEqual(run.status, InventoryScanRun.Status.PROCESSING) + + def test_scan_item_and_queue_are_private_to_session_owner(self): + run = get_or_create_active_run(self.user, self.fridge.pk) + item = create_active_scan(run, self.user, '1234567890123') + 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.post(reverse('food:inventory-scan-discard', args=[item.pk])).status_code, 400) diff --git a/main/food/urls.py b/main/food/urls.py index 602a7fd..f0c15db 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -1,6 +1,6 @@ from django.urls import path -from . import views, inventory, token_views +from . import views, inventory, token_views, scan_views app_name = 'food' @@ -18,6 +18,14 @@ urlpatterns = [ 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('inventory/scan/', scan_views.scanner, name='scanner-inventory'), + path('inventory/scan/start/', scan_views.start_run, name='inventory-scan-start'), + path('inventory/scan//items/', scan_views.create_scan, name='inventory-scan-create'), + path('inventory/scan//queue/', scan_views.scan_queue, name='inventory-scan-queue'), + path('inventory/scan/items//confirm/', scan_views.confirm_scan, name='inventory-scan-confirm'), + path('inventory/scan/items//discard/', scan_views.discard_scan, name='inventory-scan-discard'), + path('inventory/scan/items//count/', scan_views.adjust_scan_count, name='inventory-scan-count'), + path('inventory/scan/batches//submit/', scan_views.submit_scan_batch, name='inventory-scan-submit'), 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/food/views.py b/main/food/views.py index 6267d2d..7825307 100644 --- a/main/food/views.py +++ b/main/food/views.py @@ -365,7 +365,7 @@ def import_product(request): @login_required def scanner(request): if request.GET.get('mode') == 'inventory': - return render(request, 'food/scanner.html', {'inventory_mode': True}) + return redirect('food:scanner-inventory') day, error = _day(request) if error: return error