diff --git a/main/food/scan_views.py b/main/food/scan_views.py index 891c340..1776b1e 100644 --- a/main/food/scan_views.py +++ b/main/food/scan_views.py @@ -11,7 +11,7 @@ from django.views.decorators.http import require_GET, require_http_methods, requ from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem, InventoryReviewPreference, InventoryScanRun) from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count, - approve_scan_item, approve_scan_items, confirm_scan_item, create_active_scan, + approve_scan_item, approve_scan_items, change_draft_batch_location, confirm_scan_item, create_active_scan, defer_scan_item, discard_active_scan, get_or_create_active_run, resume_active_run, save_review_item, submit_batch, update_review_preference) @@ -118,7 +118,23 @@ def submit_scan_batch(request, batch_id): 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])}) + 'submit_url': reverse('food:inventory-scan-submit', args=[next_batch.pk]), + 'location_url': reverse('food:inventory-scan-location', args=[next_batch.pk])}) + + +@login_required +@require_POST +def change_scan_location(request, batch_id): + payload, error = _payload(request) + if error: + return JsonResponse({'error': error}, status=400) + try: + batch = change_draft_batch_location(request.user, batch_id=batch_id, + location_id=payload.get('location_id')) + except (ScanWorkflowError, TypeError, ValueError) as error: + return JsonResponse({'error': str(error)}, status=400) + return JsonResponse({'ok': True, 'location_id': batch.location_id, + 'location': batch.location.name}) @login_required diff --git a/main/food/services/inventory_scanner.py b/main/food/services/inventory_scanner.py index 69dc01f..2a881a0 100644 --- a/main/food/services/inventory_scanner.py +++ b/main/food/services/inventory_scanner.py @@ -51,6 +51,33 @@ def resume_active_run(user): .prefetch_related('batches__items').order_by('-created_at').first()) +def change_draft_batch_location(user, *, batch_id, location_id): + """Change the location for a live draft batch and all of its unsubmitted scans.""" + with transaction.atomic(): + batch = (InventoryScanBatch.objects.select_for_update().select_related('run') + .filter(pk=batch_id, run__user=user).first()) + if not batch or batch.status != InventoryScanBatch.Status.DRAFT: + raise ScanWorkflowError('Only the current unsaved batch can change location.') + run = InventoryScanRun.objects.select_for_update().get(pk=batch.run_id) + if run.status != InventoryScanRun.Status.ACTIVE: + raise ScanWorkflowError('This scan session is no longer active.') + location = InventoryLocation.objects.filter(user=user, pk=location_id).first() + if not location: + raise ScanWorkflowError('Choose one of your existing inventory locations.') + + batch.location = location + batch.save(update_fields=('location',)) + run.selected_location = location + run.save(update_fields=('selected_location',)) + items = batch.items.select_for_update().filter( + status__in=(InventoryScanItem.Status.ACTIVE, InventoryScanItem.Status.CONFIRMED)) + for item in items: + item.location = location + item.user_data = _item_data(item) + item.save(update_fields=('location', 'user_data')) + return batch + + def create_active_scan(run, user, barcode): if not barcode.isascii() or not barcode.isdigit() or not 6 <= len(barcode) <= 64: raise ScanWorkflowError('Enter a valid numeric barcode.') diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css index a3cfda6..0583551 100644 --- a/main/food/static/food/food.css +++ b/main/food/static/food/food.css @@ -97,6 +97,15 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .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-location-panel{display:grid;grid-template-columns:minmax(170px,.7fr) minmax(0,1.3fr);align-items:center;gap:1rem;margin:0 0 1rem;padding:1rem 1.1rem;background:#f5f8f4;border:1px solid #d8e1d8;border-radius:14px} +.inventory-scan-location-summary{display:grid;justify-items:start;gap:.35rem} +.inventory-scan-location-summary .inventory-kicker{margin:0} +.inventory-scan-location-form{display:grid;gap:.4rem} +.inventory-scan-location-form>label{font-weight:700} +.inventory-scan-location-actions{display:flex;gap:.55rem;align-items:center} +.inventory-scan-location-form select{flex:1;min-width:0;min-height:46px;padding:.6rem .7rem;border:1px solid #b9c9bd;border-radius:10px;background:#fff;color:#19242b;font:inherit} +.inventory-scan-location-form>p{margin:0;color:#63776c;font-size:.85rem} +.inventory-scan-location-form [data-scan-location-error]:not([hidden]){color:#9b342d;font-weight:650} .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} @@ -173,8 +182,8 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317} .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(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}.inventory-scan-location-panel{grid-template-columns:1fr;align-items: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-location-actions{align-items:stretch;flex-direction:column}.inventory-scan-location-actions .button{width:100%}.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}} .inventory-staging,.inventory-review-page .food-card{border:1px solid #d8e1d8;border-radius:14px;background:#fff;padding:1rem}.inventory-staging{display:grid;gap:1rem;margin:1rem 0;background:#f5f8f4}.inventory-staging-top{display:flex;align-items:center;justify-content:space-between;gap:1rem}.inventory-staging-top h2,.inventory-review-page h2{margin:.1rem 0;color:#183c2c}.inventory-staging-top p:last-child{margin:.35rem 0;color:#63776c}.inventory-kicker{margin:0;color:#247452;font-size:.75rem;font-weight:750;letter-spacing:.04em;text-transform:uppercase}.inventory-staging-counts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem}.inventory-staging-counts>a{display:flex;align-items:center;gap:.75rem;min-height:62px;padding:.6rem .8rem;border:1px solid #d8e1d8;border-radius:10px;background:white;color:#273d33;text-decoration:none}.inventory-staging-counts strong{font-size:1.45rem;color:#183c2c}.inventory-review-mode,.inventory-review-toolbar form{display:flex;align-items:center;gap:.45rem;flex-wrap:wrap}.inventory-review-mode>span,.inventory-review-toolbar>span{margin-right:.4rem;font-weight:700}.inventory-review-mode button,.inventory-review-toolbar button{min-height:42px;padding:.5rem .8rem;border:1px solid #c8d4ca;border-radius:9px;background:white;color:#183c2c;font:inherit;cursor:pointer}.inventory-review-mode button.is-selected,.inventory-review-toolbar button.is-selected{background:#e9f3ec;border-color:#247452;color:#183c2c;font-weight:700}.inventory-review-page{max-width:920px;padding-top:1.25rem}.inventory-review-page>.food-heading{margin-bottom:1rem}.inventory-review-page .food-heading h1{margin:.35rem 0;color:#183c2c}.inventory-review-page .food-heading p:last-child{color:#63776c}.inventory-review-toolbar{display:flex;justify-content:space-between;align-items:center;gap:.8rem;margin:.75rem 0}.inventory-review-list{display:grid;gap:.7rem}.inventory-review-row{display:flex;align-items:center;justify-content:space-between;gap:1rem}.inventory-review-row h2{margin:.15rem 0;font-size:1.05rem}.inventory-review-row p{margin:.25rem 0;color:#63776c}.inventory-review-row .button,.inventory-bulk-review button{min-height:44px}.inventory-review-error{color:#9b342d;font-weight:650}.inventory-review-success{color:#247452;font-weight:700}.inventory-bulk-review{display:grid;gap:.8rem;margin-top:.8rem}.inventory-bulk-review>p{margin:0;color:#63776c}.inventory-bulk-selection{display:grid;gap:.35rem;margin:0;padding:.5rem;border:1px solid #d8e1d8;border-radius:10px}.inventory-bulk-selection legend{font-weight:700}.inventory-bulk-selection label{display:flex;align-items:center;gap:.65rem;min-height:52px;padding:.4rem;border-bottom:1px solid #edf0ed}.inventory-bulk-selection input{width:20px;height:20px;flex:none}.inventory-bulk-selection label span{display:grid;gap:.2rem;min-width:0}.inventory-bulk-selection small,.inventory-review-preview span{color:#63776c}.inventory-review-shared-fields,.inventory-review-fields,.inventory-review-nutrients{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.7rem}.inventory-review-shared-fields label,.inventory-review-fields label,.inventory-review-nutrients label{display:grid;gap:.3rem;font-weight:650}.inventory-review-fields textarea{min-height:80px}.inventory-review-fields input,.inventory-review-fields select,.inventory-review-fields textarea,.inventory-review-shared-fields input,.inventory-review-shared-fields select,.inventory-review-nutrients input{width:100%;min-width:0;min-height:44px;padding:.6rem .7rem;border:1px solid #c8d4ca;border-radius:9px;background:white;color:#19242b;font:inherit;font-weight:400;box-sizing:border-box}.inventory-review-form{display:grid;gap:1rem}.inventory-review-form .inventory-scan-nutrition p{color:#63776c}.inventory-review-actions{display:flex;align-items:center;gap:.5rem;flex-wrap:wrap}.inventory-review-actions .button{min-height:44px}.inventory-review-preview{padding:.65rem;border-bottom:1px solid #edf0ed}.inventory-review-preview>div{display:grid;gap:.2rem}.inventory-review-preview>span{text-align:right}.inventory-review-page :focus-visible,.inventory-staging :focus-visible{outline:3px solid #f2ad49;outline-offset:2px}@media(max-width:600px){.inventory-staging-top,.inventory-review-row,.inventory-review-toolbar{align-items:flex-start;flex-direction:column}.inventory-review-shared-fields,.inventory-review-fields,.inventory-review-nutrients{grid-template-columns:1fr}.inventory-review-preview{align-items:flex-start;flex-direction:column}.inventory-review-preview>span{text-align:left}.inventory-review-actions{display:grid}.inventory-review-actions .button{width:100%}} .food-quantity-form{display:flex;align-items:center;gap:.35rem}.food-quantity{font-weight:700;white-space:nowrap}.food-quantity-form button{min-width:44px;min-height:44px;border:1px solid var(--food-border);border-radius:50%;background:var(--food-surface);color:var(--food-ink);font:inherit;font-size:1.4rem;cursor:pointer}.food-quantity-form button:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}.food-quantity-form.htmx-request button{opacity:.6;cursor:progress}.food-screen-reader{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} diff --git a/main/food/static/food/scanner.js b/main/food/static/food/scanner.js index 2b1a684..b902078 100644 --- a/main/food/static/food/scanner.js +++ b/main/food/static/food/scanner.js @@ -437,7 +437,11 @@ 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}`; + root.dataset.currentLocationId = String(data.location_id); + root.dataset.locationUrl = data.location_url; + locationForm.action = data.location_url; + locationForm.querySelector('[name="location_id"]').value = String(data.location_id); + document.querySelector('[data-scan-current-location]').textContent = 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); } @@ -450,6 +454,33 @@ location.assign(data.redirect); } catch (error) { say(error.message); } }); + const locationForm = document.querySelector('[data-scan-location-change]'); + locationForm.addEventListener('submit', async (event) => { + event.preventDefault(); + const button = locationForm.querySelector('[type="submit"]'); + const errorNode = locationForm.querySelector('[data-scan-location-error]'); + const currentSelect = locationForm.querySelector('[name="location_id"]'); + const nextLocation = submitForm.querySelector('[name="next_location_id"]'); + const previousLocationId = root.dataset.currentLocationId; + button.disabled = true; + errorNode.hidden = true; + try { + const data = await request(root.dataset.locationUrl, new FormData(locationForm)); + currentSelect.value = String(data.location_id); + root.dataset.currentLocationId = String(data.location_id); + document.querySelector('[data-scan-current-location]').textContent = data.location; + const activeLocation = activeWrap.querySelector('[data-scan-confirm] [name="location_id"]'); + if (activeLocation) activeLocation.value = String(data.location_id); + if (nextLocation.value === previousLocationId) nextLocation.value = String(data.location_id); + await refreshQueue(); + say(`Current batch and its unsubmitted scans are now assigned to ${data.location}. The camera is ${stream ? 'still active.' : 'off.'}`); + } catch (error) { + errorNode.textContent = error.message; + errorNode.hidden = false; + } finally { + button.disabled = false; + } + }); const leaveLink = document.querySelector('.inventory-scan-page .food-heading a[href]'); leaveLink?.addEventListener('click', (event) => { if (root.dataset.hasPending === 'true' && diff --git a/main/food/templates/food/inventory_scanner.html b/main/food/templates/food/inventory_scanner.html index 1bde085..fc613cf 100644 --- a/main/food/templates/food/inventory_scanner.html +++ b/main/food/templates/food/inventory_scanner.html @@ -1,21 +1,44 @@ {% 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 run %} +
+
+

Current batch location

+ {{ draft_batch.location.name }} +
+
+ {% csrf_token %} + +
+ + +
+

Moves every scan in this unsaved batch. Previously saved batches stay in their locations. Use Save & next location to keep batches in different places.

+ +
+
+ {% endif %} {% if not run %}

Choose a starting location

-

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

+

Choose where these packages will be stored before starting. Your session is saved as you scan, so you can return to it after navigating away.

{% if start_error %}{% endif %} {% if locations %}
- {% csrf_token %} - + {% csrf_token %} +
{% else %} @@ -26,6 +49,8 @@
{% endif %}
- + {% endblock %} diff --git a/main/food/test_inventory_scanner.py b/main/food/test_inventory_scanner.py index 205edab..dc964f7 100644 --- a/main/food/test_inventory_scanner.py +++ b/main/food/test_inventory_scanner.py @@ -11,7 +11,8 @@ from food.models import (FoodProduct, InventoryLocation, InventoryScanBatch, InventoryReviewPreference, InventoryScanItem, InventoryScanRun, KitchenInventoryItem, OpenFoodFactsRequest) from food.services.inventory_scanner import (ScanWorkflowError, - adjust_confirmed_count, approve_scan_item, approve_scan_items, confirm_scan_item, create_active_scan, get_or_create_active_run, + adjust_confirmed_count, approve_scan_item, approve_scan_items, change_draft_batch_location, + confirm_scan_item, create_active_scan, get_or_create_active_run, dispatch_pending_scan_notifications, process_next_scan_item, save_review_item, submit_batch, update_review_preference) from food.services.off_rate_limit import OpenFoodFactsRateLimited, off_http_request @@ -49,6 +50,33 @@ class InventoryScanQueueTests(TestCase): item.refresh_from_db() self.assertEqual(item.status, InventoryScanItem.Status.QUEUED) + def test_current_batch_location_change_moves_unsaved_items_but_not_saved_batches(self): + run, saved_item = self._confirmed_item() + current_run = submit_batch(self.user, batch_id=saved_item.batch_id, + next_location_id=self.shelf.pk) + current_batch = current_run.batches.get(status=InventoryScanBatch.Status.DRAFT) + pantry = InventoryLocation.objects.create(user=self.user, name='Pantry') + active_item = create_active_scan(current_run, self.user, '87654321') + confirm_scan_item(self.user, active_item.pk, { + 'location_id': self.shelf.pk, 'product_name': 'Rice', + }) + + changed = change_draft_batch_location( + self.user, batch_id=current_batch.pk, location_id=pantry.pk) + + saved_item.refresh_from_db() + active_item.refresh_from_db() + current_batch.refresh_from_db() + current_run.refresh_from_db() + self.assertEqual((saved_item.location, saved_item.batch.location), (self.fridge, self.fridge)) + self.assertEqual((changed.location, current_batch.location), (pantry, pantry)) + self.assertEqual(active_item.location, pantry) + self.assertEqual(active_item.user_data['location_id'], pantry.pk) + self.assertEqual(current_run.selected_location, pantry) + with self.assertRaises(ScanWorkflowError): + change_draft_batch_location(self.user, batch_id=saved_item.batch_id, + location_id=pantry.pk) + def test_batch_rejects_other_users_location(self): run, item = self._confirmed_item() foreign = InventoryLocation.objects.create(user=self.other, name='Other') @@ -237,6 +265,7 @@ class InventoryScanWorkflowViewTests(TestCase): 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') + self.assertContains(response, '', html=True) 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) @@ -245,6 +274,28 @@ class InventoryScanWorkflowViewTests(TestCase): self.assertContains(response, 'Fridge') self.assertContains(response, str(run.api_id)) + def test_running_session_location_can_be_changed_and_start_requires_explicit_choice(self): + response = self.client.post(reverse('food:inventory-scan-start'), {}) + self.assertEqual(response.status_code, 400) + self.assertContains(response, 'Choose one of your existing inventory locations.', status_code=400) + self.assertFalse(InventoryScanRun.objects.filter(user=self.user).exists()) + + run = get_or_create_active_run(self.user, self.fridge.pk) + item = create_active_scan(run, self.user, '87654321') + confirm_scan_item(self.user, item.pk, { + 'location_id': self.fridge.pk, 'product_name': 'Rice', + }) + response = self.client.post(reverse('food:inventory-scan-location', args=[item.batch_id]), { + 'location_id': self.pantry.pk, + }) + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json()['location'], 'Pantry') + item.refresh_from_db() + self.assertEqual(item.location, self.pantry) + response = self.client.get(reverse('food:scanner-inventory')) + self.assertContains(response, 'Current batch location') + self.assertContains(response, f'', html=True) + 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]), @@ -263,6 +314,8 @@ class InventoryScanWorkflowViewTests(TestCase): self.assertEqual(response.status_code, 200) self.assertEqual(response.json()['location'], 'Pantry') next_batch = run.batches.get(status=InventoryScanBatch.Status.DRAFT) + self.assertEqual(response.json()['location_url'], + reverse('food:inventory-scan-location', args=[next_batch.pk])) 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() diff --git a/main/food/urls.py b/main/food/urls.py index 18bec08..f4831db 100644 --- a/main/food/urls.py +++ b/main/food/urls.py @@ -22,6 +22,7 @@ urlpatterns = [ 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/batches//location/', scan_views.change_scan_location, name='inventory-scan-location'), 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'),