Add continuous inventory barcode scanning workflow
This commit is contained in:
@@ -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')),
|
||||
}
|
||||
@@ -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():
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
@@ -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 = '<article class="food-card inventory-scan-active inventory-scan-skeleton" data-scan-active><p>Scan a product to begin.</p></article>';
|
||||
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 = `<article class="food-card inventory-scan-active inventory-scan-loading" aria-live="polite"><p>Barcode detected · <strong>${code}</strong></p><p>Preparing product card…</p></article>`;
|
||||
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 = '<article class="food-card inventory-scan-active inventory-scan-error" role="alert"></article>';
|
||||
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;
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
{% extends 'planner/base.html' %}{% load static %}
|
||||
{% block title %}Bulk scan inventory · Tasknest{% endblock %}
|
||||
{% block content %}
|
||||
<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-bulk-2">
|
||||
<main class="food-page inventory-scan-page">
|
||||
<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>
|
||||
{% if run %}<span class="inventory-scan-location" data-scan-current-location>{{ draft_batch.location.name }}</span>{% endif %}
|
||||
</header>
|
||||
{% if not run %}
|
||||
<section class="food-card inventory-scan-start">
|
||||
<h2>Choose a starting location</h2>
|
||||
<p>Your session is saved as you scan, so you can return to it after navigating away.</p>
|
||||
{% if start_error %}<p class="inventory-scan-error" role="alert">{{ start_error }}</p>{% endif %}
|
||||
{% if locations %}
|
||||
<form method="post" action="{% url 'food:inventory-scan-start' %}" class="inventory-scan-start-form">
|
||||
{% csrf_token %}<label for="scan-start-location">Scan into</label>
|
||||
<select id="scan-start-location" name="location_id" required>{% for location in locations %}<option value="{{ location.pk }}">{{ location.name }}</option>{% endfor %}</select>
|
||||
<button class="button" type="submit">Start scanning</button>
|
||||
</form>
|
||||
{% else %}
|
||||
<p>You need an inventory location before you can scan.</p><a class="button" href="{% url 'food:inventory-add' %}">Add an inventory location</a>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% else %}
|
||||
<div class="inventory-scan-layout" data-inventory-scanner
|
||||
data-run-id="{{ run.api_id }}"
|
||||
data-batch-id="{{ draft_batch.pk }}"
|
||||
data-create-url="{% url 'food:inventory-scan-create' run.api_id %}"
|
||||
data-queue-url="{% url 'food:inventory-scan-queue' run.api_id %}"
|
||||
data-submit-url="{% url 'food:inventory-scan-submit' draft_batch.pk %}"
|
||||
data-zxing-url="{% static 'food/vendor/zxing-browser.min.js' %}">
|
||||
<section class="inventory-scan-camera food-card" aria-label="Barcode scanner">
|
||||
<div class="inventory-camera-label"><span class="inventory-camera-indicator" aria-hidden="true"></span><strong>Camera scanner</strong><span>Camera stays on while you confirm packages</span></div>
|
||||
<div class="food-camera-frame"><video data-scanner-video autoplay muted playsinline aria-label="Camera preview"></video><div class="food-scan-guide" aria-hidden="true"></div></div>
|
||||
<p data-scanner-status role="status" aria-live="polite">Camera is off. Start the camera or enter a barcode.</p>
|
||||
<div class="food-actions"><button class="button" type="button" data-scanner-start>Start camera</button><button class="button button--secondary" type="button" data-scanner-stop hidden>Pause camera</button></div>
|
||||
<form class="food-barcode-form inventory-scan-manual" data-scanner-form>
|
||||
<label for="inventory-scanner-barcode">Enter barcode manually</label><div><input id="inventory-scanner-barcode" data-scanner-barcode name="barcode" inputmode="numeric" pattern="[0-9]{6,64}" autocomplete="off" required><button class="button button--secondary" type="submit">Add barcode</button></div>
|
||||
</form>
|
||||
<p class="food-attribution">Product data from <a href="https://world.openfoodfacts.org/" rel="noopener noreferrer">Open Food Facts</a>.</p>
|
||||
</section>
|
||||
<section class="inventory-scan-right">
|
||||
<div class="inventory-scan-active-wrap" data-scan-active-wrap>
|
||||
{% if active_item %}{% include 'food/partials/inventory_scan_active.html' with item=active_item locations=locations %}{% else %}
|
||||
<article class="food-card inventory-scan-active inventory-scan-skeleton" data-scan-active hidden aria-live="polite"><p>Scan a product to begin.</p></article>
|
||||
{% endif %}
|
||||
</div>
|
||||
<section class="food-card inventory-scan-queue" aria-labelledby="inventory-scan-queue-title">
|
||||
<div class="inventory-scan-queue-heading"><div><p class="inventory-kicker">Current session</p><h2 id="inventory-scan-queue-title">Scan queue</h2></div><span data-scan-queue-count>{{ queued_count }} queued item{{ queued_count|pluralize }}</span></div>
|
||||
<div id="inventory-scan-queue" data-scan-queue aria-live="polite" data-queue-url="{% url 'food:inventory-scan-queue' run.api_id %}">
|
||||
{% include 'food/partials/inventory_scan_queue.html' with run=run batches=queue_batches %}
|
||||
</div>
|
||||
</section>
|
||||
<section class="food-card inventory-scan-controls">
|
||||
<p>The camera remains active as items move into the queue. Use the package controls to correct repeated scans or undo a count.</p>
|
||||
<form data-scan-submit action="{% url 'food:inventory-scan-submit' draft_batch.pk %}">
|
||||
{% csrf_token %}<label for="scan-next-location">Save this batch and scan next location</label>
|
||||
<div class="inventory-scan-next-row"><select id="scan-next-location" name="next_location_id" aria-label="Next inventory location">{% for location in locations %}<option value="{{ location.pk }}" {% if location.pk == draft_batch.location_id %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select><button class="button button--secondary" type="button" data-scan-next disabled>Save & next location</button></div>
|
||||
<button class="button inventory-scan-done" type="button" data-scan-done disabled>Done · process confirmed items</button>
|
||||
</form>
|
||||
<p class="inventory-scan-note">Processing runs in the background. Items without a confirmed product or valid package setup appear in Needs Review.</p>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
{% endif %}
|
||||
</main>
|
||||
<script src="{% static 'food/scanner.js' %}?v=20261026-bulk-2" defer></script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,36 @@
|
||||
<article class="food-card inventory-scan-active" data-scan-active data-item-id="{{ item.pk }}">
|
||||
<div class="inventory-scan-active-heading"><span class="inventory-scan-status-dot" aria-hidden="true"></span><p>Barcode detected · <strong>{{ item.barcode }}</strong></p></div>
|
||||
<form data-scan-confirm action="{% url 'food:inventory-scan-confirm' item.pk %}">
|
||||
{% csrf_token %}
|
||||
<div class="inventory-scan-product-title"><label for="scan-product-name-{{ item.pk }}">Product name</label><input id="scan-product-name-{{ item.pk }}" name="product_name" maxlength="255" value="{{ item.product_name }}" placeholder="Product name" required></div>
|
||||
<label>Brand <input name="brand" maxlength="255" value="{{ item.brand }}" placeholder="Optional"></label>
|
||||
<div class="inventory-scan-fields inventory-scan-fields--package">
|
||||
<label>Packages <input type="number" name="package_count" min="1" max="10000" step="1" value="{{ item.package_count }}" required></label>
|
||||
<label>Amount per package <input type="number" name="package_amount" min="0.001" step="0.001" value="{{ item.package_amount|default_if_none:'' }}" placeholder="Unknown"></label>
|
||||
<label>Package unit <select name="package_unit"><option value="">Count only / unknown size</option><option value="mg" {% if item.package_unit == 'mg' %}selected{% endif %}>mg</option><option value="g" {% if item.package_unit == 'g' %}selected{% endif %}>g</option><option value="kg" {% if item.package_unit == 'kg' %}selected{% endif %}>kg</option><option value="ml" {% if item.package_unit == 'ml' %}selected{% endif %}>ml</option><option value="L" {% if item.package_unit == 'L' %}selected{% endif %}>L</option><option value="pieces" {% if item.package_unit == 'pieces' %}selected{% endif %}>pieces</option><option value="packs" {% if item.package_unit == 'packs' %}selected{% endif %}>packs</option><option value="portions" {% if item.package_unit == 'portions' %}selected{% endif %}>portions</option></select></label>
|
||||
</div>
|
||||
<p class="inventory-scan-total">Total: <strong data-scan-total>{{ item.package_count }} × {{ item.package_amount|default:'unknown' }} {{ item.package_unit }}</strong></p>
|
||||
<details class="inventory-scan-more"><summary>Piece and inner pack details</summary>
|
||||
<div class="inventory-scan-fields">
|
||||
<label>Pieces in package <input type="number" name="pieces_per_package" min="1" step="1" value="{{ item.pieces_per_package|default_if_none:'' }}"></label>
|
||||
<label>Measured amount per piece <input type="number" name="piece_amount" min="0.001" step="0.001" value="{{ item.piece_amount|default_if_none:'' }}"></label>
|
||||
<label>Inner packs <input type="number" name="inner_packs_per_package" min="1" step="1" value="{{ item.inner_packs_per_package|default_if_none:'' }}"></label>
|
||||
<label>Pieces per inner pack <input type="number" name="pieces_per_inner_pack" min="1" step="1" value="{{ item.pieces_per_inner_pack|default_if_none:'' }}"></label>
|
||||
<label>Measured amount per inner pack <input type="number" name="inner_pack_amount" min="0.001" step="0.001" value="{{ item.inner_pack_amount|default_if_none:'' }}"></label>
|
||||
<label>Inner pack label <input name="inner_pack_label" maxlength="40" value="{{ item.inner_pack_label }}" placeholder="wrapper"></label>
|
||||
<label>Piece label <input name="piece_label" maxlength="40" value="{{ item.piece_label }}" placeholder="biscuit"></label>
|
||||
</div>
|
||||
</details>
|
||||
<div class="inventory-scan-fields">
|
||||
<label>Storage location <select name="location_id" required>{% for location in locations %}<option value="{{ location.pk }}" {% if item.location_id == location.pk %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label>
|
||||
<label>Category <input name="category_name" maxlength="100" value="{{ item.category_name }}" placeholder="Optional"></label>
|
||||
<label>Best before <input type="date" name="best_before" value="{{ item.best_before|date:'Y-m-d' }}"></label>
|
||||
<label class="inventory-scan-checkbox"><input type="checkbox" name="opened" value="true" {% if item.opened %}checked{% endif %}> Already opened</label>
|
||||
</div>
|
||||
<label>Notes <textarea name="notes" rows="2" maxlength="4000" placeholder="Optional">{{ item.notes }}</textarea></label>
|
||||
{% if item.source_data.nutrition %}<details class="inventory-scan-nutrition"><summary>Open Food Facts nutrition · unknown values stay blank</summary><dl>{% for name,value in item.source_data.nutrition.items %}<div><dt>{{ name|cut:'_100'|title }}</dt><dd>{% if value is None %}Unknown{% else %}{{ value }}{% endif %}</dd></div>{% endfor %}</dl></details>{% else %}<p class="inventory-scan-meta">Nutrition will be fetched in the background. Missing values remain unknown.</p>{% endif %}
|
||||
<div class="inventory-scan-card-actions"><button class="button" type="submit">Confirm & keep scanning</button><button class="button button--secondary" type="button" data-scan-discard>Remove this scan</button></div>
|
||||
<p class="inventory-scan-hint">You can also swipe this card left to confirm. Keyboard users can submit with Enter.</p>
|
||||
<p class="inventory-scan-error" data-scan-item-error role="alert" hidden></p>
|
||||
</form>
|
||||
</article>
|
||||
@@ -0,0 +1,23 @@
|
||||
<div class="inventory-scan-batches" data-scan-queue-content>
|
||||
{% for batch in batches %}
|
||||
<section class="inventory-scan-batch" data-batch-id="{{ batch.pk }}" data-batch-status="{{ batch.status }}">
|
||||
<div class="inventory-scan-batch-heading"><h3>{{ batch.location.name }}</h3><span>{{ batch.get_status_display }}</span></div>
|
||||
{% for item in batch.queue_items %}
|
||||
<article class="inventory-scan-queue-item" data-queue-item data-queue-status="{{ item.status }}" data-item-id="{{ item.pk }}" data-barcode="{{ item.barcode }}">
|
||||
<div class="inventory-scan-queue-item-main"><span class="inventory-scan-queue-state inventory-scan-queue-state--{{ item.status }}" aria-hidden="true"></span><div><strong>{{ item.product_name|default:'Product details needed' }}</strong><small>{{ item.barcode }} · {{ item.get_status_display }}{% if item.last_error %} · {{ item.last_error }}{% endif %}</small></div></div>
|
||||
<div class="inventory-scan-queue-item-side">
|
||||
<span>{{ item.package_count }} package{{ item.package_count|pluralize }}</span>
|
||||
{% if item.package_amount %}<small>{{ item.package_amount }} {{ item.package_unit }}</small>{% endif %}
|
||||
{% if batch.status == 'draft' and item.status == 'confirmed' %}
|
||||
<div class="inventory-scan-count-controls" aria-label="Adjust {{ item.product_name }} package count">
|
||||
<button type="button" data-scan-count="-1" aria-label="Remove one package">−</button>
|
||||
<span>{{ item.package_count }}</span>
|
||||
<button type="button" data-scan-count="1" aria-label="Add one package">+</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</article>
|
||||
{% empty %}<p class="inventory-scan-empty">No confirmed items in this location batch yet.</p>{% endfor %}
|
||||
</section>
|
||||
{% empty %}<p class="inventory-scan-empty">Your saved batches will appear here.</p>{% endfor %}
|
||||
</div>
|
||||
@@ -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)
|
||||
|
||||
+9
-1
@@ -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/<int:pk>/preview/', inventory.preview_consumption, name='inventory-preview'),
|
||||
path('inventory/product/<int:pk>/use/', inventory.use_amount, name='inventory-use'),
|
||||
path('inventory/consumption/<uuid:identifier>/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/<uuid:run_id>/items/', scan_views.create_scan, name='inventory-scan-create'),
|
||||
path('inventory/scan/<uuid:run_id>/queue/', scan_views.scan_queue, name='inventory-scan-queue'),
|
||||
path('inventory/scan/items/<int:item_id>/confirm/', scan_views.confirm_scan, name='inventory-scan-confirm'),
|
||||
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/batches/<int:batch_id>/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'),
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user