Add inventory scan staging and review workflows

This commit is contained in:
Joren de Graaf
2026-10-26 01:45:26 +01:00
parent d305a99b1b
commit 9c8162bf7e
12 changed files with 407 additions and 23 deletions
+119 -9
View File
@@ -64,6 +64,13 @@ def create_active_scan(run, user, barcode):
raise ScanWorkflowError('Choose a location before scanning.')
if batch.items.filter(status=InventoryScanItem.Status.ACTIVE).exists():
raise ScanWorkflowError('Confirm or remove the active scan before scanning another item.')
repeated = batch.items.select_for_update().filter(
barcode=barcode, status=InventoryScanItem.Status.CONFIRMED).order_by('-confirmed_at', '-pk').first()
if repeated:
repeated.package_count += 1
repeated.user_data = _item_data(repeated)
repeated.save(update_fields=('package_count', 'user_data'))
return repeated
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
values = {}
if product:
@@ -397,8 +404,7 @@ def _send_completion_notification(run_id):
tallies = dict(run.batches.values('items__status').annotate(total=Count('items')).values_list('items__status', 'total'))
succeeded = tallies.get(InventoryScanItem.Status.COMPLETE, 0)
review = sum(tallies.get(status, 0) for status in (InventoryScanItem.Status.NEEDS_REVIEW,
InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED))
InventoryScanItem.Status.DEFERRED))
failed = tallies.get(InventoryScanItem.Status.FAILED, 0)
run.notification_attempted_at = now # durable at-most-once delivery guard for worker restarts
run.save(update_fields=('notification_attempted_at',))
@@ -425,7 +431,8 @@ def approve_scan_item(user, item_id, values):
with transaction.atomic():
item = (InventoryScanItem.objects.select_for_update().select_related('batch__run__user')
.filter(pk=item_id, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED)).first())
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED)).first())
if not item:
raise ScanWorkflowError('This staged item is no longer awaiting review.')
if values.get('product_name'):
@@ -437,12 +444,16 @@ def approve_scan_item(user, item_id, values):
if values.get('notes') is not None:
item.notes = str(values['notes']).strip()[:4000]
if values.get('location_id'):
item.location = InventoryLocation.objects.get(user=user, pk=values['location_id'])
location = InventoryLocation.objects.filter(user=user, pk=values['location_id']).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
item.location = location
item.package_count = _integer(values.get('package_count', item.package_count), 'Enter a valid number of packages.', 1, 10000)
if 'package_amount' in values:
item.package_amount = _decimal_or_none(values['package_amount'], 'Enter a valid package size.')
if 'package_unit' in values:
item.package_unit = str(values['package_unit']).strip()[:8]
_apply_nutrition_values(item, values)
if not item.product_name:
raise ScanWorkflowError('Enter a product name before approving.')
product = item.product or FoodProduct.objects.filter(owner=user, barcode=item.barcode).first()
@@ -459,6 +470,7 @@ def approve_scan_item(user, item_id, values):
else:
_apply_scan_product_corrections(product, item)
_populate_from_product(item, product)
_apply_nutrition_values(item, values, product=product)
item.product = product
if not _valid_stock_input(item):
raise ScanWorkflowError('Add valid package details or choose count-only stock before approving.')
@@ -472,18 +484,116 @@ def approve_scan_item(user, item_id, values):
return item
def save_review_item(user, item_id, values):
"""Persist edits on a staged row so switching review modes cannot lose them."""
with transaction.atomic():
item = (InventoryScanItem.objects.select_for_update().filter(
pk=item_id, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED)).first())
if not item:
raise ScanWorkflowError('This staged item is no longer awaiting review.')
if values.get('product_name') is not None:
item.product_name = str(values['product_name']).strip()[:255]
if values.get('brand') is not None:
item.brand = str(values['brand']).strip()[:255]
if values.get('category_name') is not None:
item.category_name = str(values['category_name']).strip()[:100]
if values.get('notes') is not None:
item.notes = str(values['notes']).strip()[:4000]
if values.get('location_id'):
location = InventoryLocation.objects.filter(user=user, pk=values['location_id']).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
item.location = location
item.package_count = _integer(values.get('package_count', item.package_count), 'Enter a valid number of packages.', 1, 10000)
if 'package_amount' in values:
item.package_amount = _decimal_or_none(values['package_amount'], 'Enter a valid package size.')
if 'package_unit' in values:
item.package_unit = str(values['package_unit']).strip()[:8]
_apply_nutrition_values(item, values)
item.user_data = _item_data(item)
item.save()
return item
def approve_scan_items(user, item_ids, values):
"""Approve a selected group atomically after a preview has been shown."""
ids = list(dict.fromkeys(int(value) for value in item_ids))
if not ids:
raise ScanWorkflowError('Select at least one product to approve.')
with transaction.atomic():
items = list(InventoryScanItem.objects.select_for_update().filter(
pk__in=ids, batch__run__user=user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED)))
if len(items) != len(ids):
raise ScanWorkflowError('One or more selected products are no longer awaiting review. Reload and try again.')
approved = []
for item in items:
shared = dict(values)
shared.setdefault('product_name', item.product_name)
shared.setdefault('brand', item.brand)
shared.setdefault('package_count', item.package_count)
shared.setdefault('package_amount', str(item.package_amount) if item.package_amount is not None else '')
shared.setdefault('package_unit', item.package_unit)
approved.append(approve_scan_item(user, item.pk, shared))
for run_id in set(item.batch.run_id for item in approved):
_refresh_completion(run_id)
return approved
def _apply_nutrition_values(item, values, product=None):
fields = {'energy_kcal_100': 'energy_kcal_100', 'fat_100': 'fat_100',
'saturated_fat_100': 'saturated_fat_100', 'carbohydrates_100': 'carbohydrates_100',
'sugars_100': 'sugars_100', 'protein_100': 'protein_100',
'salt_100': 'salt_100', 'fibre_100': 'fibre_100'}
if not any(key in values for key in fields):
return
product = product or item.product or FoodProduct.objects.filter(owner=item.batch.run.user, barcode=item.barcode).first()
nutrition = {}
for key, field in fields.items():
if key not in values:
continue
value = values[key]
parsed = _decimal_nonnegative_or_none(value, f'Enter a valid {key.replace("_100", "").replace("_", " ")} value.')
nutrition[key] = str(parsed) if parsed is not None else None
source_data = item.source_data if isinstance(item.source_data, dict) else {}
item.source_data = {**source_data,
'nutrition': {**source_data.get('nutrition', {}), **nutrition}}
if product:
for key, value in nutrition.items():
setattr(product, key, Decimal(value) if value is not None else None)
raw_data = product.raw_data if isinstance(product.raw_data, dict) else {}
product.raw_data = {**raw_data, 'manual_nutrition_override': True}
product.save(update_fields=(*nutrition.keys(), 'raw_data', 'updated_at'))
source_nutrition = item.source_data.get('nutrition', {}) if isinstance(item.source_data, dict) else {}
item.source_data = {**(item.source_data if isinstance(item.source_data, dict) else {}),
'nutrition': {**source_nutrition, **nutrition}}
def _decimal_nonnegative_or_none(value, message):
if value in (None, ''):
return None
try:
result = Decimal(str(value))
except (InvalidOperation, TypeError, ValueError):
raise ScanWorkflowError(message) from None
if not result.is_finite() or result < 0 or result > Decimal('9999999.999'):
raise ScanWorkflowError(message)
return result.quantize(Decimal('.001'))
def defer_scan_item(user, item_id):
updated = InventoryScanItem.objects.filter(pk=item_id, batch__run__user=user,
status=InventoryScanItem.Status.NEEDS_REVIEW).update(status=InventoryScanItem.Status.DEFERRED)
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.FAILED,
InventoryScanItem.Status.DEFERRED)).update(
status=InventoryScanItem.Status.DEFERRED)
if not updated:
raise ScanWorkflowError('This item can no longer be deferred.')
def _apply_scan_product_corrections(product, item):
# Metadata corrections are limited to product identity and packaging. Nutrition remains source-owned.
if (product.source == FoodProduct.Source.OPEN_FOOD_FACTS and isinstance(product.raw_data, dict) and
product.raw_data.get('manual_nutrition_override')):
return
# This path updates identity and package metadata only; nutrition overrides remain untouched.
product.product_name = item.product_name or product.product_name
product.brand = item.brand or product.brand
product.package_amount = item.package_amount or product.package_amount
+6 -2
View File
@@ -183,8 +183,12 @@ def cached_product(user, barcode, *, refresh=False, wait_for_slot=False, on_requ
return product
_rate_limit(user.pk, 'product', 10)
try:
data = OpenFoodFactsClient().get_product(barcode, wait_for_slot=wait_for_slot,
on_request_start=on_request_start)
client = OpenFoodFactsClient()
if wait_for_slot or on_request_start:
data = client.get_product(barcode, wait_for_slot=wait_for_slot,
on_request_start=on_request_start)
else:
data = client.get_product(barcode)
except OpenFoodFactsError:
if product:
return product