Compare commits

...
11 Commits
51 changed files with 3467 additions and 185 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

-115
View File
@@ -1,115 +0,0 @@
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
Reading package lists...
Building dependency tree...
Reading state information...
Starting pkgProblemResolver with broken count: 0
Starting 2 pkgProblemResolver with broken count: 0
Done
The following packages will be REMOVED:
anthy anthy-common anthy-unicode-common docker-neon fonts-liberation2
gimp-data graphviz hunspell-fr kasumi kinit libamd3 libann0
libanthy-unicode-0t64 libanthy1t64 libanthyinput0t64 libbabl-0.1-0 libcamd3
libccolamd3 libcdt5 libcgraph6 libchewing3 libchewing3-data libcholmod5
libcolamd3 libddcutil4 libfwupd2 libgegl-0.4-0t64 libgegl-common libgexiv2-2
libgimp2.0t64 libgts-0.7-5t64 libgts-bin libgvc6 libgvpr2 liblab-gamut1
libmaliit-plugins2 libmbim-proxy libmypaint-1.5-1 libmypaint-common
libpathplan4 libpinyin-data libpinyin15 libprotobuf-c1 libpyside6-py3-6.10
libqmi-proxy libqt5feedback5 libqt5glib-2.0-0 libqt5gstreamer-1.0-0
libqt5gstreamerquick-1.0-0 libqt5multimedia5 libqt5multimediaquick5
libqt5opengl5t64 libroc0.3 libshiboken6-py3-6.10 libsuitesparseconfig7
libumfpack6 libwireplumber-0.4-0 libwmf-0.2-7 libwmflite-0.2-7
linux-headers-6.17.0-29-generic linux-hwe-6.17-headers-6.17.0-29
linux-hwe-6.17-tools-6.17.0-29 linux-image-6.17.0-29-generic
linux-modules-6.17.0-29-generic linux-modules-extra-6.17.0-29-generic
linux-tools-6.17.0-29-generic maliit-framework maliit-keyboard
plasma-integration5 plasma-workspace-wayland
qml-module-org-kde-qqc2desktopstyle qml-module-org-kde-sonnet
qml-module-org-kde-syntaxhighlighting qml-module-qtfeedback
qml-module-qtgstreamer qml-module-qtmultimedia
qml-module-qtquick-localstorage qt6-virtualkeyboard-plugin
qtgstreamer-plugins-qt5 sddm sddm-theme-breeze sddm-theme-maya
0 upgraded, 0 newly installed, 82 to remove and 383 not upgraded.
Remv anthy [1:0.4-3build1]
Remv libanthyinput0t64 [1:0.4-3build1]
Remv kasumi [2.5+debian1-1build2]
Remv libanthy1t64 [1:0.4-3build1]
Remv anthy-common [1:0.4-3build1]
Remv maliit-keyboard [2.3.1+p24.04+vrelease+git20250831.2310-0]
Remv libanthy-unicode-0t64 [1.0.0.20240502-1+24.04+noble+release+build5]
Remv anthy-unicode-common [1.0.0.20240502-1+24.04+noble+release+build5]
Remv docker-neon [0.0+p24.04+vrelease+git20240819.0606-0]
Remv fonts-liberation2 [1:2.1.5-3]
Remv gimp-data [2.10.36-3ubuntu0.24.04.1]
Remv graphviz [2.42.2-9ubuntu0.1]
Remv hunspell-fr [1:7.0-1]
Remv kinit [5.116.0-1zneon+24.04+noble+release+build3]
Remv libgimp2.0t64 [2.10.36-3ubuntu0.24.04.1]
Remv libgegl-0.4-0t64 [1:0.4.48-2.4build2]
Remv libumfpack6 [1:7.6.1+dfsg-1build1]
Remv libcholmod5 [1:7.6.1+dfsg-1build1]
Remv libamd3 [1:7.6.1+dfsg-1build1]
Remv libann0 [1.1.2+doc-9build1]
Remv libbabl-0.1-0 [1:0.1.108-1]
Remv libcamd3 [1:7.6.1+dfsg-1build1]
Remv libccolamd3 [1:7.6.1+dfsg-1build1]
Remv libgvpr2 [2.42.2-9ubuntu0.1]
Remv libgvc6 [2.42.2-9ubuntu0.1]
Remv libcdt5 [2.42.2-9ubuntu0.1] [libcgraph6:amd64 ]
Remv libcgraph6 [2.42.2-9ubuntu0.1]
Remv libchewing3 [0.6.0-1build1]
Remv libchewing3-data [0.6.0-1build1]
Remv libcolamd3 [1:7.6.1+dfsg-1build1]
Remv libddcutil4 [1.4.1-1build2]
Remv libfwupd2 [1.9.34-0ubuntu1~24.04.1]
Remv libgegl-common [1:0.4.48-2.4build2]
Remv libgexiv2-2 [0.14.2-2build3]
Remv libgts-bin [0.7.6+darcs121130-5.2build1]
Remv libgts-0.7-5t64 [0.7.6+darcs121130-5.2build1]
Remv liblab-gamut1 [2.42.2-9ubuntu0.1]
Remv maliit-framework [2.3.0+p24.04+vrelease+git20250831.2250-0]
Remv libmaliit-plugins2 [2.3.0+p24.04+vrelease+git20250831.2250-0]
Remv libmbim-proxy [1.32.0-1+24.04+noble+release+build1]
Remv libmypaint-1.5-1 [1.6.0-2build2]
Remv libmypaint-common [1.6.0-2build2]
Remv libpathplan4 [2.42.2-9ubuntu0.1]
Remv libpinyin15 [2.8.1-1build3]
Remv libpinyin-data [2.8.1-1build3]
Remv libprotobuf-c1 [1.4.1-1ubuntu4]
Remv libpyside6-py3-6.10 [6.11.1-0zneon+24.04+noble+release+build89]
Remv libqmi-proxy [1.36.0-1+24.04+noble+release+build1]
Remv qml-module-qtfeedback [5.0+p24.04+vrelease+git20250829.0151-0]
Remv libqt5feedback5 [5.0+p24.04+vrelease+git20250829.0151-0]
Remv qml-module-qtgstreamer [1.2.0-5.2build4]
Remv libqt5gstreamerquick-1.0-0 [1.2.0-5.2build4]
Remv libqt5gstreamer-1.0-0 [1.2.0-5.2build4]
Remv libqt5glib-2.0-0 [1.2.0-5.2build4]
Remv qml-module-qtmultimedia [5.15.17+p24.04+vrelease+git20250828.1415-0]
Remv libqt5multimediaquick5 [5.15.17+p24.04+vrelease+git20250828.1415-0]
Remv libqt5multimedia5 [5.15.17+p24.04+vrelease+git20250828.1415-0]
Remv qtgstreamer-plugins-qt5 [1.2.0-5.2build4]
Remv libqt5opengl5t64 [5.15.17+p24.04+vrelease+git20250828.1236-0]
Remv libroc0.3 [0.3.0+dfsg-7ubuntu2]
Remv libshiboken6-py3-6.10 [6.11.1-0zneon+24.04+noble+release+build89]
Remv libsuitesparseconfig7 [1:7.6.1+dfsg-1build1]
Remv libwireplumber-0.4-0 [0.4.17-1ubuntu4.1]
Remv libwmf-0.2-7 [0.2.13-1.1build3]
Remv libwmflite-0.2-7 [0.2.13-1.1build3]
Remv linux-headers-6.17.0-29-generic [6.17.0-29.29~24.04.1]
Remv linux-hwe-6.17-headers-6.17.0-29 [6.17.0-29.29~24.04.1]
Remv linux-tools-6.17.0-29-generic [6.17.0-29.29~24.04.1]
Remv linux-hwe-6.17-tools-6.17.0-29 [6.17.0-29.29~24.04.1]
Remv linux-image-6.17.0-29-generic [6.17.0-29.29~24.04.1]
Remv linux-modules-extra-6.17.0-29-generic [6.17.0-29.29~24.04.1]
Remv linux-modules-6.17.0-29-generic [6.17.0-29.29~24.04.1]
Remv plasma-integration5 [6.7.5-0zneon+24.04+noble+release+build60]
Remv plasma-workspace-wayland [4:6.7.5-0zneon+24.04+noble+release+build95]
Remv qml-module-org-kde-qqc2desktopstyle [5.116.1-0zneon+24.04+noble+release+build4]
Remv qml-module-org-kde-sonnet [5.116.0-1zneon+24.04+noble+release+build2]
Remv qml-module-org-kde-syntaxhighlighting [5.116.0-1zneon+24.04+noble+release+build3]
Remv qml-module-qtquick-localstorage [5.15.17+p24.04+vrelease+git20250828.1340-0]
Remv qt6-virtualkeyboard-plugin [6.11.1-0zneon+24.04+noble+release+build27]
Remv sddm-theme-maya [0.21.0-6+24.04+noble+release+build32]
Remv sddm-theme-breeze [4:6.7.5-0zneon+24.04+noble+release+build95]
Remv sddm [0.21.0-6+24.04+noble+release+build32]
+3 -1
View File
@@ -30,7 +30,7 @@ Collection responses use `count`, `limit`, `offset`, and `results`. The default
JSON decimal values are strings to preserve precision. For food creation, send `meal`, positive decimal `amount`, and `unit` (`g` or `ml`). With `product_id`, nutrition and name snapshots are calculated from that owned product using the same service as the web UI, and the unit must match its basis. Without a product, send `product_name` and optional `brand`, `barcode`, `portion_label`, and nutrition totals (`calories_kcal`, `carbohydrates_g`, `protein_g`, `fat_g`, `fibre_g`, `sugars_g`, `salt_g`). Manual entries are snapshot-only, so repeat estimates do not create duplicate products. `date` defaults to the user's saved local time zone date; an explicit ISO date and optional time can be supplied. API entries have `created_via: api`, separate from their nutrition `source`.
Inventory creation requires an owned product UUID, positive integer `quantity`, and a location name. Optional fields are `category`, `notes`, `opened`, and `best_before`. Location and category names reuse the application's owned lookup records. There is no invented inventory unit: the existing model counts whole items. DELETE removes the item, matching the API operation; the web inventory still has its separate archive behavior.
Inventory creation requires an owned product UUID, positive integer `quantity` (outer package count), and a location name. Optional fields include `category`, `notes`, `opened`, and `best_before`. Flat packages may supply `original_amount` and `unit`, `pieces_per_package`, `remaining_pieces`, and explicit `piece_amount`. For one nested layer, supply `inner_packs_per_package`, `pieces_per_inner_pack`, `inner_pack_label`, `piece_label`, and (for measured stock) `inner_pack_amount`; `original_amount` is derived as inner-pack amount × inner-pack count. Total pieces are derived from the two counts. For example, 6 inner packs × 3 biscuits with 44 g per inner pack creates one 264 g package with 18 pieces. Per-biscuit weight is an estimate derived from the measured inner-pack amount. With no measured amount, nested piece contents use `pieces` as the stock unit. Location and category names reuse the application's owned lookup records. DELETE removes the item, matching the API operation; the web inventory still has its separate archive behavior.
For attachment upload, send multipart `image` and optional `caption`. JPEG, PNG, and WebP are accepted after decoding and format/MIME checks. The file limit is 5 MiB and the pixel limit is 25 million. Images are stored under `main/private_media/`, which has no public media URL; download requires `food:read` and ownership of the parent entry. Filenames on disk are random. The original filename is metadata only.
@@ -42,6 +42,8 @@ Food Diary entries saved in millilitres can count toward hydration automatically
For a packaged inventory item, `PATCH /kitchen/items/{id}/` may set `remaining_amount` to an absolute value from zero through its current remaining amount. A reduction uses the existing inventory consumption service; zero archives that package from active inventory. `opened`, `notes`, and other metadata can be sent in the same request. Increasing stock or exceeding the package capacity is rejected. Quantity validation errors return `error.details.field` and `error.details.reason`.
For piece-aware stock, `PATCH` may instead set absolute `remaining_pieces`; a reduction consumes the difference atomically and updates measured stock and opened state. Do not send both remaining fields in one request. Flat piece-to-mass or piece-to-volume conversion requires an explicit `piece_amount`. Nested packages derive piece estimates from the explicit `inner_pack_amount`; measured deductions must correspond to whole pieces, and the final piece consumes the exact remaining residual. Consumption accepts `inner_packs` for configured nested packages. Inventory responses include the inner-pack counts, labels, and derived opened-inner-pack remainder. A count-only legacy row can be converted in place by supplying `quantity` explicitly with package contents and, when needed, measured amount and unit. Historical food logs are untouched.
## Example requests
```sh
+2
View File
@@ -108,6 +108,8 @@ The corresponding HTTP routes are listed in `GET /api/v1/schema/`. Recipe meal d
`inventory_update` accepts an absolute `remaining_amount` for one owned package. Reductions use the same consumption service as `inventory_consume`; zero archives the package. It can update `opened` and `notes` in the same request. A rejected quantity returns `success: false` with `error.details.field` and `error.details.reason`.
Inventory `quantity` is outer-package count. Flat packages use `pieces_per_package`, `remaining_pieces`, and optional explicit `piece_amount`. Nested packages add `inner_packs_per_package`, `pieces_per_inner_pack`, labels, and (for measured stock) `inner_pack_amount`. The outer amount and total piece count are derived from that metadata; per-piece weight is estimated from the measured inner-pack amount. `inventory_get_stock` exposes both piece and measured totals plus the nested breakdown. Preview and consume accept `pieces`, `inner_packs`, or matching g/ml amounts where the metadata supports conversion; measured deductions must map to whole pieces, with the final piece taking the exact remaining residual. `inventory_update` can reduce absolute `remaining_pieces` through the same atomic ledger. Converting a count-only legacy row requires explicitly setting package count so an old mistaken count is not multiplied into stock.
### Bulk inventory housekeeping
`inventory_bulk_update` accepts 1–50 `{item_id, changes}` entries. `changes` uses the same fields and stock rules as `inventory_update`; omitted fields stay unchanged. Optional `expected_updated_at` rejects an item that changed since it was read. `dry_run` defaults to true and returns per-item before/after snapshots without saving. Set `dry_run: false` and provide an `idempotency_key` to apply. The default allows valid entries to succeed when others fail; `atomic: true` rolls back the whole batch on any failure. Duplicate IDs and oversized batches are rejected before writes.
@@ -0,0 +1,14 @@
[Unit]
Description=Process Tasknest kitchen inventory scan jobs
After=network.target
[Service]
Type=simple
User=jorenmartijn
WorkingDirectory=/home/jorenmartijn/django/main
ExecStart=/home/jorenmartijn/django/tasksnest-host/bin/python manage.py process_inventory_scans --poll-seconds 2
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
+175 -6
View File
@@ -214,6 +214,15 @@ def _inventory_data(item):
return {'id': str(item.api_id), 'product_id': str(item.product.api_id),
'product_name': item.product.product_name, 'brand': item.product.brand,
'barcode': item.product.barcode, 'quantity': item.quantity,
'package_count': item.quantity, 'pieces_per_package': item.pieces_per_package,
'remaining_pieces': item.remaining_pieces,
'piece_amount': str(item.piece_amount) if item.piece_amount is not None else None,
'inner_packs_per_package': item.inner_packs_per_package,
'pieces_per_inner_pack': item.pieces_per_inner_pack,
'inner_pack_amount': str(item.inner_pack_amount) if item.inner_pack_amount is not None else None,
'inner_pack_label': item.inner_pack_label, 'piece_label': item.piece_label,
'remaining_full_inner_packs': item.remaining_full_inner_packs,
'opened_inner_pack_pieces': item.opened_inner_pack_pieces,
'location': item.location.name, 'category': item.category.name if item.category else None,
'notes': item.notes, 'opened': item.opened,
'remaining_amount': str(item.remaining_amount) if item.remaining_amount is not None else None,
@@ -460,7 +469,10 @@ def _import_one_grocery(request, raw, create_missing):
key: raw[key] for key in ('name', 'brand', 'barcode', 'package_quantity', 'package_unit', 'nutrition_per_100') if key in raw})
if product is None:
return {'status': 'needs_review', 'reason': 'Possible duplicate product.', 'candidates': candidates}
inventory_data = {key: raw[key] for key in ('quantity', 'location', 'category', 'notes', 'opened', 'best_before') if key in raw}
inventory_data = {key: raw[key] for key in ('quantity', 'location', 'category', 'notes', 'opened',
'best_before', 'original_amount', 'unit', 'pieces_per_package', 'remaining_pieces', 'piece_amount',
'inner_packs_per_package', 'pieces_per_inner_pack', 'inner_pack_amount',
'inner_pack_label', 'piece_label') if key in raw}
inventory_data['product_id'] = str(product.api_id)
item, failure = _save_inventory(request, inventory_data)
if failure:
@@ -589,10 +601,15 @@ def inventory_list(request):
def _save_inventory(request, data, item=None):
creating = item is None
was_count_only = item is not None and item.original_amount is None
old_piece_state = ((item.pieces_per_package, item.remaining_pieces, item.piece_amount,
item.inner_packs_per_package, item.pieces_per_inner_pack, item.inner_pack_amount,
item.inner_pack_label, item.piece_label)
if item is not None else None)
if item is None:
item = KitchenInventoryItem(user=request.api_user)
allowed = {'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'best_before', 'remaining_amount',
'original_amount', 'unit', 'purchase_batch'}
'original_amount', 'unit', 'purchase_batch', 'pieces_per_package', 'remaining_pieces', 'piece_amount',
'inner_packs_per_package', 'pieces_per_inner_pack', 'inner_pack_amount', 'inner_pack_label', 'piece_label'}
if set(data) - allowed:
raise ValueError('Unknown inventory fields.')
if 'product_id' in data:
@@ -604,6 +621,31 @@ def _save_inventory(request, data, item=None):
if isinstance(data['quantity'], bool) or not isinstance(data['quantity'], int) or data['quantity'] < 1:
raise ValueError('Quantity must be a positive integer.')
item.quantity = data['quantity']
if was_count_only and 'pieces_per_package' in data and 'quantity' not in data:
raise ValueError('Specify package count explicitly when converting a count-only item.')
for field in ('pieces_per_package', 'remaining_pieces'):
if field in data:
value = data[field]
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or
value < (1 if field == 'pieces_per_package' else 0)):
raise ValueError(f'{field} must be a whole count.')
setattr(item, field, value)
for field in ('inner_packs_per_package', 'pieces_per_inner_pack'):
if field in data:
value = data[field]
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value < 1):
raise ValueError(f'{field} must be a positive whole count.')
setattr(item, field, value)
if 'piece_amount' in data:
item.piece_amount = _decimal(data['piece_amount'], 'piece_amount') if data['piece_amount'] is not None else None
if 'inner_pack_amount' in data:
item.inner_pack_amount = _decimal(data['inner_pack_amount'], 'inner_pack_amount') if data['inner_pack_amount'] is not None else None
for field in ('inner_pack_label', 'piece_label'):
if field in data:
value = str(data[field] or '').strip()
if len(value) > 40:
raise ValueError(f'{field} must be 40 characters or fewer.')
setattr(item, field, value)
if 'location' in data:
name = ' '.join(str(data['location']).split())
if not name or len(name) > 100:
@@ -644,8 +686,88 @@ def _save_inventory(request, data, item=None):
raise ValueError('product_id and location are required.')
if creating and item.original_amount is None and item.product.package_amount:
item.original_amount, item.inventory_unit = item.product.package_amount, item.product.package_unit
if item.inner_packs_per_package is not None or item.pieces_per_inner_pack is not None:
if item.inner_packs_per_package is None or item.pieces_per_inner_pack is None:
raise ValueError('Provide both inner_packs_per_package and pieces_per_inner_pack.')
nested_capacity = item.inner_packs_per_package * item.pieces_per_inner_pack
if 'pieces_per_package' in data and item.pieces_per_package != nested_capacity:
raise ValueError('pieces_per_package must equal inner packs times pieces per inner pack.')
item.pieces_per_package = nested_capacity
if item.inventory_unit == 'pieces':
if item.inner_pack_amount is not None:
raise ValueError('Piece-only nested packages do not use inner_pack_amount.')
item.original_amount = Decimal(nested_capacity)
else:
if item.inventory_unit not in ('mg', 'g', 'kg', 'ml', 'L'):
raise ValueError('Nested packages require a pieces, mass, or volume unit.')
if item.inner_pack_amount is None:
raise ValueError('Provide inner_pack_amount for a weighed or measured nested package.')
derived_original = item.inner_pack_amount * item.inner_packs_per_package
if item.original_amount is not None and item.original_amount != derived_original:
raise ValueError('original_amount must equal inner_pack_amount times inner_packs_per_package.')
item.original_amount = derived_original
if item.remaining_pieces is None:
item.remaining_pieces = nested_capacity
if creating or was_count_only:
if item.inventory_unit == 'pieces':
expected_remaining = Decimal(item.remaining_pieces)
else:
from .services.inventory_consumption import _nested_amount_for_pieces
expected_remaining = _nested_amount_for_pieces(item, item.remaining_pieces)
if item.remaining_amount is not None and item.remaining_amount != expected_remaining:
raise ValueError('remaining_amount does not match the nested pieces and inner-pack amount.')
item.remaining_amount = expected_remaining
if item.remaining_pieces < nested_capacity:
item.opened = True
if item.pieces_per_package is not None:
if item.remaining_pieces is None:
item.remaining_pieces = item.pieces_per_package
if item.original_amount is None:
item.original_amount = Decimal(item.pieces_per_package)
item.inventory_unit = 'pieces'
if item.inventory_unit == 'pieces':
if item.original_amount != item.pieces_per_package:
raise ValueError('Piece package amount must equal pieces per package.')
expected = Decimal(item.remaining_pieces)
elif item.remaining_pieces < item.pieces_per_package and (creating or was_count_only):
if item.inner_packs_per_package is not None:
from .services.inventory_consumption import _nested_amount_for_pieces
expected = _nested_amount_for_pieces(item, item.remaining_pieces)
elif item.piece_amount is None:
raise ValueError('An explicit amount per piece is required for partly used weighed packages.')
else:
expected = item.piece_amount * item.remaining_pieces
else:
expected = item.original_amount
if (creating or was_count_only) and item.remaining_amount is not None and item.remaining_amount != expected:
raise ValueError('Remaining amount and piece count disagree.')
if creating or was_count_only:
item.remaining_amount = expected
if item.remaining_pieces < item.pieces_per_package:
item.opened = True
if item.original_amount is not None and item.remaining_amount is None:
item.remaining_amount = item.original_amount
if not creating and not was_count_only and item.pieces_per_package is not None:
current_piece_state = (item.pieces_per_package, item.remaining_pieces, item.piece_amount,
item.inner_packs_per_package, item.pieces_per_inner_pack, item.inner_pack_amount,
item.inner_pack_label, item.piece_label)
if old_piece_state[0] is not None and old_piece_state != current_piece_state:
raise ValueError('Use inventory consumption to change tracked pieces.')
if old_piece_state[0] is None:
if item.quantity != 1:
raise ValueError('Convert one package at a time.')
if item.inventory_unit == 'pieces':
if item.remaining_amount != item.remaining_pieces:
raise ValueError('Piece count must match current stock.')
elif item.inner_packs_per_package is not None:
from .services.inventory_consumption import _nested_amount_for_pieces
if _nested_amount_for_pieces(item, item.remaining_pieces) != item.remaining_amount:
raise ValueError('Nested pieces must match current measured stock.')
elif item.piece_amount is None:
if item.remaining_amount != item.original_amount or item.remaining_pieces != item.pieces_per_package:
raise ValueError('Set an explicit amount per piece for partly used stock.')
elif item.piece_amount * item.remaining_pieces != item.remaining_amount:
raise ValueError('Piece count and amount per piece must match current stock.')
item.full_clean()
item.save()
if creating or (was_count_only and item.original_amount is not None):
@@ -698,7 +820,32 @@ def inventory_change(request, identifier):
def _apply_inventory_update(request, item, data):
"""Shared single-item rules for PATCH and batch updates; caller owns the transaction."""
data = dict(data)
deducted = False
try:
if item.original_amount is not None and item.pieces_per_package is not None and 'remaining_pieces' in data:
if 'remaining_amount' in data:
return _inventory_validation('remaining_pieces', 'Change pieces or measured amount in one request, not both.')
count = data['remaining_pieces']
if isinstance(count, bool) or not isinstance(count, int) or count < 0:
return _inventory_validation('remaining_pieces', 'Enter a non-negative whole piece count.')
if count > item.remaining_pieces:
return _inventory_validation('remaining_pieces', 'Increasing remaining stock is not supported.')
if count < item.remaining_pieces:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit', 'pieces_per_package', 'piece_amount',
'inner_packs_per_package', 'pieces_per_inner_pack', 'inner_pack_amount'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0], 'Change package metadata separately from consumption.')
if data.get('opened') is False and count > 0:
return _inventory_validation('opened', 'A partly used package must be opened.')
from .services.inventory_consumption import StockError, consume
try:
consume(request.api_user, item.product, item.remaining_pieces - count,
'pieces', package_id=item.api_id, source='mcp')
except StockError as exc:
return _inventory_validation('remaining_pieces', str(exc))
deducted = True
item.refresh_from_db()
data.pop('remaining_pieces')
remaining = data.get('remaining_amount', item.remaining_amount)
if 'remaining_amount' in data and remaining is not None:
try:
@@ -714,7 +861,9 @@ def _apply_inventory_update(request, item, data):
if remaining > item.remaining_amount:
return _inventory_validation('remaining_amount', 'Increasing remaining stock is not supported.')
if remaining < item.remaining_amount:
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit'}
conflicting = set(data) & {'product_id', 'quantity', 'original_amount', 'unit',
'pieces_per_package', 'piece_amount', 'inner_packs_per_package',
'pieces_per_inner_pack', 'inner_pack_amount', 'inner_pack_label', 'piece_label'}
if conflicting:
return _inventory_validation(sorted(conflicting)[0],
'Change package identity or size separately from consumption.')
@@ -727,13 +876,18 @@ def _apply_inventory_update(request, item, data):
description=str(data.get('notes') or '')[:255])
except StockError as exc:
return _inventory_validation('remaining_amount', str(exc))
deducted = True
item.refresh_from_db()
data = {key: value for key, value in data.items() if key != 'remaining_amount'}
elif 'remaining_amount' in data:
return _inventory_validation('remaining_amount', 'Use a number between zero and the package capacity.')
item, failure = _save_inventory(request, data, item)
if failure is not None and deducted:
transaction.set_rollback(True)
return failure or JsonResponse(_inventory_data(item))
except (ValueError, ValidationError) as exc:
if deducted:
transaction.set_rollback(True)
return _inventory_exception(exc)
@@ -773,7 +927,10 @@ def _inventory_batch_input(request, data, *, deleting=False):
changes = raw.get('changes')
expected = raw.get('expected_updated_at')
if not isinstance(changes, dict) or not changes or set(changes) - {
'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'remaining_amount', 'best_before'}:
'product_id', 'quantity', 'location', 'category', 'notes', 'opened', 'remaining_amount',
'original_amount', 'unit', 'pieces_per_package', 'remaining_pieces', 'piece_amount',
'inner_packs_per_package', 'pieces_per_inner_pack', 'inner_pack_amount',
'inner_pack_label', 'piece_label', 'best_before'}:
raise ValueError('Each update needs supported, nonempty changes.')
if expected is not None and not isinstance(expected, str):
raise ValueError('expected_updated_at must be a timestamp.')
@@ -955,7 +1112,11 @@ def _stock_result(plan):
'available': str(plan['total']), 'shortage': str(plan['shortage']),
'deductions': [{'package_id': str(row['package'].api_id),
'amount': str(row['amount']), 'unit': row['unit'],
'before': str(row['before']), 'after': str(row['after'])}
'before': str(row['before']), 'after': str(row['after']),
'before_pieces': row['before_pieces'], 'after_pieces': row['after_pieces'],
'after_inner_pack_balance': row['after_inner_pack_balance'],
'estimated_piece_weight': bool(row['package'].inner_packs_per_package and
plan['unit'] in ('pieces', 'inner_packs'))}
for row in plan['deductions']]}
@@ -985,6 +1146,8 @@ def inventory_stock(request):
dimension, factor = FACTORS[unit]
base_unit = {'mass': 'g', 'volume': 'ml'}.get(dimension, unit)
groups[base_unit] = groups.get(base_unit, Decimal(0)) + amount * factor
if item.remaining_pieces is not None and base_unit != 'pieces':
groups['pieces'] = groups.get('pieces', Decimal(0)) + item.remaining_pieces
result.append({'product_id': str(product.api_id), 'product_name': product.product_name,
'totals': {unit: str(amount) for unit, amount in groups.items()},
'available': any(amount > 0 for amount in groups.values()),
@@ -1022,7 +1185,13 @@ def inventory_consume(request):
allow_partial=data.get('allow_partial') is True)
return JsonResponse({'transaction_id': str(operation.pk), 'amount': str(operation.amount),
'unit': operation.unit, 'deductions': [{'package_id': str(line.package.api_id),
'amount': str(line.amount), 'unit': line.unit} for line in operation.lines.select_related('package')]})
'amount': str(line.amount), 'unit': line.unit,
'remaining_amount': str(line.after_amount), 'remaining_pieces': line.after_pieces,
'remaining_full_inner_packs': line.package.remaining_full_inner_packs,
'opened_inner_pack_pieces': line.package.opened_inner_pack_pieces,
'inner_pack_label': line.package.inner_pack_label,
'piece_label': line.package.piece_label}
for line in operation.lines.select_related('package')]})
except (StockError, KeyError, ValueError) as exc:
return error('invalid_consumption', str(exc))
+9
View File
@@ -37,6 +37,15 @@ INVENTORY = {'type': 'object', 'properties': {
'location': {'type': 'string'}, 'category': {'type': 'string'}, 'notes': {'type': 'string'},
'opened': {'type': 'boolean'}, 'best_before': {'type': ['string', 'null'], 'format': 'date'},
'remaining_amount': {'type': ['string', 'null'], 'description': 'Only for one opened package with known size'},
'original_amount': {'type': ['string', 'null']}, 'unit': {'type': 'string'},
'pieces_per_package': {'type': ['integer', 'null'], 'minimum': 1},
'remaining_pieces': {'type': ['integer', 'null'], 'minimum': 0},
'piece_amount': {'type': ['string', 'null'], 'description': 'Explicit amount per piece in the package unit'},
'inner_packs_per_package': {'type': ['integer', 'null'], 'minimum': 1},
'pieces_per_inner_pack': {'type': ['integer', 'null'], 'minimum': 1},
'inner_pack_amount': {'type': ['string', 'null'], 'description': 'Measured amount per inner pack in the package unit'},
'inner_pack_label': {'type': 'string', 'maxLength': 40},
'piece_label': {'type': 'string', 'maxLength': 40},
}}
PRODUCT = {'type': 'object', 'required': ['name'], 'properties': {
'name': {'type': 'string', 'maxLength': 255}, 'brand': {'type': 'string', 'maxLength': 255},
+128 -5
View File
@@ -207,9 +207,18 @@ class InventoryItemForm(forms.ModelForm):
class Meta:
model = KitchenInventoryItem
fields = ('quantity', 'original_amount', 'inventory_unit', 'opened', 'best_before', 'notes')
fields = ('quantity', 'original_amount', 'inventory_unit', 'pieces_per_package',
'remaining_pieces', 'piece_amount', 'inner_packs_per_package',
'pieces_per_inner_pack', 'inner_pack_amount', 'inner_pack_label',
'piece_label', 'opened', 'best_before', 'notes')
widgets = {'quantity': forms.NumberInput(attrs={'min': 1, 'step': 1}),
'original_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
'pieces_per_package': forms.NumberInput(attrs={'min': 1, 'step': 1}),
'remaining_pieces': forms.NumberInput(attrs={'min': 0, 'step': 1}),
'piece_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
'inner_packs_per_package': forms.NumberInput(attrs={'min': 1, 'step': 1}),
'pieces_per_inner_pack': forms.NumberInput(attrs={'min': 1, 'step': 1}),
'inner_pack_amount': forms.NumberInput(attrs={'min': '.001', 'step': '.001'}),
'best_before': forms.DateInput(attrs={'type': 'date'}),
'notes': forms.Textarea(attrs={'rows': 2})}
@@ -218,7 +227,26 @@ class InventoryItemForm(forms.ModelForm):
self.fields['inventory_unit'] = forms.ChoiceField(required=False, label='Package unit',
choices=[('', 'Count only (unknown size)')] + [(unit, unit) for unit in
('mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions')])
self.fields['original_amount'].label = 'Amount per package'
self.fields['original_amount'].label = 'Amount in outer package'
self.fields['quantity'].label = 'Number of packages'
self.fields['pieces_per_package'].label = 'Total pieces per package (flat package)'
self.fields['remaining_pieces'].label = 'Individual pieces remaining'
self.fields['piece_amount'].label = 'Amount per piece in package unit (optional)'
self.fields['inner_packs_per_package'].label = 'Inner packs per package (optional)'
self.fields['pieces_per_inner_pack'].label = 'Pieces per inner pack'
self.fields['inner_pack_amount'].label = 'Amount per inner pack'
self.fields['inner_pack_label'].label = 'Inner pack name'
self.fields['piece_label'].label = 'Individual item name'
self.fields['quantity'].help_text = 'Count packages or cans here, not the pieces inside them.'
self.fields['original_amount'].help_text = 'For nested packs, leave blank to calculate it from inner-pack amount × inner packs.'
self.fields['pieces_per_package'].help_text = 'For flat packages, such as 12 rolls or 10 sausages. Leave blank when entering nested pack counts below.'
self.fields['remaining_pieces'].help_text = 'Total individual pieces left across all inner packs. For a full package, leave blank.'
self.fields['piece_amount'].help_text = 'Enter a measured amount per piece for g or ml conversion; never inferred from the pack label.'
self.fields['inner_packs_per_package'].help_text = 'For a nested pack, such as 6 individually wrapped inner packs.'
self.fields['pieces_per_inner_pack'].help_text = 'How many individual items are in each inner pack.'
self.fields['inner_pack_amount'].help_text = 'Measured amount in one inner pack, for example 44 g. This derives the approximate amount per piece.'
self.fields['inner_pack_label'].help_text = 'For example, packet or wrapper.'
self.fields['piece_label'].help_text = 'For example, biscuit or cracker.'
if self.instance.pk:
self.fields['location_name'].initial = self.instance.location.name
self.fields['category_name'].initial = self.instance.category.name if self.instance.category else ''
@@ -226,16 +254,111 @@ class InventoryItemForm(forms.ModelForm):
def clean(self):
data = super().clean()
pieces = data.get('pieces_per_package')
remaining_pieces = data.get('remaining_pieces')
piece_amount = data.get('piece_amount')
original = data.get('original_amount')
unit = data.get('inventory_unit')
inner_packs = data.get('inner_packs_per_package')
pieces_per_inner = data.get('pieces_per_inner_pack')
inner_amount = data.get('inner_pack_amount')
was_count_only = self.instance.pk and KitchenInventoryItem.objects.filter(
pk=self.instance.pk, original_amount__isnull=True).exists()
nested = inner_packs is not None or pieces_per_inner is not None
if nested:
if inner_packs is None or pieces_per_inner is None:
raise forms.ValidationError('Enter both inner packs per package and pieces per inner pack.')
if pieces is not None and pieces != inner_packs * pieces_per_inner:
raise forms.ValidationError('Total pieces must equal inner packs times pieces per inner pack.')
pieces = inner_packs * pieces_per_inner
data['pieces_per_package'] = pieces
self.instance.pieces_per_package = pieces
if not data.get('piece_label'):
raise forms.ValidationError('Name the individual item, for example biscuit.')
if inner_packs > 1 and not data.get('inner_pack_label'):
raise forms.ValidationError('Name the inner package, for example packet.')
if not original and not unit:
if inner_amount is not None:
raise forms.ValidationError('Choose a package unit for the measured inner-pack amount.')
original, unit = Decimal(pieces), 'pieces'
data['original_amount'], data['inventory_unit'] = original, unit
self.instance.original_amount, self.instance.inventory_unit = original, unit
if unit == 'pieces':
if inner_amount is not None:
raise forms.ValidationError('Piece-only packages do not use a measured inner-pack amount.')
original = Decimal(pieces)
data['original_amount'] = original
self.instance.original_amount = original
elif unit in ('mg', 'g', 'kg', 'ml', 'L'):
if inner_amount is None:
raise forms.ValidationError('Enter the measured amount in one inner pack.')
expected_original = inner_amount * inner_packs
if original is not None and original != expected_original:
raise forms.ValidationError('Outer package amount must equal inner-pack amount times inner packs.')
original = expected_original
data['original_amount'] = original
self.instance.original_amount = original
else:
raise forms.ValidationError('Nested contents require a pieces, mass, or volume unit.')
if piece_amount is not None:
raise forms.ValidationError('Nested packages derive piece amounts from the inner-pack amount.')
if pieces is not None:
if remaining_pieces is None:
remaining_pieces = pieces
data['remaining_pieces'] = pieces
self.instance.remaining_pieces = pieces
if remaining_pieces > pieces:
raise forms.ValidationError('Pieces remaining cannot exceed pieces per package.')
if not original and not unit:
original, unit = Decimal(pieces), 'pieces'
data['original_amount'], data['inventory_unit'] = original, unit
self.instance.original_amount, self.instance.inventory_unit = original, unit
if unit == 'pieces':
if original != Decimal(pieces) or piece_amount is not None:
raise forms.ValidationError('For piece stock, package amount must equal pieces per package; leave amount per piece blank.')
if not self.instance.pk or was_count_only:
self.instance.remaining_amount = Decimal(remaining_pieces)
elif unit in ('mg', 'g', 'kg', 'ml', 'L'):
if remaining_pieces < pieces and (not self.instance.pk or was_count_only):
if nested:
full_packs, loose_pieces = divmod(remaining_pieces, pieces_per_inner)
remaining_value = inner_amount * full_packs
if loose_pieces:
remaining_value += (inner_amount * loose_pieces / pieces_per_inner).quantize(Decimal('.001'))
self.instance.remaining_amount = remaining_value
elif piece_amount is None:
raise forms.ValidationError('Enter an explicit amount per piece to record a partly used weighed package.')
else:
self.instance.remaining_amount = piece_amount * remaining_pieces
if self.instance.remaining_amount > original:
raise forms.ValidationError('Piece amounts exceed the package amount.')
else:
raise forms.ValidationError('Piece contents require a piece, mass, or volume package unit.')
if remaining_pieces < pieces:
self.instance.opened = True
data['opened'] = True
elif remaining_pieces is not None or piece_amount is not None:
raise forms.ValidationError('Enter pieces per package first.')
if bool(data.get('original_amount')) != bool(data.get('inventory_unit')):
raise forms.ValidationError('Enter both package amount and unit, or leave both blank.')
if data.get('original_amount') and self.instance.remaining_amount is None:
self.instance.remaining_amount = data['original_amount']
if self.instance.pk and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount:
if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('original_amount') != self.instance.original_amount:
raise forms.ValidationError('Existing package sizes cannot be changed after tracking starts.')
if self.instance.pk and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit:
if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('inventory_unit') != self.instance.inventory_unit:
raise forms.ValidationError('Existing package units cannot be changed after tracking starts.')
if self.instance.pk and self.instance.original_amount and data.get('quantity') != 1:
if self.instance.pk and not was_count_only and self.instance.original_amount and data.get('quantity') != 1:
raise forms.ValidationError('A tracked package has a quantity of one.')
if self.instance.pk and not was_count_only:
old = KitchenInventoryItem.objects.get(pk=self.instance.pk)
nested_state = (inner_packs, pieces_per_inner, inner_amount,
data.get('inner_pack_label'), data.get('piece_label'))
old_nested_state = (old.inner_packs_per_package, old.pieces_per_inner_pack,
old.inner_pack_amount, old.inner_pack_label, old.piece_label)
if old.pieces_per_package is not None and (pieces != old.pieces_per_package or piece_amount != old.piece_amount or remaining_pieces != old.remaining_pieces or nested_state != old_nested_state):
raise forms.ValidationError('Use inventory consumption to change tracked pieces.')
if old.pieces_per_package is None and pieces is not None and not nested and piece_amount is not None and old.remaining_amount != piece_amount * remaining_pieces:
raise forms.ValidationError('Piece counts must match current measured stock; use inventory consumption for deductions.')
return data
def clean_location_name(self):
+73 -5
View File
@@ -13,7 +13,8 @@ from django.utils import timezone
from django.views.decorators.http import require_http_methods, require_POST
from .forms import InventoryItemForm, InventoryManualProductForm
from .models import FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation, KitchenInventoryItem
from .models import (FoodProduct, InventoryCategory, InventoryConsumption, InventoryLocation,
InventoryReviewPreference, InventoryScanItem, KitchenInventoryItem)
from .services.inventory_consumption import FACTORS, StockError, consume, materialize_packages, preview, undo
from .services.openfoodfacts import OpenFoodFactsError, cached_product, cached_search
from .services.products import local_products
@@ -23,6 +24,16 @@ def _owned_items(user):
return KitchenInventoryItem.objects.filter(user=user, archived_at__isnull=True).select_related('product', 'location', 'category')
def _inventory_review_counts(user):
review_items = InventoryScanItem.objects.filter(batch__run__user=user)
return {
'processing_count': review_items.filter(status__in=(InventoryScanItem.Status.QUEUED,
InventoryScanItem.Status.PROCESSING)).count(),
'needs_review_count': review_items.filter(status__in=(InventoryScanItem.Status.NEEDS_REVIEW,
InventoryScanItem.Status.DEFERRED, InventoryScanItem.Status.FAILED)).count(),
}
@login_required
def overview(request):
items = _owned_items(request.user)
@@ -58,12 +69,23 @@ def overview(request):
choices = {'mg': ('mg', 'g', 'kg'), 'g': ('mg', 'g', 'kg'), 'kg': ('mg', 'g', 'kg'),
'ml': ('ml', 'L'), 'L': ('ml', 'L')}
cards[key] = {'product': item.product, 'unit': unit, 'packages': [], 'total': Decimal(0),
'units': choices.get(unit, (unit,)),
'units': list(choices.get(unit, (unit,))), 'piece_total': 0, 'has_pieces': False,
'package_count': 0,
'count_unit': dimension in ('pieces', 'packs', 'portions')}
cards[key]['packages'].append(item)
cards[key]['package_count'] += item.quantity if item.original_amount is None else 1
cards[key]['total'] += (item.remaining_amount if item.remaining_amount is not None
else Decimal(item.quantity)) * factor
if item.remaining_pieces is not None:
cards[key]['piece_total'] += item.remaining_pieces
cards[key]['has_pieces'] = True
if 'pieces' not in cards[key]['units'] and (item.piece_amount is not None or item.inner_packs_per_package):
cards[key]['units'].append('pieces')
if item.inner_packs_per_package and 'inner_packs' not in cards[key]['units']:
cards[key]['units'].append('inner_packs')
recent = InventoryConsumption.objects.filter(user=request.user, reverses__isnull=True).select_related('product').prefetch_related('lines__package').order_by('-created_at')[:8]
review_counts = _inventory_review_counts(request.user)
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
return render(request, 'food/inventory_overview.html', {
'items': items, 'cards': list(cards.values()), 'recent_consumption': recent,
'query': query, 'sort': sort, 'selected_location': location,
@@ -71,9 +93,18 @@ def overview(request):
'locations': InventoryLocation.objects.filter(user=request.user),
'categories': InventoryCategory.objects.filter(user=request.user),
'today': timezone.localdate(), 'soon_date': timezone.localdate() + timedelta(days=14),
**review_counts,
'review_mode': preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL,
})
@login_required
@require_http_methods(['GET'])
def inventory_staging_counts(request):
return render(request, 'food/partials/inventory_staging_counts.html',
_inventory_review_counts(request.user))
@login_required
@require_http_methods(['GET', 'POST'])
def add(request):
@@ -98,7 +129,8 @@ def add(request):
item = form.save(commit=False)
item.user, item.product, item.location, item.category = request.user, product, location, category
if item.original_amount is not None:
item.remaining_amount = item.original_amount
if item.remaining_amount is None:
item.remaining_amount = item.original_amount
if item.quantity > 1:
count = item.quantity
item.quantity = 1
@@ -222,7 +254,12 @@ def change_quantity(request, pk):
if item.original_amount is not None:
KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location,
category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount,
inventory_unit=item.inventory_unit, best_before=item.best_before)
inventory_unit=item.inventory_unit, pieces_per_package=item.pieces_per_package,
remaining_pieces=item.pieces_per_package, piece_amount=item.piece_amount,
inner_packs_per_package=item.inner_packs_per_package,
pieces_per_inner_pack=item.pieces_per_inner_pack, inner_pack_amount=item.inner_pack_amount,
inner_pack_label=item.inner_pack_label, piece_label=item.piece_label,
best_before=item.best_before)
else:
item.quantity += 1
item.save(update_fields=('quantity', 'updated_at'))
@@ -237,7 +274,12 @@ def add_existing(request, pk):
if item.original_amount is not None:
KitchenInventoryItem.objects.create(user=item.user, product=item.product, location=item.location,
category=item.category, original_amount=item.original_amount, remaining_amount=item.original_amount,
inventory_unit=item.inventory_unit, best_before=item.best_before)
inventory_unit=item.inventory_unit, pieces_per_package=item.pieces_per_package,
remaining_pieces=item.pieces_per_package, piece_amount=item.piece_amount,
inner_packs_per_package=item.inner_packs_per_package,
pieces_per_inner_pack=item.pieces_per_inner_pack, inner_pack_amount=item.inner_pack_amount,
inner_pack_label=item.inner_pack_label, piece_label=item.piece_label,
best_before=item.best_before)
else:
item.quantity += 1
item.save(update_fields=('quantity', 'updated_at'))
@@ -254,6 +296,32 @@ def preview_consumption(request, pk):
request.POST.get('unit'), request.POST.get('package_id') or None)
except StockError as exc:
return render(request, 'food/partials/inventory_preview.html', {'error': str(exc)})
base_unit = product.base_unit
base_dimension = FACTORS[base_unit][0]
equivalent = Decimal(0)
compatible_equivalent = True
estimated_piece_weight = False
for deduction in plan['deductions']:
unit = deduction['unit']
if FACTORS[unit][0] != base_dimension:
compatible_equivalent = False
break
equivalent += deduction['amount'] * FACTORS[unit][1]
if deduction['package'].inner_packs_per_package and plan['unit'] in ('pieces', 'inner_packs'):
estimated_piece_weight = True
nutrition = []
if compatible_equivalent and equivalent:
for label, field in (('Energy', 'energy_kcal_100'), ('Carbohydrates', 'carbohydrates_100'),
('Protein', 'protein_100'), ('Fat', 'fat_100'),
('Fibre', 'fibre_100'), ('Sugars', 'sugars_100'), ('Salt', 'salt_100')):
value = getattr(product, field)
if value is not None:
nutrition.append({'label': label, 'value': (value * equivalent / 100).quantize(Decimal('.1')),
'unit': 'kcal' if label == 'Energy' else 'g'})
plan['equivalent_amount'] = equivalent.quantize(Decimal('.001')) if compatible_equivalent else None
plan['equivalent_unit'] = base_unit
plan['estimated_piece_weight'] = estimated_piece_weight
plan['nutrition'] = nutrition
return render(request, 'food/partials/inventory_preview.html',
{'plan': plan, 'product': product, 'package_id': request.POST.get('package_id', '')})
@@ -0,0 +1,29 @@
import time
from django.core.management.base import BaseCommand
from food.services.inventory_scanner import (dispatch_pending_scan_notifications,
process_next_scan_item)
class Command(BaseCommand):
help = 'Process due persisted kitchen inventory scan enrichment jobs.'
def add_arguments(self, parser):
parser.add_argument('--once', action='store_true', help='Process at most one job and exit.')
parser.add_argument('--poll-seconds', type=float, default=2.0)
parser.add_argument('--max-items', type=int, default=0, help='Stop after this many jobs; 0 runs continuously.')
def handle(self, *args, **options):
processed = 0
while True:
dispatch_pending_scan_notifications()
did_work = process_next_scan_item()
if did_work:
processed += 1
if options['once'] or (options['max_items'] and processed >= options['max_items']):
return
elif options['once']:
return
else:
time.sleep(max(0.25, options['poll_seconds']))
@@ -0,0 +1,39 @@
# Generated by Django 6.1.1 on 2026-10-25 16:08
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0011_log_quantity'),
]
operations = [
migrations.AddField(
model_name='inventoryconsumptionline',
name='after_pieces',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='inventoryconsumptionline',
name='before_pieces',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='piece_amount',
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)]),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='pieces_per_package',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='remaining_pieces',
field=models.PositiveIntegerField(blank=True, null=True),
),
]
@@ -0,0 +1,39 @@
# Generated by Django 6.1.1 on 2026-10-25 23:07
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0012_inventoryconsumptionline_after_pieces_and_more'),
]
operations = [
migrations.AddField(
model_name='kitcheninventoryitem',
name='inner_pack_amount',
field=models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)]),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='inner_pack_label',
field=models.CharField(blank=True, max_length=40),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='inner_packs_per_package',
field=models.PositiveIntegerField(blank=True, null=True),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='piece_label',
field=models.CharField(blank=True, max_length=40),
),
migrations.AddField(
model_name='kitcheninventoryitem',
name='pieces_per_inner_pack',
field=models.PositiveIntegerField(blank=True, null=True),
),
]
@@ -0,0 +1,18 @@
# Generated by Django 6.1.1 on 2026-10-25 23:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0013_kitcheninventoryitem_inner_pack_amount_and_more'),
]
operations = [
migrations.AlterField(
model_name='inventoryconsumption',
name='unit',
field=models.CharField(max_length=16),
),
]
@@ -0,0 +1,127 @@
# Generated by Django 6.1.1 on 2026-10-25 23:32
import django.core.validators
import django.db.models.deletion
import uuid
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0014_alter_inventoryconsumption_unit'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='OpenFoodFactsRequest',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('requested_at', models.DateTimeField(db_index=True)),
('endpoint', models.CharField(blank=True, max_length=24)),
],
),
migrations.CreateModel(
name='OpenFoodFactsRateLimit',
fields=[
('id', models.PositiveSmallIntegerField(default=1, editable=False, primary_key=True, serialize=False)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='InventoryReviewPreference',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('mode', models.CharField(choices=[('individual', 'Individual'), ('bulk', 'Bulk')], default='individual', max_length=12)),
('updated_at', models.DateTimeField(auto_now=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='inventory_review_preference', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='InventoryScanRun',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('api_id', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)),
('status', models.CharField(choices=[('active', 'Active'), ('processing', 'Processing'), ('complete', 'Complete'), ('complete_with_review', 'Complete with review'), ('cancelled', 'Cancelled')], db_index=True, default='active', max_length=24)),
('created_at', models.DateTimeField(auto_now_add=True)),
('submitted_at', models.DateTimeField(blank=True, null=True)),
('completed_at', models.DateTimeField(blank=True, null=True)),
('notification_attempted_at', models.DateTimeField(blank=True, null=True)),
('notification_sent_at', models.DateTimeField(blank=True, null=True)),
('notification_error', models.CharField(blank=True, max_length=255)),
('selected_location', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='active_scan_runs', to='food.inventorylocation')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='inventory_scan_runs', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='InventoryScanBatch',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('sequence', models.PositiveIntegerField()),
('status', models.CharField(choices=[('draft', 'Draft'), ('queued', 'Queued'), ('complete', 'Complete')], db_index=True, default='draft', max_length=12)),
('created_at', models.DateTimeField(auto_now_add=True)),
('submitted_at', models.DateTimeField(blank=True, null=True)),
('completed_at', models.DateTimeField(blank=True, null=True)),
('location', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='scan_batches', to='food.inventorylocation')),
('run', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='batches', to='food.inventoryscanrun')),
],
options={
'ordering': ('sequence',),
},
),
migrations.CreateModel(
name='InventoryScanItem',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('barcode', models.CharField(db_index=True, max_length=64)),
('status', models.CharField(choices=[('active', 'Active scan'), ('confirmed', 'Confirmed'), ('queued', 'Queued'), ('processing', 'Processing'), ('needs_review', 'Needs review'), ('complete', 'Complete'), ('deferred', 'Deferred'), ('failed', 'Failed')], db_index=True, default='active', max_length=16)),
('package_count', models.PositiveIntegerField(default=1, validators=[django.core.validators.MinValueValidator(1)])),
('package_amount', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)])),
('package_unit', models.CharField(blank=True, max_length=8)),
('pieces_per_package', models.PositiveIntegerField(blank=True, null=True)),
('piece_amount', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)])),
('inner_packs_per_package', models.PositiveIntegerField(blank=True, null=True)),
('pieces_per_inner_pack', models.PositiveIntegerField(blank=True, null=True)),
('inner_pack_amount', models.DecimalField(blank=True, decimal_places=3, max_digits=10, null=True, validators=[django.core.validators.MinValueValidator(0.001)])),
('inner_pack_label', models.CharField(blank=True, max_length=40)),
('piece_label', models.CharField(blank=True, max_length=40)),
('product_name', models.CharField(blank=True, max_length=255)),
('brand', models.CharField(blank=True, max_length=255)),
('category_name', models.CharField(blank=True, max_length=100)),
('notes', models.TextField(blank=True)),
('best_before', models.DateField(blank=True, null=True)),
('opened', models.BooleanField(default=False)),
('source_data', models.JSONField(blank=True, default=dict)),
('user_data', models.JSONField(blank=True, default=dict)),
('attempts', models.PositiveSmallIntegerField(default=0)),
('next_attempt_at', models.DateTimeField(blank=True, db_index=True, null=True)),
('lease_until', models.DateTimeField(blank=True, db_index=True, null=True)),
('last_error', models.CharField(blank=True, max_length=255)),
('created_at', models.DateTimeField(auto_now_add=True)),
('confirmed_at', models.DateTimeField(blank=True, null=True)),
('completed_at', models.DateTimeField(blank=True, null=True)),
('batch', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='items', to='food.inventoryscanbatch')),
('location', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='scan_items', to='food.inventorylocation')),
('inventory_item', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='scan_items', to='food.kitcheninventoryitem')),
('product', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='scan_items', to='food.foodproduct')),
],
options={
'ordering': ('created_at', 'pk'),
'indexes': [models.Index(fields=['status', 'next_attempt_at'], name='food_scan_item_due')],
},
),
migrations.AddIndex(
model_name='inventoryscanrun',
index=models.Index(fields=['user', 'status', '-created_at'], name='food_scan_run_user_status'),
),
migrations.AddConstraint(
model_name='inventoryscanbatch',
constraint=models.UniqueConstraint(fields=('run', 'sequence'), name='food_unique_scan_batch_sequence'),
),
migrations.AddConstraint(
model_name='inventoryscanbatch',
constraint=models.UniqueConstraint(condition=models.Q(('status', 'draft')), fields=('run',), name='food_one_draft_scan_batch'),
),
]
@@ -0,0 +1,19 @@
# Generated by Django 6.1.1 on 2026-10-25 23:36
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('food', '0015_openfoodfactsrequest_inventoryreviewpreference_and_more'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddConstraint(
model_name='inventoryscanrun',
constraint=models.UniqueConstraint(condition=models.Q(('status', 'active')), fields=('user',), name='food_one_active_scan_run'),
),
]
+209 -2
View File
@@ -1,5 +1,5 @@
import uuid
from decimal import Decimal
from decimal import Decimal, ROUND_HALF_UP
from django.conf import settings
from django.core.exceptions import ValidationError
@@ -192,6 +192,14 @@ class KitchenInventoryItem(models.Model):
remaining_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=NON_NEGATIVE)
original_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inventory_unit = models.CharField(max_length=8, blank=True)
pieces_per_package = models.PositiveIntegerField(null=True, blank=True)
remaining_pieces = models.PositiveIntegerField(null=True, blank=True)
piece_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inner_packs_per_package = models.PositiveIntegerField(null=True, blank=True)
pieces_per_inner_pack = models.PositiveIntegerField(null=True, blank=True)
inner_pack_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inner_pack_label = models.CharField(max_length=40, blank=True)
piece_label = models.CharField(max_length=40, blank=True)
opened_at = models.DateTimeField(null=True, blank=True)
purchase_batch = models.CharField(max_length=100, blank=True)
best_before = models.DateField(null=True, blank=True)
@@ -211,6 +219,56 @@ class KitchenInventoryItem(models.Model):
if (self.original_amount is not None and self.remaining_amount is not None and
0 < self.remaining_amount < self.original_amount and not self.opened):
raise ValidationError({'opened': 'A partly used package must be opened.'})
if self.pieces_per_package is not None:
if not self.pieces_per_package or (self.pk and self.quantity != 1) or self.original_amount is None:
raise ValidationError({'pieces_per_package': 'Track one package with a known contents amount.'})
if self.remaining_pieces is None or self.remaining_pieces > self.pieces_per_package:
raise ValidationError({'remaining_pieces': 'Enter a piece count within the package capacity.'})
if self.remaining_pieces < self.pieces_per_package and not self.opened and self.remaining_pieces > 0:
raise ValidationError({'opened': 'A partly used package must be opened.'})
if self.inventory_unit == 'pieces':
if self.original_amount != self.pieces_per_package or self.remaining_amount != self.remaining_pieces:
raise ValidationError({'original_amount': 'Piece stock must match the package piece counts.'})
if self.piece_amount is not None:
raise ValidationError({'piece_amount': 'A separate piece amount is only used for weighed packages.'})
elif self.inventory_unit in ('mg', 'g', 'kg', 'ml', 'L'):
if self.piece_amount is not None and self.piece_amount <= 0:
raise ValidationError({'piece_amount': 'Enter a positive amount per piece.'})
if self.remaining_pieces == 0 and self.remaining_amount != 0:
raise ValidationError({'remaining_amount': 'A package with no pieces must have no remaining amount.'})
else:
raise ValidationError({'inventory_unit': 'Piece contents require pieces, mass, or volume.'})
elif self.remaining_pieces is not None or self.piece_amount is not None:
raise ValidationError({'pieces_per_package': 'Enter pieces per package first.'})
nested_values = (self.inner_packs_per_package, self.pieces_per_inner_pack)
if any(value is not None for value in nested_values):
if any(value is None or value < 1 for value in nested_values):
raise ValidationError({'inner_packs_per_package': 'Enter both inner packs per package and pieces per inner pack.'})
if self.pieces_per_package != self.inner_packs_per_package * self.pieces_per_inner_pack:
raise ValidationError({'pieces_per_package': 'Total pieces must equal inner packs times pieces per inner pack.'})
if self.piece_amount is not None:
raise ValidationError({'piece_amount': 'Nested packages derive piece weight from the inner-pack amount.'})
if self.inventory_unit == 'pieces':
if self.inner_pack_amount is not None:
raise ValidationError({'inner_pack_amount': 'Piece-only packages do not use a measured inner-pack amount.'})
elif self.inventory_unit in ('mg', 'g', 'kg', 'ml', 'L'):
if self.inner_pack_amount is None:
raise ValidationError({'inner_pack_amount': 'Enter the measured amount in one inner pack.'})
if self.original_amount != self.inner_pack_amount * self.inner_packs_per_package:
raise ValidationError({'original_amount': 'Outer package amount must equal inner-pack amount times inner packs.'})
full_packs, loose_pieces = divmod(self.remaining_pieces, self.pieces_per_inner_pack)
expected_remaining = self.inner_pack_amount * full_packs
if loose_pieces:
expected_remaining += (self.inner_pack_amount * loose_pieces / self.pieces_per_inner_pack).quantize(
Decimal('.001'), rounding=ROUND_HALF_UP)
if self.remaining_amount != expected_remaining:
raise ValidationError({'remaining_amount': 'Remaining amount must match the remaining whole pieces and inner packs.'})
if self.inner_packs_per_package > 1 and not self.inner_pack_label:
raise ValidationError({'inner_pack_label': 'Name the inner package unit (for example, packet).'})
if not self.piece_label:
raise ValidationError({'piece_label': 'Name the individual item (for example, biscuit).'})
elif self.inner_pack_amount is not None or self.inner_pack_label or self.piece_label:
raise ValidationError({'inner_packs_per_package': 'Enter nested package counts before adding inner-pack details.'})
if self.user_id and self.product_id and self.product.owner_id != self.user_id:
raise ValidationError({'product': 'Choose one of your own products.'})
if self.user_id and self.location_id and self.location.user_id != self.user_id:
@@ -235,13 +293,36 @@ class KitchenInventoryItem(models.Model):
return 'depleted'
return 'opened' if self.opened else 'unopened'
@property
def remaining_full_inner_packs(self):
if not self.pieces_per_inner_pack or self.remaining_pieces is None:
return 0
return self.remaining_pieces // self.pieces_per_inner_pack
@property
def opened_inner_pack_pieces(self):
if not self.pieces_per_inner_pack or self.remaining_pieces is None:
return 0
return self.remaining_pieces % self.pieces_per_inner_pack
@property
def remaining_inner_pack_balance(self):
if not self.inner_packs_per_package:
return ''
parts = []
if self.remaining_full_inner_packs:
parts.append(f'{self.remaining_full_inner_packs} unopened {self.inner_pack_label or "inner pack"}{"s" if self.remaining_full_inner_packs != 1 else ""}')
if self.opened_inner_pack_pieces:
parts.append(f'1 opened {self.inner_pack_label or "inner pack"} with {self.opened_inner_pack_pieces} {self.piece_label or "piece"}{"s" if self.opened_inner_pack_pieces != 1 else ""} left')
return ' + '.join(parts) if parts else 'no inner packs remaining'
class InventoryConsumption(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
product = models.ForeignKey(FoodProduct, on_delete=models.PROTECT)
amount = models.DecimalField(max_digits=10, decimal_places=3, validators=POSITIVE)
unit = models.CharField(max_length=8)
unit = models.CharField(max_length=16)
source = models.CharField(max_length=16, choices=[('manual', 'Manual'), ('mcp', 'MCP'), ('recipe', 'Recipe')])
source_reference = models.CharField(max_length=255, blank=True)
description = models.CharField(max_length=255, blank=True)
@@ -263,6 +344,8 @@ class InventoryConsumptionLine(models.Model):
after_amount = models.DecimalField(max_digits=10, decimal_places=3)
before_opened = models.BooleanField(default=False)
before_opened_at = models.DateTimeField(null=True, blank=True)
before_pieces = models.PositiveIntegerField(null=True, blank=True)
after_pieces = models.PositiveIntegerField(null=True, blank=True)
class PersonalAccessToken(models.Model):
@@ -297,3 +380,127 @@ class ApiIdempotencyRecord(models.Model):
class Meta:
constraints = [models.UniqueConstraint(fields=('token', 'key'), name='food_unique_api_idempotency_key')]
class InventoryScanRun(models.Model):
"""A resumable scan-in session, including batches submitted while scanning continues."""
class Status(models.TextChoices):
ACTIVE = 'active', 'Active'
PROCESSING = 'processing', 'Processing'
COMPLETE = 'complete', 'Complete'
COMPLETE_WITH_REVIEW = 'complete_with_review', 'Complete with review'
CANCELLED = 'cancelled', 'Cancelled'
api_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='inventory_scan_runs')
status = models.CharField(max_length=24, choices=Status.choices, default=Status.ACTIVE, db_index=True)
selected_location = models.ForeignKey(InventoryLocation, on_delete=models.SET_NULL, null=True, blank=True,
related_name='active_scan_runs')
created_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
completed_at = models.DateTimeField(null=True, blank=True)
notification_attempted_at = models.DateTimeField(null=True, blank=True)
notification_sent_at = models.DateTimeField(null=True, blank=True)
notification_error = models.CharField(max_length=255, blank=True)
class Meta:
indexes = [models.Index(fields=('user', 'status', '-created_at'), name='food_scan_run_user_status')]
constraints = [models.UniqueConstraint(fields=('user',), condition=Q(status='active'),
name='food_one_active_scan_run')]
class InventoryScanBatch(models.Model):
"""A location-specific portion of a run. Save & next closes one and opens another."""
class Status(models.TextChoices):
DRAFT = 'draft', 'Draft'
QUEUED = 'queued', 'Queued'
COMPLETE = 'complete', 'Complete'
run = models.ForeignKey(InventoryScanRun, on_delete=models.CASCADE, related_name='batches')
location = models.ForeignKey(InventoryLocation, on_delete=models.PROTECT, related_name='scan_batches')
sequence = models.PositiveIntegerField()
status = models.CharField(max_length=12, choices=Status.choices, default=Status.DRAFT, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
submitted_at = models.DateTimeField(null=True, blank=True)
completed_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('sequence',)
constraints = [
models.UniqueConstraint(fields=('run', 'sequence'), name='food_unique_scan_batch_sequence'),
models.UniqueConstraint(fields=('run',), condition=Q(status='draft'), name='food_one_draft_scan_batch'),
]
class InventoryScanItem(models.Model):
"""A persisted scan entry that becomes its own retryable enrichment job on submit."""
class Status(models.TextChoices):
ACTIVE = 'active', 'Active scan'
CONFIRMED = 'confirmed', 'Confirmed'
QUEUED = 'queued', 'Queued'
PROCESSING = 'processing', 'Processing'
NEEDS_REVIEW = 'needs_review', 'Needs review'
COMPLETE = 'complete', 'Complete'
DEFERRED = 'deferred', 'Deferred'
FAILED = 'failed', 'Failed'
batch = models.ForeignKey(InventoryScanBatch, on_delete=models.CASCADE, related_name='items')
location = models.ForeignKey(InventoryLocation, on_delete=models.PROTECT, related_name='scan_items')
barcode = models.CharField(max_length=64, db_index=True)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.ACTIVE, db_index=True)
package_count = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])
package_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
package_unit = models.CharField(max_length=8, blank=True)
pieces_per_package = models.PositiveIntegerField(null=True, blank=True)
piece_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inner_packs_per_package = models.PositiveIntegerField(null=True, blank=True)
pieces_per_inner_pack = models.PositiveIntegerField(null=True, blank=True)
inner_pack_amount = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True, validators=POSITIVE)
inner_pack_label = models.CharField(max_length=40, blank=True)
piece_label = models.CharField(max_length=40, blank=True)
product_name = models.CharField(max_length=255, blank=True)
brand = models.CharField(max_length=255, blank=True)
category_name = models.CharField(max_length=100, blank=True)
notes = models.TextField(blank=True)
best_before = models.DateField(null=True, blank=True)
opened = models.BooleanField(default=False)
source_data = models.JSONField(default=dict, blank=True)
user_data = models.JSONField(default=dict, blank=True)
product = models.ForeignKey(FoodProduct, on_delete=models.SET_NULL, null=True, blank=True,
related_name='scan_items')
inventory_item = models.ForeignKey(KitchenInventoryItem, on_delete=models.SET_NULL, null=True, blank=True,
related_name='scan_items')
attempts = models.PositiveSmallIntegerField(default=0)
next_attempt_at = models.DateTimeField(null=True, blank=True, db_index=True)
lease_until = models.DateTimeField(null=True, blank=True, db_index=True)
last_error = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
confirmed_at = models.DateTimeField(null=True, blank=True)
completed_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ('created_at', 'pk')
indexes = [models.Index(fields=('status', 'next_attempt_at'), name='food_scan_item_due')]
class OpenFoodFactsRequest(models.Model):
"""A durable timestamp for each actual OFF HTTP request; shared by web and worker processes."""
requested_at = models.DateTimeField(db_index=True)
endpoint = models.CharField(max_length=24, blank=True)
class OpenFoodFactsRateLimit(models.Model):
"""A single database lock row coordinates request reservations across processes."""
id = models.PositiveSmallIntegerField(primary_key=True, default=1, editable=False)
updated_at = models.DateTimeField(auto_now=True)
class InventoryReviewPreference(models.Model):
class Mode(models.TextChoices):
INDIVIDUAL = 'individual', 'Individual'
BULK = 'bulk', 'Bulk'
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='inventory_review_preference')
mode = models.CharField(max_length=12, choices=Mode.choices, default=Mode.INDIVIDUAL)
updated_at = models.DateTimeField(auto_now=True)
+283
View File
@@ -0,0 +1,283 @@
import json
from django.contrib.auth.decorators import login_required
from django.db.models import Prefetch
from django.http import JsonResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.template.loader import render_to_string
from django.urls import reverse
from django.views.decorators.http import require_GET, require_http_methods, require_POST
from .models import (InventoryLocation, InventoryScanBatch, InventoryScanItem,
InventoryReviewPreference, InventoryScanRun)
from .services.inventory_scanner import (ScanWorkflowError, adjust_confirmed_count,
approve_scan_item, approve_scan_items, 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)
@login_required
def scanner(request):
run = resume_active_run(request.user)
draft_batch = run.batches.filter(status=InventoryScanBatch.Status.DRAFT).first() if run else None
active_item = draft_batch.items.filter(status=InventoryScanItem.Status.ACTIVE).first() if draft_batch else None
queued_count = sum(batch.items.exclude(status=InventoryScanItem.Status.ACTIVE).count()
for batch in run.batches.all()) if run else 0
queue_batches = _queue_batches(run) if run else []
return render(request, 'food/inventory_scanner.html', {
'run': run, 'draft_batch': draft_batch, 'active_item': active_item,
'locations': InventoryLocation.objects.filter(user=request.user), 'queued_count': queued_count,
'queue_batches': queue_batches,
})
@login_required
@require_POST
def start_run(request):
try:
run = get_or_create_active_run(request.user, request.POST.get('location_id'))
except (ScanWorkflowError, TypeError, ValueError) as error:
return render(request, 'food/inventory_scanner.html', {
'locations': InventoryLocation.objects.filter(user=request.user), 'start_error': str(error),
}, status=400)
return redirect('food:scanner-inventory')
@login_required
@require_POST
def create_scan(request, run_id):
run = get_object_or_404(InventoryScanRun, api_id=run_id, user=request.user,
status=InventoryScanRun.Status.ACTIVE)
payload, error = _payload(request)
if error:
return JsonResponse({'error': error}, status=400)
try:
item = create_active_scan(run, request.user, str(payload.get('barcode', '')).strip())
except ScanWorkflowError as error:
return JsonResponse({'error': str(error)}, status=400)
if item.status == InventoryScanItem.Status.CONFIRMED:
return JsonResponse({'incremented': True, 'item': _item_json(item)})
html = render_to_string('food/partials/inventory_scan_active.html', {
'item': item, 'locations': InventoryLocation.objects.filter(user=request.user),
}, request=request)
return JsonResponse({'item': _item_json(item), 'existing': bool(item.source_data.get('cached')), 'html': html})
@login_required
@require_POST
def confirm_scan(request, item_id):
payload, error = _payload(request)
if error:
return JsonResponse({'error': error}, status=400)
payload['opened'] = str(payload.get('opened', '')).lower() in {'true', '1', 'yes', 'on'}
try:
item = confirm_scan_item(request.user, item_id, payload)
except (ScanWorkflowError, TypeError, ValueError) as error:
return JsonResponse({'error': str(error)}, status=400)
return JsonResponse({'item': _item_json(item)})
@login_required
@require_POST
def discard_scan(request, item_id):
try:
discard_active_scan(request.user, item_id)
except ScanWorkflowError as error:
return JsonResponse({'error': str(error)}, status=400)
return JsonResponse({'ok': True})
@login_required
@require_POST
def adjust_scan_count(request, item_id):
payload, error = _payload(request)
if error:
return JsonResponse({'error': error}, status=400)
try:
item = adjust_confirmed_count(request.user, item_id, int(payload.get('delta', 0)))
except (ScanWorkflowError, TypeError, ValueError) as error:
return JsonResponse({'error': str(error)}, status=400)
return JsonResponse({'ok': True, 'deleted': item is None,
'item': _item_json(item) if item else None})
@login_required
@require_POST
def submit_scan_batch(request, batch_id):
payload, error = _payload(request)
if error:
return JsonResponse({'error': error}, status=400)
finish = str(payload.get('finish', '')).lower() in {'true', '1', 'yes', 'on'}
try:
run = submit_batch(request.user, batch_id=batch_id,
next_location_id=payload.get('next_location_id'), finish=finish)
except (ScanWorkflowError, TypeError, ValueError) as error:
return JsonResponse({'error': str(error)}, status=400)
if finish:
return JsonResponse({'ok': True, 'redirect': reverse('food:inventory')})
next_batch = run.batches.get(status=InventoryScanBatch.Status.DRAFT)
return JsonResponse({'ok': True, 'batch_id': next_batch.pk,
'location_id': next_batch.location_id, 'location': next_batch.location.name,
'submit_url': reverse('food:inventory-scan-submit', args=[next_batch.pk]),
'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
@require_GET
def scan_queue(request, run_id):
run = get_object_or_404(InventoryScanRun, api_id=run_id, user=request.user)
batches = _queue_batches(run)
return render(request, 'food/partials/inventory_scan_queue.html', {'run': run, 'batches': batches})
@login_required
@require_http_methods(['GET', 'POST'])
def inventory_review(request):
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
mode = preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL
if request.method == 'POST' and request.POST.get('action') == 'mode':
try:
preference = update_review_preference(request.user, request.POST.get('mode'))
except ScanWorkflowError as error:
return JsonResponse({'error': str(error)}, status=400)
suffix = f"?mode={preference.mode}"
if request.POST.get('state') in ('processing', 'deferred'):
suffix += f"&state={request.POST['state']}"
return redirect(f"{reverse('food:inventory-review')}{suffix}")
if request.GET.get('mode') in InventoryReviewPreference.Mode.values:
mode = request.GET['mode']
requested_state = request.GET.get('state') or request.POST.get('state')
state = requested_state if requested_state in ('processing', 'deferred') else 'review'
statuses = ((InventoryScanItem.Status.QUEUED, InventoryScanItem.Status.PROCESSING)
if state == 'processing' else
(InventoryScanItem.Status.DEFERRED,) if state == 'deferred' else
(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.FAILED))
items = (InventoryScanItem.objects.filter(batch__run__user=request.user, status__in=statuses)
.select_related('location', 'product', 'batch__run').order_by('created_at'))
context = {'mode': mode, 'items': items,
'locations': InventoryLocation.objects.filter(user=request.user),
'review_count': items.count(), 'state': state,
'eligible_bulk_count': items.exclude(product_name='').count(),
'approved_count': request.GET.get('approved', ''),
'deferred_count': InventoryScanItem.objects.filter(batch__run__user=request.user,
status=InventoryScanItem.Status.DEFERRED).count()}
if request.method == 'POST' and request.POST.get('action') == 'preview':
selected_ids = request.POST.getlist('item_ids')
selected = list(items.filter(pk__in=selected_ids))
shared_location = InventoryLocation.objects.filter(user=request.user,
pk=request.POST.get('location_id')).first() if request.POST.get('location_id') else None
context.update({'preview_items': selected, 'selected_ids': [str(item.pk) for item in selected],
'shared_location_id': request.POST.get('location_id', ''),
'shared_location_name': shared_location.name if shared_location else '',
'shared_category': request.POST.get('category_name', ''), 'preview': True})
elif request.method == 'POST' and request.POST.get('action') == 'approve':
selected_ids = request.POST.getlist('item_ids')
try:
approve_scan_items(request.user, selected_ids, {
'location_id': request.POST.get('location_id'),
'category_name': request.POST.get('category_name'),
})
except (ScanWorkflowError, TypeError, ValueError) as error:
context['review_error'] = str(error)
else:
return redirect(f"{reverse('food:inventory-review')}?mode=bulk&approved={len(set(selected_ids))}")
return render(request, 'food/inventory_review.html', context)
@login_required
@require_http_methods(['GET', 'POST'])
def review_item(request, item_id):
item = get_object_or_404(InventoryScanItem.objects.select_related('batch__run', 'product', 'location'),
pk=item_id, batch__run__user=request.user,
status__in=(InventoryScanItem.Status.NEEDS_REVIEW, InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED))
locations = InventoryLocation.objects.filter(user=request.user)
nutrient_fields = ('energy_kcal_100', 'fat_100', 'saturated_fat_100', 'carbohydrates_100',
'sugars_100', 'protein_100', 'salt_100', 'fibre_100')
values = {'product_name': item.product_name, 'brand': item.brand,
'package_count': item.package_count,
'package_amount': str(item.package_amount) if item.package_amount is not None else '',
'package_unit': item.package_unit, 'category_name': item.category_name,
'notes': item.notes, 'location_id': item.location_id}
if item.product:
values.update({field: str(getattr(item.product, field)) if getattr(item.product, field) is not None else ''
for field in nutrient_fields})
else:
values.update({field: (item.source_data.get('nutrition', {}).get(field) or '')
for field in nutrient_fields})
nutrients = [{'field': field, 'label': field.removesuffix('_100').replace('_', ' ').title(),
'value': values[field]} for field in nutrient_fields]
error = ''
if request.method == 'POST':
values.update({key: request.POST.get(key, '') for key in (
'product_name', 'brand', 'package_count', 'package_amount', 'package_unit',
'category_name', 'notes', 'location_id', *nutrient_fields)})
intent = request.POST.get('action')
try:
if intent == 'defer':
save_review_item(request.user, item.pk, values)
defer_scan_item(request.user, item.pk)
return redirect('food:inventory-review')
if intent == 'approve':
approve_scan_item(request.user, item.pk, values)
return redirect('food:inventory-review')
if intent in ('save', 'mode'):
save_review_item(request.user, item.pk, values)
if intent == 'mode':
preference = update_review_preference(request.user, request.POST.get('mode'))
return redirect(f"{reverse('food:inventory-review')}?mode={preference.mode}")
item.refresh_from_db()
values['saved'] = True
except (ScanWorkflowError, TypeError, ValueError, InventoryLocation.DoesNotExist) as exc:
error = str(exc)
preference = InventoryReviewPreference.objects.filter(user=request.user).first()
return render(request, 'food/inventory_review_item.html', {
'item': item, 'locations': locations, 'values': values, 'error': error,
'nutrition_fields': nutrient_fields, 'nutrients': nutrients,
'mode': preference.mode if preference else InventoryReviewPreference.Mode.INDIVIDUAL,
})
def _queue_batches(run):
batches = list(run.batches.select_related('location').prefetch_related(Prefetch(
'items', queryset=InventoryScanItem.objects.exclude(status=InventoryScanItem.Status.ACTIVE)
.select_related('location', 'product'), to_attr='queue_items')).all())
return batches
def _payload(request):
if request.content_type == 'application/json':
try:
payload = json.loads(request.body or b'{}')
if not isinstance(payload, dict):
return {}, 'Invalid request body.'
return payload, None
except (json.JSONDecodeError, UnicodeDecodeError):
return {}, 'Invalid request body.'
return request.POST.dict(), None
def _item_json(item):
return {
'id': item.pk, 'barcode': item.barcode, 'status': item.status,
'product_name': item.product_name, 'brand': item.brand,
'package_count': item.package_count,
'package_amount': str(item.package_amount) if item.package_amount is not None else '',
'package_unit': item.package_unit, 'location_id': item.location_id,
'location': item.location.name, 'cached': bool(item.source_data.get('cached')),
}
+109 -10
View File
@@ -1,7 +1,7 @@
"""Atomic package allocation shared by the web inventory and MCP API."""
import hashlib
from decimal import Decimal, InvalidOperation
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from django.contrib.auth import get_user_model
from django.db import transaction
@@ -13,7 +13,8 @@ from food.models import FoodProduct, InventoryConsumption, InventoryConsumptionL
FACTORS = {'mg': ('mass', Decimal('.001')), 'g': ('mass', Decimal(1)),
'kg': ('mass', Decimal(1000)), 'ml': ('volume', Decimal(1)),
'L': ('volume', Decimal(1000)), 'pieces': ('pieces', Decimal(1)),
'packs': ('packs', Decimal(1)), 'portions': ('portions', Decimal(1))}
'packs': ('packs', Decimal(1)), 'inner_packs': ('inner_packs', Decimal(1)),
'portions': ('portions', Decimal(1))}
class StockError(ValueError):
@@ -44,6 +45,31 @@ def _package_stock(item):
return item.remaining_amount * FACTORS[unit][1], FACTORS[unit][0], unit
def _nested_amount_for_pieces(item, piece_count):
"""Return the rounded package-unit balance implied by whole nested pieces."""
full_packs, loose_pieces = divmod(piece_count, item.pieces_per_inner_pack)
amount = item.inner_pack_amount * full_packs
if loose_pieces:
amount += (item.inner_pack_amount * loose_pieces / item.pieces_per_inner_pack).quantize(
Decimal('.001'), rounding=ROUND_HALF_UP)
return amount
def _nested_count_for_amount(item, remaining_amount):
"""Find an exact whole-piece balance for a measured remainder."""
low, high = 0, item.remaining_pieces
while low < high:
middle = (low + high) // 2
if _nested_amount_for_pieces(item, middle) < remaining_amount:
low = middle + 1
else:
high = middle
for candidate in (low, low - 1):
if 0 <= candidate <= item.remaining_pieces and _nested_amount_for_pieces(item, candidate) == remaining_amount:
return candidate
raise StockError('This measured amount does not match a whole number of nested pieces.')
def stock(user, product, location_id=None, lock=False):
if product.owner_id != user.pk:
raise StockError('Product not found.')
@@ -57,6 +83,10 @@ def stock(user, product, location_id=None, lock=False):
def materialize_packages(item):
"""Turn a newly added count into separate packages when a size is known."""
if item.original_amount is None and item.pieces_per_package is not None:
item.original_amount = Decimal(item.pieces_per_package)
item.remaining_amount = Decimal(item.remaining_pieces)
item.inventory_unit = 'pieces'
if item.original_amount is None and item.product.package_amount and item.product.package_unit:
item.original_amount = item.product.package_amount
item.remaining_amount = item.product.package_amount
@@ -71,7 +101,12 @@ def materialize_packages(item):
KitchenInventoryItem.objects.create(user=item.user, product=item.product, quantity=1,
location=item.location, category=item.category, notes=item.notes, opened=False,
original_amount=item.original_amount, remaining_amount=item.original_amount,
inventory_unit=item.inventory_unit, best_before=item.best_before,
inventory_unit=item.inventory_unit, pieces_per_package=item.pieces_per_package,
remaining_pieces=item.pieces_per_package, piece_amount=item.piece_amount,
inner_packs_per_package=item.inner_packs_per_package,
pieces_per_inner_pack=item.pieces_per_inner_pack, inner_pack_amount=item.inner_pack_amount,
inner_pack_label=item.inner_pack_label, piece_label=item.piece_label,
best_before=item.best_before,
purchase_batch=item.purchase_batch)
return item
@@ -84,10 +119,22 @@ def preview(user, product, amount, unit, package_id=None, location_id=None, lock
if not items:
raise StockError('Package not found.')
compatible = []
missing_piece_amount = False
for item in items:
available, kind, native_unit = _package_stock(item)
if dimension == 'inner_packs' and item.inner_packs_per_package:
available = Decimal(item.remaining_pieces // item.pieces_per_inner_pack)
kind = 'inner_packs'
if dimension == 'pieces' and item.pieces_per_package is not None:
if item.inner_packs_per_package is None and kind != 'pieces' and item.piece_amount is None:
missing_piece_amount = True
continue
available = Decimal(item.remaining_pieces)
kind = 'pieces'
if kind == dimension and available > 0:
compatible.append((item, available, native_unit))
if not compatible and missing_piece_amount:
raise StockError('Set an explicit amount per piece before consuming this weighed package by pieces.')
compatible.sort(key=lambda row: (not row[0].opened, row[0].best_before is None,
row[0].best_before or timezone.datetime.max.date(),
row[0].added_at, row[0].pk))
@@ -98,10 +145,56 @@ def preview(user, product, amount, unit, package_id=None, location_id=None, lock
if left <= 0:
break
take = min(left, available)
native = take / FACTORS[native_unit][1]
native_factor = FACTORS[native_unit][1]
before_native = item.remaining_amount if item.remaining_amount is not None else Decimal(item.quantity)
before_pieces = item.remaining_pieces
after_pieces = before_pieces
if item.inner_packs_per_package is not None and dimension in ('pieces', 'inner_packs'):
piece_count = int(take) * (item.pieces_per_inner_pack if dimension == 'inner_packs' else 1)
after_pieces = before_pieces - piece_count
native = before_native - _nested_amount_for_pieces(item, after_pieces)
elif dimension == 'pieces' and FACTORS[native_unit][0] != 'pieces':
native = item.piece_amount * take
if take == item.remaining_pieces:
native = before_native # The last piece takes the precise residual.
elif native > before_native:
raise StockError('The amount per piece exceeds remaining package stock.')
else:
native = take / native_factor
if before_pieces is not None and item.inner_packs_per_package is None:
if dimension == 'pieces':
after_pieces -= int(take)
elif take == available:
after_pieces = 0
elif item.piece_amount is None:
raise StockError('Set an explicit amount per piece before partially consuming measured stock.')
else:
piece_count = native / item.piece_amount
if piece_count != piece_count.to_integral_value():
raise StockError('This amount does not correspond to whole pieces at the configured amount per piece.')
if piece_count > before_pieces:
raise StockError('The amount exceeds the remaining piece count.')
after_pieces -= int(piece_count)
elif before_pieces is not None and item.inner_packs_per_package is not None and dimension not in ('pieces', 'inner_packs'):
after_pieces = 0 if take == available else _nested_count_for_amount(item, before_native - native)
if native != native.quantize(Decimal('.001')):
raise StockError('The piece conversion needs more than three decimal places; use a measured amount instead.')
nested_balance = None
if item.inner_packs_per_package is not None:
full_inner, loose = divmod(after_pieces, item.pieces_per_inner_pack)
balance = []
if full_inner:
label = item.inner_pack_label or 'inner pack'
balance.append(f'{full_inner} unopened {label}{"s" if full_inner != 1 else ""}')
if loose:
label = item.inner_pack_label or 'inner pack'
piece_label = item.piece_label or 'piece'
balance.append(f'1 opened {label} with {loose} {piece_label}{"s" if loose != 1 else ""} left')
nested_balance = ' + '.join(balance) if balance else 'no inner packs remaining'
deductions.append({'package': item, 'amount': native, 'unit': native_unit,
'before': available / FACTORS[native_unit][1],
'after': (available - take) / FACTORS[native_unit][1]})
'before': before_native, 'after': before_native - native,
'before_pieces': before_pieces, 'after_pieces': after_pieces,
'after_inner_pack_balance': nested_balance})
left -= take
factor = FACTORS[unit][1]
return {'requested': requested / factor, 'unit': unit, 'total': total / factor,
@@ -141,16 +234,18 @@ def consume(user, product, amount, unit, *, package_id=None, source='manual',
item.quantity = int(deduction['after']) or 1
else:
item.remaining_amount = deduction['after']
item.remaining_pieces = deduction['after_pieces']
if deduction['after'] == 0:
item.archived_at = timezone.now()
elif not item.opened:
item.opened = True
item.opened_at = timezone.now()
item.save(update_fields=('quantity', 'remaining_amount', 'opened', 'opened_at', 'archived_at', 'updated_at'))
item.save(update_fields=('quantity', 'remaining_amount', 'remaining_pieces', 'opened', 'opened_at', 'archived_at', 'updated_at'))
InventoryConsumptionLine.objects.create(transaction=operation, package=item,
amount=deduction['amount'], unit=deduction['unit'], before_amount=deduction['before'],
after_amount=deduction['after'], before_opened=before_opened,
before_opened_at=before_opened_at)
before_opened_at=before_opened_at, before_pieces=deduction['before_pieces'],
after_pieces=deduction['after_pieces'])
return operation
@@ -167,6 +262,8 @@ def undo(user, operation_id):
Decimal(0) if item.original_amount is None else item.remaining_amount)
if current != line.after_amount:
raise StockError('Package changed since this consumption. Undo it in reverse order.')
if item.remaining_pieces != line.after_pieces:
raise StockError('Piece count changed since this consumption. Undo it in reverse order.')
if item.archived_at is not None and line.after_amount != 0:
raise StockError('Package was removed after this consumption.')
reversal = InventoryConsumption.objects.create(user=user, product=operation.product,
@@ -178,10 +275,12 @@ def undo(user, operation_id):
item.quantity = int(line.before_amount)
else:
item.remaining_amount = line.before_amount
item.remaining_pieces = line.before_pieces
item.archived_at = None
item.opened, item.opened_at = line.before_opened, line.before_opened_at
item.save(update_fields=('quantity', 'remaining_amount', 'archived_at', 'opened', 'opened_at', 'updated_at'))
item.save(update_fields=('quantity', 'remaining_amount', 'remaining_pieces', 'archived_at', 'opened', 'opened_at', 'updated_at'))
InventoryConsumptionLine.objects.create(transaction=reversal, package=item,
amount=line.amount, unit=line.unit, before_amount=line.after_amount,
after_amount=line.before_amount)
after_amount=line.before_amount, before_pieces=line.after_pieces,
after_pieces=line.before_pieces)
return reversal
+693
View File
@@ -0,0 +1,693 @@
"""Persistent scan-in session and enrichment queue services."""
from datetime import timedelta
from decimal import Decimal, InvalidOperation
import random
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,
InventoryScanItem, InventoryScanRun,
KitchenInventoryItem)
from food.services.openfoodfacts import (OpenFoodFactsError,
OpenFoodFactsTransientError,
cached_product)
class ScanWorkflowError(ValueError):
pass
def get_or_create_active_run(user, location_id):
location = InventoryLocation.objects.filter(user=user, pk=location_id).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
try:
with transaction.atomic():
run = (InventoryScanRun.objects.select_for_update().filter(
user=user, status=InventoryScanRun.Status.ACTIVE).order_by('-created_at').first())
if run:
draft = run.batches.filter(status=InventoryScanBatch.Status.DRAFT).first()
if not draft:
raise ScanWorkflowError('This scan session is being saved. Refresh and try again.')
run.selected_location = draft.location
return run
run = InventoryScanRun.objects.create(user=user, selected_location=location)
InventoryScanBatch.objects.create(run=run, location=location, sequence=1)
return run
except IntegrityError:
run = resume_active_run(user)
if run:
return run
raise
def resume_active_run(user):
return (InventoryScanRun.objects.filter(user=user, status=InventoryScanRun.Status.ACTIVE)
.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.')
with transaction.atomic():
locked = InventoryScanRun.objects.select_for_update().filter(
pk=run.pk, user=user, status=InventoryScanRun.Status.ACTIVE).first()
if not locked:
raise ScanWorkflowError('This scan session is no longer active.')
batch = locked.batches.select_for_update().filter(status=InventoryScanBatch.Status.DRAFT).first()
if not batch:
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:
values = {
'product_name': product.product_name, 'brand': product.brand,
'package_amount': product.package_amount, 'package_unit': product.package_unit,
'source_data': {'cached': True, 'source': product.source,
'nutrition': _product_nutrients(product)},
}
return InventoryScanItem.objects.create(batch=batch, location=batch.location,
barcode=barcode, **values)
def confirm_scan_item(user, item_id, values):
with transaction.atomic():
item = (InventoryScanItem.objects.select_for_update().select_related('batch__run')
.filter(pk=item_id, batch__run__user=user).first())
if not item or item.status != InventoryScanItem.Status.ACTIVE or item.batch.status != InventoryScanBatch.Status.DRAFT:
raise ScanWorkflowError('This scan can no longer be edited.')
location = InventoryLocation.objects.filter(user=user, pk=values.get('location_id')).first()
if not location:
raise ScanWorkflowError('Choose one of your existing inventory locations.')
item.location = location
item.product_name = str(values.get('product_name', item.product_name)).strip()[:255]
item.brand = str(values.get('brand', item.brand)).strip()[:255]
item.category_name = str(values.get('category_name', '')).strip()[:100]
item.notes = str(values.get('notes', '')).strip()[:4000]
item.package_count = _integer(values.get('package_count', 1), 'Enter a valid number of packages.', minimum=1, maximum=10000)
item.package_amount = _decimal_or_none(values.get('package_amount'), 'Enter a valid package size.')
item.package_unit = str(values.get('package_unit', '')).strip()[:8]
item.pieces_per_package = _integer_or_none(values.get('pieces_per_package'), 'Enter a valid number of pieces.', maximum=100000)
item.piece_amount = _decimal_or_none(values.get('piece_amount'), 'Enter a valid amount per piece.')
item.inner_packs_per_package = _integer_or_none(values.get('inner_packs_per_package'), 'Enter a valid number of inner packs.', maximum=100000)
item.pieces_per_inner_pack = _integer_or_none(values.get('pieces_per_inner_pack'), 'Enter a valid number of pieces per inner pack.', maximum=100000)
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]
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
item.confirmed_at = timezone.now()
item.save()
item.batch.run.selected_location = location
item.batch.run.save(update_fields=('selected_location',))
return item
def discard_active_scan(user, item_id):
deleted, _ = InventoryScanItem.objects.filter(pk=item_id, batch__run__user=user,
status=InventoryScanItem.Status.ACTIVE, batch__status=InventoryScanBatch.Status.DRAFT).delete()
if not deleted:
raise ScanWorkflowError('Only an unconfirmed active scan can be removed.')
def adjust_confirmed_count(user, item_id, delta):
if delta not in (-1, 1):
raise ScanWorkflowError('Invalid package adjustment.')
with transaction.atomic():
item = InventoryScanItem.objects.select_for_update().filter(pk=item_id, batch__run__user=user,
batch__status=InventoryScanBatch.Status.DRAFT, status=InventoryScanItem.Status.CONFIRMED).first()
if not item:
raise ScanWorkflowError('This queued item can no longer be changed.')
if item.package_count + delta < 1:
item.delete()
return None
item.package_count += delta
item.user_data = _item_data(item)
item.save(update_fields=('package_count', 'user_data'))
return item
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())
if not batch:
raise ScanWorkflowError('Scan batch not found.')
run = InventoryScanRun.objects.select_for_update().get(pk=batch.run_id)
if batch.status == InventoryScanBatch.Status.QUEUED:
return run
if run.status != InventoryScanRun.Status.ACTIVE or batch.status != InventoryScanBatch.Status.DRAFT:
raise ScanWorkflowError('This scan batch has already been submitted.')
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)
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()
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
run.save(update_fields=('status', 'submitted_at'))
else:
location = InventoryLocation.objects.filter(user=user, pk=next_location_id).first()
if not location:
raise ScanWorkflowError('Choose an existing location for the next batch.')
run.selected_location = location
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',))
run_id = run.pk
if finish:
_refresh_completion(run_id)
return InventoryScanRun.objects.get(pk=run_id)
def _claim_next_item():
now = timezone.now()
with transaction.atomic():
skip_locked = connections['default'].features.has_select_for_update_skip_locked
qs = InventoryScanItem.objects.select_for_update(skip_locked=skip_locked).filter(
Q(status=InventoryScanItem.Status.QUEUED, next_attempt_at__lte=now) |
Q(status=InventoryScanItem.Status.PROCESSING, lease_until__lt=now),
batch__status=InventoryScanBatch.Status.QUEUED,
batch__run__status__in=(InventoryScanRun.Status.ACTIVE, InventoryScanRun.Status.PROCESSING))
item = qs.select_related('batch__run__user').order_by('next_attempt_at', 'created_at', 'pk').first()
if not item:
return None
item.status = InventoryScanItem.Status.PROCESSING
item.lease_until = now + timedelta(minutes=15)
item.last_error = ''
item.save(update_fields=('status', 'lease_until', 'last_error'))
return item.pk
def process_next_scan_item():
item_id = _claim_next_item()
if not item_id:
return False
item = InventoryScanItem.objects.select_related('batch__run__user', 'location').get(pk=item_id)
product = FoodProduct.objects.filter(owner=item.batch.run.user, barcode=item.barcode).first()
try:
if not product:
def record_http_attempt():
InventoryScanItem.objects.filter(pk=item_id, status=InventoryScanItem.Status.PROCESSING).update(
attempts=F('attempts') + 1)
product = cached_product(item.batch.run.user, item.barcode, wait_for_slot=True,
on_request_start=record_http_attempt)
except OpenFoodFactsTransientError as error:
_retry_or_review(item_id, str(error), retry_after=error.retry_after)
_refresh_completion(item.batch.run_id)
return True
except OpenFoodFactsError as error:
_mark_needs_review(item_id, str(error))
_refresh_completion(item.batch.run_id)
return True
if not product:
_mark_needs_review(item_id, 'No product was found for this barcode. Enter product details to approve it.')
_refresh_completion(item.batch.run_id)
return True
with transaction.atomic():
current = InventoryScanItem.objects.select_for_update().select_related('batch__run').get(pk=item_id)
if current.status != InventoryScanItem.Status.PROCESSING:
return True
_populate_from_product(current, product)
current.product = product
if not current.product_name.strip() or not current.location_id or not _valid_stock_input(current):
current.status = InventoryScanItem.Status.NEEDS_REVIEW
current.last_error = 'Product identity or package details need review.'
current.completed_at = timezone.now()
current.lease_until = None
current.save()
else:
try:
stock = _create_inventory_stock(current, product)
except (ValidationError, ScanWorkflowError) as error:
current.status = InventoryScanItem.Status.NEEDS_REVIEW
current.last_error = str(error)[:255]
current.completed_at = timezone.now()
current.lease_until = None
current.save()
else:
current.status = InventoryScanItem.Status.COMPLETE
current.inventory_item = stock
current.completed_at = timezone.now()
current.lease_until = None
current.last_error = ''
current.save()
_refresh_completion(item.batch.run_id)
return True
def _retry_or_review(item_id, message, *, retry_after=None):
with transaction.atomic():
item = InventoryScanItem.objects.select_for_update().get(pk=item_id)
item.lease_until = None
item.last_error = message[:255]
item.refresh_from_db(fields=('attempts',))
if item.attempts >= 10:
item.status = InventoryScanItem.Status.NEEDS_REVIEW
item.completed_at = timezone.now()
else:
backoff = min(900, 5 * (2 ** max(0, item.attempts - 1)))
delay = max(backoff + random.uniform(0, backoff * 0.25), retry_after or 0)
item.status = InventoryScanItem.Status.QUEUED
item.next_attempt_at = timezone.now() + timedelta(seconds=delay)
item.save(update_fields=('status', 'lease_until', 'last_error', 'completed_at', 'next_attempt_at'))
def _mark_needs_review(item_id, message):
InventoryScanItem.objects.filter(pk=item_id, status=InventoryScanItem.Status.PROCESSING).update(
status=InventoryScanItem.Status.NEEDS_REVIEW, last_error=message[:255], completed_at=timezone.now(), lease_until=None)
def _populate_from_product(item, product):
if not item.product_name:
item.product_name = product.product_name
if not item.brand:
item.brand = product.brand
if item.package_amount is None and product.package_amount is not None:
item.package_amount = product.package_amount
item.package_unit = product.package_unit
item.source_data = {
'source': product.source,
'fetched_at': product.fetched_at.isoformat() if product.fetched_at else None,
'product_name': product.product_name,
'brand': product.brand,
'package_quantity': product.package_quantity,
'image_url': product.image_url,
'nutrition': _product_nutrients(product),
'raw_data': product.raw_data if isinstance(product.raw_data, dict) else {},
}
item.user_data = _item_data(item)
def _create_inventory_stock(item, product):
package_amount = item.package_amount
package_unit = item.package_unit
pieces = item.pieces_per_package
if pieces and package_amount is None and not package_unit:
package_amount, package_unit = Decimal(pieces), 'pieces'
if pieces and item.inner_packs_per_package and item.pieces_per_inner_pack:
if package_amount is None and item.inner_pack_amount is not None:
package_amount = item.inner_pack_amount * item.inner_packs_per_package
if package_unit and package_unit not in {'mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'}:
raise ScanWorkflowError('Choose a supported package unit.')
category = None
if item.category_name:
category, _ = InventoryCategory.objects.get_or_create(user=item.batch.run.user,
name__iexact=item.category_name, defaults={'name': item.category_name})
base = KitchenInventoryItem(
user=item.batch.run.user, product=product, location=item.location,
category=category, quantity=item.package_count if package_amount is None else 1,
notes=item.notes, opened=item.opened, best_before=item.best_before,
original_amount=package_amount, remaining_amount=package_amount,
inventory_unit=package_unit, pieces_per_package=pieces,
remaining_pieces=pieces, piece_amount=item.piece_amount,
inner_packs_per_package=item.inner_packs_per_package,
pieces_per_inner_pack=item.pieces_per_inner_pack,
inner_pack_amount=item.inner_pack_amount, inner_pack_label=item.inner_pack_label,
piece_label=item.piece_label,
)
base.full_clean()
base.save()
if package_amount is None:
return base
for _ in range(item.package_count - 1):
package = KitchenInventoryItem(
user=base.user, product=base.product, location=base.location,
category=base.category, quantity=1, notes=base.notes, opened=base.opened,
best_before=base.best_before, original_amount=base.original_amount,
remaining_amount=base.original_amount, inventory_unit=base.inventory_unit,
pieces_per_package=base.pieces_per_package, remaining_pieces=base.pieces_per_package,
piece_amount=base.piece_amount, inner_packs_per_package=base.inner_packs_per_package,
pieces_per_inner_pack=base.pieces_per_inner_pack, inner_pack_amount=base.inner_pack_amount,
inner_pack_label=base.inner_pack_label, piece_label=base.piece_label,
)
package.full_clean()
package.save()
return base
def _valid_stock_input(item):
if item.package_amount is None and not item.pieces_per_package:
return True # Count-only packages have unknown size by design.
if item.package_amount is not None and item.package_unit:
return True
return bool(item.inner_packs_per_package and item.pieces_per_inner_pack and
item.inner_pack_amount and item.package_unit)
def _refresh_completion(run_id):
with transaction.atomic():
run = InventoryScanRun.objects.select_for_update().get(pk=run_id)
for batch in run.batches.filter(status=InventoryScanBatch.Status.QUEUED):
if not batch.items.filter(status__in=(InventoryScanItem.Status.QUEUED, InventoryScanItem.Status.PROCESSING)).exists():
batch.status = InventoryScanBatch.Status.COMPLETE
batch.completed_at = timezone.now()
batch.save(update_fields=('status', 'completed_at'))
if run.status == InventoryScanRun.Status.PROCESSING and not run.batches.filter(
status=InventoryScanBatch.Status.QUEUED).exists():
review = run.batches.filter(items__status__in=(InventoryScanItem.Status.NEEDS_REVIEW,
InventoryScanItem.Status.DEFERRED,
InventoryScanItem.Status.FAILED)).exists()
run.status = (InventoryScanRun.Status.COMPLETE_WITH_REVIEW if review
else InventoryScanRun.Status.COMPLETE)
run.completed_at = timezone.now()
run.save(update_fields=('status', 'completed_at'))
if run.status in (InventoryScanRun.Status.COMPLETE, InventoryScanRun.Status.COMPLETE_WITH_REVIEW):
_send_completion_notification(run_id)
def _send_completion_notification(run_id):
from planner.services.notifications import NotificationError, send_notification
now = timezone.now()
with transaction.atomic():
run = InventoryScanRun.objects.select_for_update().select_related('user').get(pk=run_id)
if run.notification_sent_at or run.status not in (
InventoryScanRun.Status.COMPLETE, InventoryScanRun.Status.COMPLETE_WITH_REVIEW):
return
retry_window = timedelta(seconds=60)
if run.notification_attempted_at and run.notification_attempted_at > now - retry_window:
return
from django.db.models import Count
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))
failed = tallies.get(InventoryScanItem.Status.FAILED, 0)
run.notification_attempted_at = now
run.notification_error = ''
run.save(update_fields=('notification_attempted_at', 'notification_error'))
user = run.user
url = '/food/inventory/#inventory-review'
message = f'Bulk scan finished: {succeeded} added, {review} need review, {failed} failed. {url}'
try:
sent = send_notification(user, 'Kitchen inventory scan complete', message,
sequence_id=f'inventory-scan-{run.api_id}')
except NotificationError as error:
InventoryScanRun.objects.filter(pk=run_id).update(notification_error=str(error)[:255])
return
if sent:
InventoryScanRun.objects.filter(pk=run_id).update(notification_sent_at=timezone.now(), notification_error='')
else:
InventoryScanRun.objects.filter(pk=run_id).update(notification_error='ntfy notifications are not enabled')
def dispatch_pending_scan_notifications(limit=50):
"""Retry completed-run notifications after a short persisted delivery cooldown."""
cutoff = timezone.now() - timedelta(seconds=60)
run_ids = InventoryScanRun.objects.filter(
status__in=(InventoryScanRun.Status.COMPLETE, InventoryScanRun.Status.COMPLETE_WITH_REVIEW),
notification_sent_at__isnull=True).exclude(notification_error='ntfy notifications are not enabled').filter(
Q(notification_attempted_at__isnull=True) | Q(notification_attempted_at__lte=cutoff)
).order_by('completed_at').values_list('pk', flat=True)[:limit]
for run_id in run_ids:
_send_completion_notification(run_id)
def update_review_preference(user, mode):
if mode not in InventoryReviewPreference.Mode.values:
raise ScanWorkflowError('Choose Individual or Bulk review.')
preference, _ = InventoryReviewPreference.objects.update_or_create(user=user, defaults={'mode': mode})
return preference
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,
InventoryScanItem.Status.FAILED)).first())
if not item:
raise ScanWorkflowError('This staged item is no longer awaiting review.')
if values.get('product_name'):
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)
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()
if not product:
product = FoodProduct.objects.create(owner=user, barcode=item.barcode,
product_name=item.product_name, brand=item.brand,
package_quantity=(f'{item.package_amount} {item.package_unit}' if item.package_amount else ''),
package_amount=item.package_amount, package_unit=item.package_unit,
source=FoodProduct.Source.MANUAL, raw_data={'scan_item_id': item.pk, 'manual_nutrition_override': True})
elif product.source == FoodProduct.Source.MANUAL:
product.product_name = item.product_name
product.brand = item.brand
product.save(update_fields=('product_name', 'brand', 'updated_at'))
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.')
stock = _create_inventory_stock(item, product)
item.status = InventoryScanItem.Status.COMPLETE
item.inventory_item = stock
item.last_error = ''
item.completed_at = timezone.now()
item.save()
_refresh_completion(item.batch.run_id)
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__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):
# 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
product.package_unit = item.package_unit or product.package_unit
product.save(update_fields=('product_name', 'brand', 'package_amount', 'package_unit', 'updated_at'))
def _product_nutrients(product):
return {field: str(getattr(product, field)) if getattr(product, field) is not None else None
for field in ('energy_kcal_100', 'fat_100', 'saturated_fat_100', 'carbohydrates_100',
'sugars_100', 'protein_100', 'salt_100', 'fibre_100')}
def _item_data(item):
return {'product_name': item.product_name, 'brand': item.brand, 'category_name': item.category_name,
'notes': item.notes, 'location_id': item.location_id, 'package_count': item.package_count,
'package_amount': str(item.package_amount) if item.package_amount is not None else None,
'package_unit': item.package_unit, 'pieces_per_package': item.pieces_per_package,
'piece_amount': str(item.piece_amount) if item.piece_amount is not None else None,
'inner_packs_per_package': item.inner_packs_per_package,
'pieces_per_inner_pack': item.pieces_per_inner_pack,
'inner_pack_amount': str(item.inner_pack_amount) if item.inner_pack_amount is not None else None,
'best_before': item.best_before.isoformat() if item.best_before else None, 'opened': item.opened}
def _integer(value, message, minimum=0, maximum=100000):
try:
result = int(value)
except (TypeError, ValueError):
raise ScanWorkflowError(message) from None
if str(result) != str(value).strip() and not isinstance(value, int):
raise ScanWorkflowError(message)
if not minimum <= result <= maximum:
raise ScanWorkflowError(message)
return result
def _integer_or_none(value, message, maximum=100000):
return None if value in (None, '') else _integer(value, message, 1, maximum)
def _decimal_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'))
+59
View File
@@ -0,0 +1,59 @@
"""Database-coordinated cap for actual Open Food Facts HTTP requests."""
from contextlib import contextmanager
from datetime import timedelta
import time
from django.db import transaction
from django.utils import timezone
from food.models import OpenFoodFactsRateLimit, OpenFoodFactsRequest
REQUESTS_PER_MINUTE = 5
WINDOW_SECONDS = 60
@contextmanager
def off_http_request(endpoint, *, wait=True, before_request=None):
"""Reserve and serialize one real request across web and worker processes.
The singleton row lock is held through the HTTP call, so simultaneous workers
cannot race through the budget check. Failed HTTP requests still count because
the reservation commits before the exception is re-raised.
"""
while True:
delay = 0
failure = None
traceback = None
with transaction.atomic():
OpenFoodFactsRateLimit.objects.get_or_create(pk=1)
OpenFoodFactsRateLimit.objects.select_for_update().get(pk=1)
now = timezone.now()
cutoff = now - timedelta(seconds=WINDOW_SECONDS)
oldest = OpenFoodFactsRequest.objects.filter(requested_at__gte=cutoff).order_by('requested_at').first()
if OpenFoodFactsRequest.objects.filter(requested_at__gte=cutoff).count() >= REQUESTS_PER_MINUTE:
delay = max(0.05, (oldest.requested_at + timedelta(seconds=WINDOW_SECONDS + 0.01) - now).total_seconds())
else:
OpenFoodFactsRequest.objects.create(requested_at=now, endpoint=endpoint[:24])
OpenFoodFactsRequest.objects.filter(requested_at__lt=now - timedelta(minutes=10)).delete()
try:
if before_request:
before_request()
yield
except BaseException as error:
failure = error
traceback = error.__traceback__
if delay:
if not wait:
raise OpenFoodFactsRateLimited(delay)
time.sleep(delay)
continue
if failure is not None:
raise failure.with_traceback(traceback)
return
class OpenFoodFactsRateLimited(Exception):
def __init__(self, retry_after):
self.retry_after = max(1, int(retry_after + 0.999))
super().__init__(f'Open Food Facts request budget is full; retry in {self.retry_after} seconds.')
+62 -13
View File
@@ -2,6 +2,7 @@
import json
import logging
import re
from email.utils import parsedate_to_datetime
from hashlib import sha256
from datetime import timedelta
from decimal import Decimal, InvalidOperation
@@ -15,6 +16,7 @@ from django.core.cache import cache
from django.utils import timezone
from food.models import FoodProduct, Unit
from .off_rate_limit import OpenFoodFactsRateLimited, off_http_request
logger = logging.getLogger(__name__)
FIELDS = 'code,product_name,brands,quantity,serving_size,serving_quantity,image_front_small_url,image_front_url,nutriments,categories,categories_tags'
@@ -35,7 +37,16 @@ class OpenFoodFactsError(Exception):
class OpenFoodFactsRateLimit(OpenFoodFactsError):
pass
def __init__(self, message, retry_after=None):
self.retry_after = retry_after
super().__init__(message)
class OpenFoodFactsTransientError(OpenFoodFactsError):
def __init__(self, message, *, retry_after=None, status_code=None):
self.retry_after = retry_after
self.status_code = status_code
super().__init__(message)
def normalise_query(query):
@@ -108,41 +119,59 @@ def _rate_limit(user_id, kind, limit):
class OpenFoodFactsClient:
def _get_json(self, url, params=None):
def _get_json(self, url, params=None, *, wait_for_slot=False, on_request_start=None):
if not settings.OPENFOODFACTS_ENABLED:
raise OpenFoodFactsError('Open Food Facts is unavailable.')
if params:
url = f'{url}?{urlencode(params)}'
request = Request(url, headers={'User-Agent': settings.OPENFOODFACTS_USER_AGENT, 'Accept': 'application/json'})
endpoint = 'product' if '/product/' in url else 'search'
try:
with urlopen(request, timeout=settings.OPENFOODFACTS_TIMEOUT_SECONDS) as response:
data = json.load(response)
except (HTTPError, URLError, TimeoutError, ValueError, OSError) as error:
logger.warning('Open Food Facts request failed: %s', error)
raise OpenFoodFactsError('Open Food Facts is temporarily unavailable.') from error
with off_http_request(endpoint, wait=wait_for_slot, before_request=on_request_start):
try:
with urlopen(request, timeout=settings.OPENFOODFACTS_TIMEOUT_SECONDS) as response:
data = json.load(response)
except HTTPError as error:
retry_after = _retry_after(error.headers.get('Retry-After') if error.headers else None)
logger.warning('Open Food Facts HTTP %s on %s request', error.code, endpoint)
if error.code == 429 or error.code >= 500:
raise OpenFoodFactsTransientError(
'Open Food Facts is temporarily unavailable.', retry_after=retry_after,
status_code=error.code) from error
raise OpenFoodFactsError(f'Open Food Facts rejected the request (HTTP {error.code}).') from error
except (URLError, TimeoutError, OSError) as error:
logger.warning('Open Food Facts request failed: %s', error)
raise OpenFoodFactsTransientError('Open Food Facts is temporarily unavailable.') from error
except ValueError as error:
logger.warning('Open Food Facts returned invalid JSON: %s', error)
raise OpenFoodFactsError('Open Food Facts returned an invalid response.') from error
except OpenFoodFactsRateLimited as error:
raise OpenFoodFactsRateLimit(str(error), retry_after=error.retry_after) from error
if not isinstance(data, dict):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return data
def get_product(self, barcode):
def get_product(self, barcode, *, wait_for_slot=False, on_request_start=None):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
data = self._get_json(settings.OPENFOODFACTS_PRODUCT_URL.format(barcode=barcode), {'fields': FIELDS})
data = self._get_json(settings.OPENFOODFACTS_PRODUCT_URL.format(barcode=barcode), {'fields': FIELDS},
wait_for_slot=wait_for_slot, on_request_start=on_request_start)
return data.get('product') if data.get('status') == 1 else None
def search(self, query, page=1):
def search(self, query, page=1, *, wait_for_slot=False):
query = normalise_query(query)
if not query or len(query) > 100 or page < 1 or page > 20:
raise ValueError('Enter a search query and valid page.')
data = self._get_json(settings.OPENFOODFACTS_SEARCH_URL, {'action': 'process', 'search_simple': 1,
'json': 1, 'search_terms': query, 'page': page, 'page_size': 20, 'fields': FIELDS})
'json': 1, 'search_terms': query, 'page': page, 'page_size': 20, 'fields': FIELDS},
wait_for_slot=wait_for_slot)
products = data.get('products')
if not isinstance(products, list):
raise OpenFoodFactsError('Open Food Facts returned an invalid response.')
return [mapped for item in products if (mapped := map_product(item))]
def cached_product(user, barcode, *, refresh=False):
def cached_product(user, barcode, *, refresh=False, wait_for_slot=False, on_request_start=None):
if not re.fullmatch(r'[0-9]{1,64}', barcode):
raise ValueError('Enter a numeric barcode.')
product = FoodProduct.objects.filter(owner=user, barcode=barcode).first()
@@ -154,7 +183,12 @@ def cached_product(user, barcode, *, refresh=False):
return product
_rate_limit(user.pk, 'product', 10)
try:
data = OpenFoodFactsClient().get_product(barcode)
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
@@ -173,6 +207,21 @@ def cached_product(user, barcode, *, refresh=False):
return product
def _retry_after(value):
if not value:
return None
try:
return max(0, int(value.strip()))
except (AttributeError, TypeError, ValueError):
try:
requested_at = parsedate_to_datetime(value)
if requested_at.tzinfo is None:
requested_at = requested_at.replace(tzinfo=timezone.get_current_timezone())
return max(0, int((requested_at - timezone.now()).total_seconds()))
except (TypeError, ValueError, OverflowError):
return None
def cached_search(user, query, page=1):
normalized = normalise_query(query)
if not normalized or len(normalized) > 100 or page < 1 or page > 20:
+175 -1
View File
@@ -65,7 +65,7 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
.food-help-popover .food-help-tip{margin-top:.75rem;color:var(--food-muted)}
@media(max-width:600px){.food-help-popover{top:auto!important;left:12px!important;right:12px;bottom:max(12px,env(safe-area-inset-bottom));width:auto;max-height:min(70dvh,560px)}}
.inventory-product-card{display:grid;gap:.8rem}.inventory-product-heading{display:flex;align-items:center;gap:1rem;min-width:0}.inventory-product-heading img{width:68px;height:68px;object-fit:contain;background:white;border-radius:.6rem}.inventory-product-heading h2{margin:0}.inventory-product-heading p{margin:.25rem 0;overflow-wrap:anywhere}.inventory-packages summary,.inventory-use summary{cursor:pointer;min-height:44px;align-content:center;font-weight:650}.inventory-package-list{display:grid;gap:.65rem;margin:.6rem 0}.inventory-package{display:flex;align-items:center;gap:.8rem;padding:.65rem;border:1px solid var(--food-border);border-radius:.7rem;min-width:0}.inventory-package>div:last-child{min-width:0}.inventory-package p{margin:.2rem 0}.inventory-package small{color:var(--food-muted)}.inventory-package-fill{flex:none;position:relative;width:42px;height:64px;border:2px solid var(--food-muted);border-radius:.3rem;overflow:hidden;background:var(--food-progress-track)}.inventory-package-fill span{position:absolute;bottom:0;left:0;right:0;background:var(--food-green);transition:height .25s ease}.inventory-use-form{display:flex;flex-wrap:wrap;gap:.6rem;align-items:end}.inventory-use-form label{display:grid;gap:.25rem;flex:1;min-width:100px}.inventory-use-form input,.inventory-use-form select{max-width:100%;min-height:44px}.inventory-use-form button{min-height:44px}.inventory-preview{border:1px solid var(--food-border);border-radius:.7rem;padding:.8rem;margin-top:.7rem}.inventory-preview h3{margin:0}.inventory-preview form{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}.inventory-preview form button,.inventory-history button{min-height:44px}.inventory-preview [role=alert]{color:#e9aa72}.inventory-history ul{padding-left:1.2rem}.inventory-history li{margin:.4rem 0}.inventory-history li form{display:inline-block;margin-left:.5rem}@media(max-width:480px){.inventory-product-heading{align-items:flex-start}.inventory-use-form{display:grid;grid-template-columns:1fr 1fr}.inventory-use-form label:nth-child(3){grid-column:1/-1}.inventory-use-form button{grid-column:1/-1}}@media(prefers-reduced-motion:reduce){.inventory-package-fill span{transition:none}}
.inventory-product-card{display:grid;gap:.8rem}.inventory-product-heading{display:flex;align-items:center;gap:1rem;min-width:0}.inventory-product-heading img{width:68px;height:68px;object-fit:contain;background:white;border-radius:.6rem}.inventory-product-heading h2{margin:0}.inventory-product-heading p{margin:.25rem 0;overflow-wrap:anywhere}.inventory-packages summary,.inventory-use summary{cursor:pointer;min-height:44px;align-content:center;font-weight:650}.inventory-package-list{display:grid;gap:.65rem;margin:.6rem 0}.inventory-package{display:flex;align-items:center;gap:.8rem;padding:.65rem;border:1px solid var(--food-border);border-radius:.7rem;min-width:0}.inventory-package>div:last-child{min-width:0}.inventory-package p{margin:.2rem 0}.inventory-package small{color:var(--food-muted)}.inventory-package-fill{flex:none;position:relative;width:42px;height:64px;border:2px solid var(--food-muted);border-radius:.3rem;overflow:hidden;background:var(--food-progress-track)}.inventory-package-fill span{position:absolute;bottom:0;left:0;right:0;background:var(--food-green);transition:height .25s ease}.inventory-use-form{display:flex;flex-wrap:wrap;gap:.6rem;align-items:end}.inventory-use-form label{display:grid;gap:.25rem;flex:1;min-width:0}.inventory-use-form input,.inventory-use-form select{max-width:100%;min-width:0;min-height:44px;box-sizing:border-box}.inventory-use-form select{width:100%}.inventory-use-form button{min-height:44px}.inventory-preview{border:1px solid var(--food-border);border-radius:.7rem;padding:.8rem;margin-top:.7rem}.inventory-preview h3{margin:0}.inventory-preview form{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}.inventory-preview form button,.inventory-history button{min-height:44px}.inventory-preview [role=alert]{color:#e9aa72}.inventory-history ul{padding-left:1.2rem}.inventory-history li{margin:.4rem 0}.inventory-history li form{display:inline-block;margin-left:.5rem}@media(max-width:480px){.inventory-product-heading{align-items:flex-start}.inventory-use-form{display:grid;grid-template-columns:1fr 1fr}.inventory-use-form label:nth-child(3){grid-column:1/-1}.inventory-use-form button{grid-column:1/-1}}@media(prefers-reduced-motion:reduce){.inventory-package-fill span{transition:none}}
.food-entry-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:.3rem;flex:none}.food-entry-actions a{display:inline-flex;align-items:center;min-height:44px;padding:.2rem .35rem}.food-entry-actions a:focus-visible{outline:2px solid var(--food-green);outline-offset:2px}@media(max-width:480px){.food-entry{flex-wrap:wrap}.food-entry-actions{width:100%;justify-content:flex-start}}
/* Inventory search remains available when additional filters are collapsed. */
@@ -91,9 +91,182 @@ 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-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}
.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}.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}
.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}
/* Bulk scanner surfaces follow the app's dark appearance setting. */
body[data-theme="dark"] .inventory-staging,
body[data-theme="dark"] .inventory-review-page .food-card,
body[data-theme="dark"] .inventory-scan-start,
body[data-theme="dark"] .inventory-scan-camera,
body[data-theme="dark"] .inventory-scan-active,
body[data-theme="dark"] .inventory-scan-queue {border-color:#3b473f;background:#202923;color:#edf5ef}
body[data-theme="dark"] .inventory-staging {background:#242e27}
body[data-theme="dark"] .inventory-staging-top h2,
body[data-theme="dark"] .inventory-review-page h2,
body[data-theme="dark"] .inventory-review-page .food-heading h1,
body[data-theme="dark"] .inventory-scan-page>.food-heading h1,
body[data-theme="dark"] .inventory-scan-queue-heading h2,
body[data-theme="dark"] .inventory-scan-queue-item-main strong {color:#edf5ef}
body[data-theme="dark"] .inventory-staging-top p:last-child,
body[data-theme="dark"] .inventory-review-page .food-heading p:last-child,
body[data-theme="dark"] .inventory-review-row p,
body[data-theme="dark"] .inventory-bulk-review>p,
body[data-theme="dark"] .inventory-bulk-selection small,
body[data-theme="dark"] .inventory-review-preview span,
body[data-theme="dark"] .inventory-scan-meta,
body[data-theme="dark"] .inventory-scan-hint,
body[data-theme="dark"] .inventory-scan-note,
body[data-theme="dark"] .inventory-scan-empty,
body[data-theme="dark"] .inventory-scan-queue-item-main small,
body[data-theme="dark"] .inventory-scan-queue-item-side small,
body[data-theme="dark"] .inventory-scan-queue-heading>span,
body[data-theme="dark"] .inventory-scan-batch-heading>span {color:#b8c3bb}
body[data-theme="dark"] .inventory-kicker,
body[data-theme="dark"] .inventory-scan-active-heading,
body[data-theme="dark"] .inventory-scan-batch-heading h3 {color:#9bd5ae}
body[data-theme="dark"] .inventory-staging-counts>a,
body[data-theme="dark"] .inventory-review-mode button,
body[data-theme="dark"] .inventory-review-toolbar button,
body[data-theme="dark"] .inventory-review-states a {border-color:#46544b;background:#27312b;color:#edf5ef}
body[data-theme="dark"] .inventory-staging-counts strong {color:#9bd5ae}
body[data-theme="dark"] .inventory-review-mode button.is-selected,
body[data-theme="dark"] .inventory-review-toolbar button.is-selected,
body[data-theme="dark"] .inventory-review-states a[aria-current=page] {border-color:#568466;background:#294332;color:#d9f5e0}
body[data-theme="dark"] .inventory-scan-location {border-color:#568466;background:#263c2e;color:#b9edc8}
body[data-theme="dark"] .inventory-scan-location-panel,
body[data-theme="dark"] .inventory-scan-controls {border-color:#3b473f;background:#26342b;color:#d1ddd4}
body[data-theme="dark"] .inventory-scan-location-form select,
body[data-theme="dark"] .inventory-scan-start-form select,
body[data-theme="dark"] .inventory-scan-next-row select,
body[data-theme="dark"] .inventory-scan-active input,
body[data-theme="dark"] .inventory-scan-active select,
body[data-theme="dark"] .inventory-scan-active textarea,
body[data-theme="dark"] .inventory-review-fields input,
body[data-theme="dark"] .inventory-review-fields select,
body[data-theme="dark"] .inventory-review-fields textarea,
body[data-theme="dark"] .inventory-review-shared-fields input,
body[data-theme="dark"] .inventory-review-shared-fields select,
body[data-theme="dark"] .inventory-review-nutrients input {border-color:#536159;background:#161d19;color:#edf5ef;color-scheme:dark}
body[data-theme="dark"] .inventory-scan-active form>label,
body[data-theme="dark"] .inventory-scan-active .inventory-scan-product-title,
body[data-theme="dark"] .inventory-scan-fields label,
body[data-theme="dark"] .inventory-scan-queue-item-side {color:#d9e4dc}
body[data-theme="dark"] .inventory-scan-more,
body[data-theme="dark"] .inventory-scan-nutrition,
body[data-theme="dark"] .inventory-scan-count-controls button {border-color:#3b473f;background:#27312b;color:#edf5ef}
body[data-theme="dark"] .inventory-scan-batch-heading,
body[data-theme="dark"] .inventory-scan-queue-item,
body[data-theme="dark"] .inventory-scan-manual,
body[data-theme="dark"] .inventory-scan-nutrition dl div,
body[data-theme="dark"] .inventory-bulk-selection,
body[data-theme="dark"] .inventory-bulk-selection label,
body[data-theme="dark"] .inventory-review-preview {border-color:#3b473f}
body[data-theme="dark"] .inventory-scan-nutrition dt {color:#b8c3bb}
body[data-theme="dark"] .inventory-scan-controls .inventory-scan-done {background:#39734e}
body[data-theme="dark"] .inventory-review-error,
body[data-theme="dark"] .inventory-scan-error,
body[data-theme="dark"] .inventory-scan-location-form [data-scan-location-error]:not([hidden]) {color:#ffb4a9}
body[data-theme="dark"] .inventory-review-success {color:#9bd5ae}
body[data-theme="dark"] .inventory-scan-page :focus-visible,
body[data-theme="dark"] .inventory-review-page :focus-visible,
body[data-theme="dark"] .inventory-staging :focus-visible {outline-color:#f2c16d}
/* Shared ring geometry: the outer lap stays complete beneath excess progress. */
.food-ring{position:relative;display:grid;place-items:center;background:none}
.food-ring svg{display:block;width:100%;height:100%;transform:rotate(-90deg);overflow:visible}
@@ -107,4 +280,5 @@ body[data-theme="dark"] .food-tabs a[aria-current=page]{color:#102317}
.food-macro .food-ring{--accent:inherit}
/* Shared product and entry nutrition forms. */
.inventory-review-states{display:flex;gap:.5rem;flex-wrap:wrap;margin:.75rem 0}.inventory-review-states a{min-height:42px;align-content:center;padding:.5rem .75rem;border:1px solid #c8d4ca;border-radius:9px;color:#183c2c;text-decoration:none}.inventory-review-states a[aria-current=page]{background:#e9f3ec;border-color:#247452;font-weight:700}
.product-form{display:grid;gap:1rem}.product-form .form-field,.entry-nutrition-fields .form-field{display:grid;gap:.3rem}.nutrition-fields{min-width:0;margin:0;padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.nutrition-fields legend{padding:0 .35rem;font-weight:700}.nutrition-fields p,.entry-nutrition-fields p{margin:.2rem 0 1rem;line-height:1.45;color:var(--food-muted)}.nutrition-fields>details,.entry-nutrition-fields{margin-top:1rem}.nutrition-fields summary,.entry-nutrition-fields summary{cursor:pointer;font-weight:700;min-height:44px;align-content:center}.nutrition-field-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.85rem}.nutrition-field-grid input{width:100%;min-width:0}.nutrition-fields .form-field{margin-bottom:.8rem}.entry-nutrition-fields{padding:1rem;border:1px solid var(--food-border);border-radius:.9rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]){display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.entry-nutrition-fields .form-field:has(input[type=checkbox]) small{flex-basis:100%}@media(max-width:520px){.nutrition-field-grid{grid-template-columns:1fr}}
+10
View File
@@ -5,3 +5,13 @@ document.addEventListener('click', (event) => {
input.value = Math.max(1, (Number.parseInt(input.value, 10) || 1) + Number(button.dataset.inventoryStep));
input.dispatchEvent(new Event('change', { bubbles: true }));
});
document.addEventListener('change', (event) => {
if (!event.target.matches('.inventory-use-form select[name="unit"]')) return;
const amount = event.target.form?.elements.namedItem('amount');
if (!amount) return;
const isCount = ['pieces', 'inner_packs', 'packs', 'portions'].includes(event.target.value);
amount.min = isCount ? '1' : '0.001';
amount.step = isCount ? '1' : '0.001';
amount.inputMode = isCount ? 'numeric' : 'decimal';
});
+28
View File
@@ -0,0 +1,28 @@
(() => {
document.querySelectorAll('[data-bulk-review]').forEach((form) => {
const checkboxes = [...form.querySelectorAll('input[name="item_ids"]:not(:disabled)')];
const preview = form.querySelector('[data-bulk-preview-submit]');
if (!preview) return;
const status = form.querySelector('[data-review-selection-status]');
const update = () => {
const selected = checkboxes.filter((checkbox) => checkbox.checked).length;
preview.disabled = selected === 0;
if (status) {
status.hidden = selected === 0;
status.textContent = selected ? `${selected} product${selected === 1 ? '' : 's'} selected for preview.` : '';
}
};
checkboxes.forEach((checkbox) => checkbox.addEventListener('change', update));
form.addEventListener('submit', (event) => {
if (!checkboxes.some((checkbox) => checkbox.checked)) {
event.preventDefault();
if (status) {
status.hidden = false;
status.textContent = 'Select at least one product with a name before previewing.';
status.focus?.();
}
}
});
update();
});
})();
+356 -1
View File
@@ -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,355 @@
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 < 3000) {
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);
if (data.incremented) {
clearActive();
say(`${data.item.product_name || 'This product'}: repeated scan added one package. Use Remove one package in the queue to undo.`);
return;
}
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);
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); }
});
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 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' &&
!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;
}
})();
+2 -2
View File
@@ -6,7 +6,7 @@
<section class="food-card inventory-product">{% if product.image_url %}<img src="{{ product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ product.product_name }}</h2>{% if product.brand %}<p>{{ product.brand }}</p>{% endif %}{% if product.package_quantity %}<p>{{ product.package_quantity }}</p>{% endif %}{% if off_categories %}<p><small>Open Food Facts: {{ off_categories }}</small></p>{% endif %}<p><a href="{% url 'food:product-edit' product.pk %}">View or edit product nutrition</a></p></div></section>
{% if existing %}<section class="food-card"><h2>Already in inventory</h2>{% for item in existing %}<div class="inventory-existing"><span>{{ item.location.name }} · Quantity {{ item.quantity }}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</span><form method="post" action="{% url 'food:inventory-add-one' item.pk %}">{% csrf_token %}<button class="button button--secondary" type="submit">+1 existing item</button></form></div>{% endfor %}<p>Use the form below to add this product separately.</p></section>{% endif %}
<form class="food-card inventory-form" method="post">{% csrf_token %}<input type="hidden" name="product" value="{{ product.pk }}">{{ form.non_field_errors }}
{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}
{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}
<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist>
<button class="button" type="submit">Add to inventory</button></form>
<a href="{% url 'food:inventory-add' %}">Choose another product</a>
@@ -16,4 +16,4 @@
<ul class="food-product-list">{% for item in products %}<li><a href="{% url 'food:inventory-add' %}?product={{ item.pk }}">{% if item.image_url %}<img src="{{ item.image_url }}" alt="" loading="lazy">{% endif %}<span><strong>{{ item.product_name }}</strong>{% if item.brand %}<small>{{ item.brand }}</small>{% endif %}</span></a></li>{% empty %}<li>No saved products found.</li>{% endfor %}</ul>
{% include 'food/partials/inventory_product_actions.html' %}
<form method="post" action="{% url 'food:inventory-lookup' %}" class="food-barcode-form">{% csrf_token %}<label for="inventory-barcode">Enter barcode</label><input id="inventory-barcode" name="barcode" inputmode="numeric" pattern="[0-9]+" required><button class="button button--secondary" type="submit">Look up</button></form>
{% endif %}</div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %}
{% endif %}</div><script src="{% static 'food/inventory.js' %}?v=20261026-nested" defer></script>{% endblock %}
+1 -1
View File
@@ -1,3 +1,3 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Edit inventory item · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><p>This form changes stock for this package. <a href="{% url 'food:product-edit' item.product.pk %}">View or edit product nutrition</a> for future food logs.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}" defer></script>{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}"><div class="food-form-page inventory-page"><a href="{% url 'food:inventory' %}">← Kitchen Inventory</a><h1>Edit {{ item.product.product_name }}</h1><p>This form changes stock for this package. <a href="{% url 'food:product-edit' item.product.pk %}">View or edit product nutrition</a> for future food logs.</p><form method="post" class="food-card inventory-form">{% csrf_token %}{{ form.non_field_errors }}{% for field in form %}<div class="form-field">{{ field.label_tag }}{% if field.name == 'quantity' %}<div class="inventory-quantity" data-inventory-quantity><button type="button" data-inventory-step="-1" aria-label="Decrease quantity">−</button>{{ field }}<button type="button" data-inventory-step="1" aria-label="Increase quantity">+</button></div>{% else %}{{ field }}{% endif %}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}{{ field.errors }}</div>{% endfor %}<datalist id="inventory-locations">{% for location in locations %}<option value="{{ location.name }}">{% endfor %}</datalist><datalist id="inventory-categories">{% for category in categories %}<option value="{{ category.name }}">{% endfor %}</datalist><button class="button" type="submit">Save changes</button></form></div><script src="{% static 'food/inventory.js' %}?v=20261026-nested" defer></script>{% endblock %}
@@ -1,16 +1,17 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Kitchen Inventory · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261012-filters">
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-2">
<div class="food-page inventory-page"><header class="food-heading"><div><h1>Kitchen Inventory</h1><p>What you have and where it lives.</p></div><div class="inventory-heading-actions"><a class="button" href="{% url 'food:inventory-add' %}">+ Add item</a><a class="button button--secondary" href="{% url 'food:scanner' %}?mode=inventory">Scan barcode</a></div></header>
<section class="food-card inventory-staging" id="inventory-review" aria-labelledby="inventory-staging-title"><div class="inventory-staging-top"><div><p class="inventory-kicker">Bulk scanner</p><h2 id="inventory-staging-title">Staged scan items</h2><p>Track background enrichment and finish products that need your input.</p></div><a class="button" href="{% url 'food:inventory-review' %}">Open review</a></div>{% include 'food/partials/inventory_staging_counts.html' %}<form method="post" action="{% url 'food:inventory-review' %}" class="inventory-review-mode">{% csrf_token %}<input type="hidden" name="action" value="mode"><span>Review mode</span><button name="mode" value="individual" aria-pressed="{% if review_mode == 'individual' %}true{% else %}false{% endif %}" class="{% if review_mode == 'individual' %}is-selected{% endif %}">Individual</button><button name="mode" value="bulk" aria-pressed="{% if review_mode == 'bulk' %}true{% else %}false{% endif %}" class="{% if review_mode == 'bulk' %}is-selected{% endif %}">Bulk review</button></form></section>
<form method="get" class="food-card inventory-filters" role="search" aria-label="Search kitchen inventory">
<div class="inventory-filter-search"><label for="inventory-search">Search inventory</label><div><input id="inventory-search" type="search" name="q" value="{{ query }}"><button class="button" type="submit">Search</button></div></div>
<details class="inventory-filter-details" data-responsive-filters open><summary>More filters{% if selected_location or selected_category or opened or use_soon == '1' or sort != 'location' %} · Applied{% endif %}</summary><div class="inventory-filter-options"><label>Location<select name="location"><option value="">All locations</option>{% for location in locations %}<option value="{{ location.pk }}" {% if selected_location == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<select name="category"><option value="">All categories</option>{% for category in categories %}<option value="{{ category.pk }}" {% if selected_category == category.pk|stringformat:'s' %}selected{% endif %}>{{ category.name }}</option>{% endfor %}</select></label><label>Opened<select name="opened"><option value="">All</option><option value="yes" {% if opened == 'yes' %}selected{% endif %}>Opened</option><option value="no" {% if opened == 'no' %}selected{% endif %}>Unopened</option></select></label><label>Sort<select name="sort"><option value="location" {% if sort == 'location' %}selected{% endif %}>Location</option><option value="category" {% if sort == 'category' %}selected{% endif %}>Category</option><option value="name" {% if sort == 'name' %}selected{% endif %}>Product name</option><option value="recent" {% if sort == 'recent' %}selected{% endif %}>Recently added</option><option value="best_before" {% if sort == 'best_before' %}selected{% endif %}>Best before</option></select></label><label class="inventory-check"><input type="checkbox" name="use_soon" value="1" {% if use_soon == '1' %}checked{% endif %}> Use soon</label><button class="button" type="submit">Apply filters</button></div></details>
</form>
{% for card in cards %}<article class="food-card inventory-product-card">
<div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{{ card.total|floatformat:-3 }} {% if card.unit == "packs" and card.total == 1 %}pack{% else %}{{ card.unit }}{% endif %} remaining</strong> · {{ card.packages|length }} package{{ card.packages|length|pluralize }}</p></div></div>
<div class="inventory-product-heading">{% if card.product.image_url %}<img src="{{ card.product.image_url }}" alt="" loading="lazy">{% endif %}<div><h2>{{ card.product.product_name }}</h2>{% if card.product.brand %}<p>{{ card.product.brand }}</p>{% endif %}<p><strong>{% if card.has_pieces %}{{ card.piece_total }} piece{{ card.piece_total|pluralize }}{% if card.unit != 'pieces' %} ({{ card.total|floatformat:-3 }} {{ card.unit }}){% endif %}{% else %}{{ card.total|floatformat:-3 }} {% if card.unit == 'packs' %}package{{ card.total|pluralize }}{% else %}{{ card.unit }}{% endif %}{% endif %} remaining</strong> · {{ card.package_count }} package{{ card.package_count|pluralize }}</p></div></div>
<p><a href="{% url 'food:product-edit' card.product.pk %}">View or edit product nutrition</a></p>
<details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Pack {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details>
<details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{{ unit }}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Pack {{ forloop.counter }} · {% if item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} pack{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details>
<details class="inventory-packages"><summary>View packages</summary><div class="inventory-package-list">{% for item in card.packages %}<div class="inventory-package"><div class="inventory-package-fill" role="img" aria-label="{{ item.percentage_remaining }}% remaining"><span style="height:{{ item.percentage_remaining }}%"></span></div><div><strong>Package {{ forloop.counter }} · {{ item.package_status|title }}</strong><p>{% if item.inner_packs_per_package %}{{ item.remaining_inner_pack_balance|capfirst }} · {{ item.remaining_pieces }} / {{ item.pieces_per_package }} {{ item.piece_label }}{% if item.inventory_unit != 'pieces' %} · {{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }}{% endif %}{% elif item.pieces_per_package %}{{ item.remaining_pieces }} / {{ item.pieces_per_package }} piece{{ item.pieces_per_package|pluralize }}{% if item.inventory_unit != 'pieces' %} · {{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }}{% endif %}{% elif item.original_amount %}{{ item.remaining_amount|floatformat:-3 }} / {{ item.original_amount|floatformat:-3 }} {{ item.inventory_unit }} · {{ item.percentage_remaining }}% remaining{% else %}{{ item.quantity }} package{{ item.quantity|pluralize }} · size unknown{% endif %}</p><small>{{ item.location.name }}{% if item.category %} · {{ item.category.name }}{% endif %}{% if item.best_before %} · Best before {{ item.best_before }}{% endif %}</small><div><a href="{% url 'food:inventory-edit' item.pk %}">Edit package</a></div></div></div>{% endfor %}</div></details>
<details class="inventory-use"><summary>Use amount</summary><form method="post" action="{% url 'food:inventory-preview' card.product.pk %}" hx-post="{% url 'food:inventory-preview' card.product.pk %}" hx-target="#inventory-preview-{{ card.product.pk }}-{{ card.unit }}" hx-swap="innerHTML" class="inventory-use-form">{% csrf_token %}<label>Amount<input type="number" name="amount" min="{% if card.count_unit %}1{% else %}0.001{% endif %}" step="{% if card.count_unit %}1{% else %}0.001{% endif %}" required inputmode="decimal"></label><label>Unit<select name="unit">{% for unit in card.units %}<option value="{{ unit }}" {% if unit == card.unit %}selected{% endif %}>{% if unit == 'inner_packs' %}inner packs{% else %}{{ unit }}{% endif %}</option>{% endfor %}</select></label><label>Package (optional)<select name="package_id"><option value="">Automatic selection</option>{% for item in card.packages %}<option value="{{ item.api_id }}">Package {{ forloop.counter }} · {% if item.inner_packs_per_package %}{{ item.remaining_inner_pack_balance }} · {{ item.remaining_pieces }} {{ item.piece_label }}{{ item.remaining_pieces|pluralize }} left{% elif item.pieces_per_package %}{{ item.remaining_pieces }} pieces left{% if item.inventory_unit != 'pieces' %} · {{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% endif %}{% elif item.remaining_amount is not None %}{{ item.remaining_amount|floatformat:-3 }} {{ item.inventory_unit }}{% else %}{{ item.quantity }} package{{ item.quantity|pluralize }}{% endif %}</option>{% endfor %}</select></label><button class="button button--secondary" type="submit">Preview</button></form><div id="inventory-preview-{{ card.product.pk }}-{{ card.unit }}" aria-live="polite"></div></details>
</article>{% empty %}<section class="food-card"><p>No inventory items found.</p><a class="button" href="{% url 'food:inventory-add' %}">Add your first item</a></section>{% endfor %}
{% if recent_consumption %}<section class="food-card inventory-history"><h2>Recent use</h2><ul>{% for entry in recent_consumption %}<li>{{ entry.created_at|date:'j M, H:i' }} · {{ entry.product.product_name }} · {{ entry.amount|floatformat:-3 }} {{ entry.unit }}<details><summary>Package changes</summary><ul>{% for line in entry.lines.all %}<li>Pack {{ line.package.pk }}: {{ line.before_amount|floatformat:-3 }} → {{ line.after_amount|floatformat:-3 }} {{ line.unit }}</li>{% endfor %}</ul></details>{% if not entry.reversal %}<form method="post" action="{% url 'food:inventory-undo' entry.pk %}">{% csrf_token %}<button type="submit">Undo</button></form>{% else %} · Undone{% endif %}</li>{% endfor %}</ul></section>{% endif %}
</div><script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script>{% endblock %}
{% if recent_consumption %}<section class="food-card inventory-history"><h2>Recent use</h2><ul>{% for entry in recent_consumption %}<li>{{ entry.created_at|date:'j M, H:i' }} · {{ entry.product.product_name }} · {{ entry.amount|floatformat:-3 }} {% if entry.unit == 'inner_packs' %}inner pack{{ entry.amount|pluralize }}{% elif entry.unit == 'pieces' %}{{ entry.amount|pluralize:'piece,pieces' }}{% else %}{{ entry.unit }}{% endif %}<details><summary>Package changes</summary><ul>{% for line in entry.lines.all %}<li>Package {{ line.package.pk }}: {{ line.before_amount|floatformat:-3 }} → {{ line.after_amount|floatformat:-3 }} {{ line.unit }}{% if line.after_pieces is not None %} · {{ line.before_pieces }} → {{ line.after_pieces }} pieces{% endif %}</li>{% endfor %}</ul></details>{% if not entry.reversal %}<form method="post" action="{% url 'food:inventory-undo' entry.pk %}">{% csrf_token %}<button type="submit">Undo</button></form>{% else %} · Undone{% endif %}</li>{% endfor %}</ul></section>{% endif %}
</div><script src="{% static 'planner/responsive_filters.js' %}?v=1" defer></script><script src="{% static 'food/inventory.js' %}?v=20261026-nested" defer></script>{% endblock %}
@@ -0,0 +1,30 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Inventory review · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-2">
<main class="food-page inventory-review-page">
<header class="food-heading"><div><a href="{% url 'food:inventory' %}">← Kitchen inventory</a><h1>{% if state == 'processing' %}Processing scan items{% elif state == 'deferred' %}Deferred scan items{% else %}Additional Review Required{% endif %}</h1><p>{{ review_count }} product{{ review_count|pluralize }} {% if state == 'processing' %}are queued or being enriched.{% elif state == 'deferred' %}deferred for later. Fetched and entered information remains saved.{% else %}need review. Fetched and entered information is kept on each staged item.{% endif %}</p></div></header>
{% if state != 'processing' %}<nav class="inventory-review-states" aria-label="Review status"><a href="{% url 'food:inventory-review' %}" {% if state == 'review' %}aria-current="page"{% endif %}>Needs review</a><a href="{% url 'food:inventory-review' %}?state=deferred" {% if state == 'deferred' %}aria-current="page"{% endif %}>Deferred · {{ deferred_count }}</a></nav>{% endif %}
{% if state != 'processing' %}<div class="inventory-review-toolbar"><div><form method="post" action="{% url 'food:inventory-review' %}">{% csrf_token %}<input type="hidden" name="action" value="mode"><input type="hidden" name="state" value="{{ state }}"><button name="mode" value="individual" class="{% if mode == 'individual' %}is-selected{% endif %}" aria-pressed="{% if mode == 'individual' %}true{% else %}false{% endif %}">Individual</button><button name="mode" value="bulk" class="{% if mode == 'bulk' %}is-selected{% endif %}" aria-pressed="{% if mode == 'bulk' %}true{% else %}false{% endif %}">Bulk review</button></form></div><a href="{% url 'food:inventory' %}#inventory-review">Processing and review counts</a></div>{% endif %}
{% if approved_count %}<p class="inventory-review-success" role="status">{{ approved_count }} product{{ approved_count|pluralize }} added to inventory.</p>{% endif %}
{% if review_error %}<p class="inventory-review-error" role="alert">{{ review_error }}</p>{% endif %}
{% if mode == 'individual' or state == 'processing' %}
<section class="inventory-review-list" aria-label="Products requiring individual review">
{% for item in items %}<article class="food-card inventory-review-row"><div><p class="inventory-kicker">{{ item.get_status_display }} · {{ item.location.name }}</p><h2>{{ item.product_name|default:'Product details needed' }}</h2><p>{{ item.brand }}{% if item.brand %} · {% endif %}Barcode {{ item.barcode }}</p>{% if item.last_error %}<p class="inventory-review-error">{{ item.last_error }}</p>{% endif %}<p>{{ item.package_count }} package{{ item.package_count|pluralize }}{% if item.package_amount %} · {{ item.package_amount }} {{ item.package_unit }}{% endif %}</p></div>{% if state != 'processing' %}<a class="button" href="{% url 'food:inventory-review-item' item.pk %}">Review product</a>{% endif %}</article>{% empty %}<section class="food-card"><h2>{% if state == 'processing' %}No items processing{% else %}Nothing needs review{% endif %}</h2><p>{% if state == 'processing' %}Submitted scan batches will appear here while the worker enriches them.{% else %}Products that could not be matched or need corrections will appear here.{% endif %}</p></section>{% endfor %}
</section>
{% elif state != 'processing' %}
<form class="food-card inventory-bulk-review" method="post" action="{% url 'food:inventory-review' %}" data-bulk-review>
{% csrf_token %}<input type="hidden" name="state" value="{{ state }}"><input type="hidden" name="action" value="{% if preview %}approve{% else %}preview{% endif %}">
<h2>{% if preview %}Preview selected products{% else %}Select products to review together{% endif %}</h2>
<p>{% if preview %}Review the affected rows before adding them to inventory. Individual product fields and nutrition stay unchanged.{% else %}Apply a shared storage location or category, then preview the exact products before approval.{% endif %}</p>
{% if preview %}
{% for item in preview_items %}<input type="hidden" name="item_ids" value="{{ item.pk }}"><div class="inventory-review-row inventory-review-preview"><div><strong>{{ item.product_name|default:'Product details needed' }}</strong><span>{{ item.barcode }} · {{ item.package_count }} package{{ item.package_count|pluralize }}</span></div><span>{{ shared_location_name|default:item.location.name }}{% if shared_category %} · {{ shared_category }}{% elif item.category_name %} · {{ item.category_name }}{% endif %}</span></div>{% endfor %}
<input type="hidden" name="location_id" value="{{ shared_location_id }}"><input type="hidden" name="category_name" value="{{ shared_category }}">
<div class="inventory-review-actions"><button class="button" type="submit">Approve selected products</button><a class="button button--secondary" href="{% url 'food:inventory-review' %}?mode=bulk">Back to selection</a></div>
{% else %}
<fieldset class="inventory-bulk-selection"><legend>Select staged products</legend>{% for item in items %}<label><input type="checkbox" name="item_ids" value="{{ item.pk }}" {% if not item.product_name %}disabled{% endif %}><span><strong>{{ item.product_name|default:'Product details needed' }}</strong><small>{{ item.barcode }} · {{ item.get_status_display }} · {{ item.location.name }} · {{ item.package_count }} package{{ item.package_count|pluralize }}{% if not item.product_name %} · add a name in individual review{% endif %}</small></span></label>{% empty %}<p>No staged products need review.</p>{% endfor %}</fieldset>
<div class="inventory-review-shared-fields"><label>Shared location<select name="location_id"><option value="">Keep each product's location</option>{% for location in locations %}<option value="{{ location.pk }}">{{ location.name }}</option>{% endfor %}</select></label><label>Shared category<input name="category_name" maxlength="100" placeholder="Leave blank to keep each category"></label></div>
<p data-review-selection-status role="status" aria-live="polite" hidden></p><button class="button" type="submit" data-bulk-preview-submit {% if not eligible_bulk_count %}disabled{% endif %}>Preview affected products</button>
{% endif %}
</form>
{% endif %}
</main><script src="{% static 'food/inventory_review.js' %}?v=20261026-review-1" defer></script>{% endblock %}
@@ -0,0 +1,12 @@
{% extends 'planner/base.html' %}{% load static %}
{% block title %}Review {{ item.product_name|default:'scanned product' }} · Tasknest{% endblock %}
{% block content %}<link rel="stylesheet" href="{% static 'food/food.css' %}?v=20261026-review-2">
<main class="food-page inventory-review-page"><header class="food-heading"><div><a href="{% url 'food:inventory-review' %}">← Additional Review Required</a><p class="inventory-kicker">{{ item.get_status_display }} · Barcode {{ item.barcode }}</p><h1>Review scanned product</h1><p>Unknown nutrition values stay blank. You can approve without filling optional nutrition fields.</p></div></header>
{% if error %}<p class="inventory-review-error" role="alert">{{ error }}</p>{% endif %}{% if values.saved %}<p class="inventory-review-success" role="status">Your changes were saved.</p>{% endif %}
<form method="post" class="food-card inventory-review-form">{% csrf_token %}
<div class="inventory-review-toolbar"><span>Review mode</span><button type="submit" name="action" value="mode" class="{% if mode == 'individual' %}is-selected{% endif %}" aria-pressed="{% if mode == 'individual' %}true{% else %}false{% endif %}" onclick="this.form.querySelector('[name=mode]').value='individual'">Individual</button><button type="submit" name="action" value="mode" class="{% if mode == 'bulk' %}is-selected{% endif %}" aria-pressed="{% if mode == 'bulk' %}true{% else %}false{% endif %}" onclick="this.form.querySelector('[name=mode]').value='bulk'">Bulk review</button><input type="hidden" name="mode" value="{{ mode }}"></div>
<div class="inventory-review-fields"><label>Product name<input name="product_name" maxlength="255" required value="{{ values.product_name }}"></label><label>Brand<input name="brand" maxlength="255" value="{{ values.brand }}"></label><label>Storage location<select name="location_id" required>{% for location in locations %}<option value="{{ location.pk }}" {% if item.location_id == location.pk or values.location_id|stringformat:'s' == location.pk|stringformat:'s' %}selected{% endif %}>{{ location.name }}</option>{% endfor %}</select></label><label>Category<input name="category_name" maxlength="100" value="{{ values.category_name }}"></label>
<label>Number of packages<input type="number" name="package_count" min="1" max="10000" value="{{ values.package_count }}" required></label><label>Amount per package<input type="number" name="package_amount" min="0.001" step="0.001" value="{{ values.package_amount }}" placeholder="Unknown"></label><label>Package unit<input name="package_unit" maxlength="8" value="{{ values.package_unit }}" placeholder="e.g. g, ml, pieces"></label><label>Notes<textarea name="notes" rows="3">{{ values.notes }}</textarea></label></div>
<details class="inventory-scan-nutrition" open><summary>Nutrition per 100 g/ml (optional)</summary><p>Blank means unknown; entering 0 records a known zero.</p><div class="inventory-review-nutrients">{% for nutrient in nutrients %}<label>{{ nutrient.label }}<input type="number" min="0" step="0.001" name="{{ nutrient.field }}" value="{{ nutrient.value }}" placeholder="Unknown"></label>{% endfor %}</div></details>
<div class="inventory-review-actions"><button class="button" type="submit" name="action" value="save">Save changes</button><button class="button" type="submit" name="action" value="approve">Approve and add to inventory</button><button class="button button--secondary" type="submit" name="action" value="defer">Skip for now</button></div>
</form></main>{% endblock %}
@@ -0,0 +1,94 @@
{% 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-location-3">
<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>
</header>
{% if run %}
<section class="inventory-scan-location-panel" aria-labelledby="scan-current-location-title">
<div class="inventory-scan-location-summary">
<p class="inventory-kicker" id="scan-current-location-title">Current batch location</p>
<strong class="inventory-scan-location" data-scan-current-location aria-live="polite">{{ draft_batch.location.name }}</strong>
</div>
<form class="inventory-scan-location-form" data-scan-location-change
action="{% url 'food:inventory-scan-location' draft_batch.pk %}">
{% csrf_token %}
<label for="scan-current-location">Change location for this batch</label>
<div class="inventory-scan-location-actions">
<select id="scan-current-location" name="location_id" required>
{% 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="submit">Update current batch</button>
</div>
<p>Moves every scan in this unsaved batch. Previously saved batches stay in their locations. Use Save &amp; next location to keep batches in different places.</p>
<p class="inventory-scan-error" data-scan-location-error role="alert" hidden></p>
</form>
</section>
{% endif %}
{% if not run %}
<section class="food-card inventory-scan-start">
<h2>Choose a starting location</h2>
<p>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.</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">Starting location</label>
<select id="scan-start-location" name="location_id" required>
<option value="" selected disabled>Choose a location</option>
{% 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-current-location-id="{{ draft_batch.location_id }}"
data-location-url="{% url 'food:inventory-scan-location' 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 &amp; 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-location-3" defer></script>
{% endblock %}
@@ -1 +1 @@
{% if error %}<p role="alert">{{ error }}</p>{% elif plan %}<div class="inventory-preview"><h3>Consumption preview</h3><p>Available: {{ plan.total|floatformat:-3 }} {{ plan.unit }}</p><ul>{% for deduction in plan.deductions %}<li>{{ deduction.package.location.name }} · Pack {{ deduction.package.pk }}: −{{ deduction.amount|floatformat:-3 }} {{ deduction.unit }} ({{ deduction.after|floatformat:-3 }} left)</li>{% endfor %}</ul>{% if plan.shortage %}<p role="alert">Shortage: {{ plan.shortage|floatformat:-3 }} {{ plan.unit }}. Choose a partial use explicitly or cancel.</p>{% endif %}<form method="post" action="{% url 'food:inventory-use' product.pk %}">{% csrf_token %}<input type="hidden" name="amount" value="{{ plan.requested }}"><input type="hidden" name="unit" value="{{ plan.unit }}"><input type="hidden" name="package_id" value="{{ package_id }}">{% if plan.shortage %}<label><input type="checkbox" name="allow_partial" value="yes" required> Use only the available amount</label>{% endif %}<button class="button" type="submit" {% if not plan.deductions %}disabled{% endif %}>Confirm use</button><button type="button" onclick="this.closest('.inventory-preview').remove()">Cancel</button></form></div>{% endif %}
{% if error %}<p role="alert">{{ error }}</p>{% elif plan %}<div class="inventory-preview"><h3>Consumption preview</h3><p>Available: {{ plan.total|floatformat:-3 }} {{ plan.unit }}</p>{% if plan.equivalent_amount is not None %}<p>Calculated amount: {{ plan.equivalent_amount|floatformat:-3 }} {{ plan.equivalent_unit }}{% if plan.estimated_piece_weight %} <strong>(estimated from measured inner-pack weight)</strong>{% endif %}</p>{% endif %}<ul>{% for deduction in plan.deductions %}<li>{{ deduction.package.location.name }} · Package {{ deduction.package.pk }}: −{{ deduction.amount|floatformat:-3 }} {{ deduction.unit }} ({{ deduction.after|floatformat:-3 }} left){% if deduction.after_pieces is not None %} · {{ deduction.after_pieces }} {{ deduction.package.piece_label|default:'piece' }}{% if deduction.after_pieces != 1 %}s{% endif %} left{% endif %}{% if deduction.package.inner_packs_per_package %} · {{ deduction.after_inner_pack_balance }}{% endif %}</li>{% endfor %}</ul>{% if plan.nutrition %}<p><strong>Estimated nutrition for this use:</strong> {% for nutrient in plan.nutrition %}{{ nutrient.value|floatformat:-1 }} {{ nutrient.unit }} {{ nutrient.label|lower }}{% if not forloop.last %} · {% endif %}{% endfor %}</p>{% endif %}{% if plan.shortage %}<p role="alert">Shortage: {{ plan.shortage|floatformat:-3 }} {{ plan.unit }}. Choose a partial use explicitly or cancel.</p>{% endif %}<form method="post" action="{% url 'food:inventory-use' product.pk %}">{% csrf_token %}<input type="hidden" name="amount" value="{{ plan.requested }}"><input type="hidden" name="unit" value="{{ plan.unit }}"><input type="hidden" name="package_id" value="{{ package_id }}">{% if plan.shortage %}<label><input type="checkbox" name="allow_partial" value="yes" required> Use only the available amount</label>{% endif %}<button class="button" type="submit" {% if not plan.deductions %}disabled{% endif %}>Confirm use</button><button type="button" onclick="this.closest('.inventory-preview').remove()">Cancel</button></form></div>{% endif %}
@@ -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 &amp; 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>
@@ -0,0 +1,7 @@
<div class="inventory-staging-counts" id="inventory-staging-counts"
hx-get="{% url 'food:inventory-staging-counts' %}"
hx-trigger="every 5s" hx-swap="outerHTML"
aria-live="polite" aria-atomic="true">
<a href="{% url 'food:inventory-review' %}?state=processing"><strong>{{ processing_count }}</strong><span>Processing</span></a>
<a href="{% url 'food:inventory-review' %}"><strong>{{ needs_review_count }}</strong><span>Needs Review</span></a>
</div>
+118 -1
View File
@@ -1,10 +1,14 @@
from unittest.mock import patch
from decimal import Decimal
import json
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import FoodProduct, InventoryLocation, KitchenInventoryItem
from .api import create_token
from .models import FoodProduct, InventoryLocation, KitchenInventoryItem, InventoryConsumption
from .services.inventory_consumption import StockError, consume, preview, undo
class KitchenInventoryTests(TestCase):
@@ -68,3 +72,116 @@ class KitchenInventoryTests(TestCase):
self.assertEqual(list(KitchenInventoryItem.objects.filter(product=self.product)
.values_list('quantity', 'original_amount', 'remaining_amount', 'inventory_unit')),
[(1, 6, 6, 'pieces')] * 3)
def test_opened_roll_pack_tracks_pieces_not_packs(self):
response = self.client.post(reverse('food:inventory-add'), {
'product': self.product.pk, 'quantity': 1, 'pieces_per_package': 12,
'remaining_pieces': 10, 'location_name': 'Bread box',
})
self.assertEqual(response.status_code, 302, response.content[:500])
item = KitchenInventoryItem.objects.get(user=self.user)
self.assertEqual((item.quantity, item.original_amount, item.remaining_amount,
item.inventory_unit, item.remaining_pieces, item.opened),
(1, 12, 10, 'pieces', 10, True))
page = self.client.get(reverse('food:inventory'))
self.assertContains(page, '10 pieces')
self.assertContains(page, '1 package')
operation = consume(self.user, self.product, 2, 'pieces', package_id=item.api_id)
item.refresh_from_db()
self.assertEqual((item.remaining_pieces, item.remaining_amount), (8, 8))
undo(self.user, operation.pk)
item.refresh_from_db()
self.assertEqual((item.remaining_pieces, item.remaining_amount), (10, 10))
def test_weighed_sausages_piece_and_mass_deductions(self):
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('230'), remaining_amount=Decimal('230'),
inventory_unit='g', pieces_per_package=10, remaining_pieces=10,
piece_amount=Decimal('23'))
self.assertEqual(preview(self.user, self.product, 6, 'pieces')['deductions'][0]['after'], 92)
operation = consume(self.user, self.product, 6, 'pieces', package_id=item.api_id)
item.refresh_from_db()
self.assertEqual((item.quantity, item.remaining_pieces, item.remaining_amount, item.opened),
(1, 4, Decimal('92'), True))
self.assertEqual(operation.lines.get().amount, Decimal('138'))
consume(self.user, self.product, 46, 'g', package_id=item.api_id)
item.refresh_from_db()
self.assertEqual((item.remaining_pieces, item.remaining_amount), (2, Decimal('46')))
with self.assertRaisesMessage(StockError, 'whole pieces'):
consume(self.user, self.product, 20, 'g', package_id=item.api_id)
item.refresh_from_db()
self.assertEqual((item.remaining_pieces, item.remaining_amount), (2, Decimal('46')))
self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 2)
def test_api_converts_legacy_count_and_deducts_sausages(self):
_, token = create_token(self.user, 'inventory test', {'inventory:read', 'inventory:write'})
headers = {'HTTP_AUTHORIZATION': f'Bearer {token}'}
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
legacy = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, quantity=10)
url = f'/api/v1/kitchen/items/{legacy.api_id}/'
missing_count = self.client.patch(url, data=json.dumps({'pieces_per_package': 12}),
content_type='application/json', **headers)
self.assertEqual(missing_count.status_code, 400)
converted = self.client.patch(url, data=json.dumps({'quantity': 1,
'pieces_per_package': 12, 'remaining_pieces': 10, 'opened': True}),
content_type='application/json', **headers)
self.assertEqual(converted.status_code, 200, converted.content[:500])
self.assertEqual(converted.json()['remaining_pieces'], 10)
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.user).count(), 1)
self.assertEqual(converted.json()['unit'], 'pieces')
result = self.client.post('/api/v1/kitchen/consumption/',
data=json.dumps({'product_id': str(self.product.api_id), 'amount': 2,
'unit': 'pieces', 'package_id': str(legacy.api_id)}),
content_type='application/json', HTTP_IDEMPOTENCY_KEY='rolls-2', **headers)
self.assertEqual(result.status_code, 200, result.content[:500])
legacy.refresh_from_db()
self.assertEqual(legacy.remaining_pieces, 8)
def test_piece_conversion_requires_explicit_amount(self):
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
item = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('230'), remaining_amount=Decimal('230'),
inventory_unit='g', pieces_per_package=10, remaining_pieces=10)
with self.assertRaisesMessage(StockError, 'explicit amount per piece'):
preview(self.user, self.product, 6, 'pieces', package_id=item.api_id)
def test_api_corrects_one_legacy_can_without_creating_stock(self):
_, token = create_token(self.user, 'can correction', {'inventory:read', 'inventory:write'})
headers = {'HTTP_AUTHORIZATION': f'Bearer {token}'}
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
can = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, quantity=1, notes='10 sausages; 230 g drained weight')
other = KitchenInventoryItem.objects.create(user=self.other,
product=FoodProduct.objects.create(owner=self.other, product_name='Other stock'),
location=InventoryLocation.objects.create(user=self.other, name='Other pantry'), quantity=3)
response = self.client.patch(f'/api/v1/kitchen/items/{can.api_id}/',
data=json.dumps({'quantity': 1, 'original_amount': '230', 'unit': 'g',
'pieces_per_package': 10, 'remaining_pieces': 4, 'piece_amount': '23',
'opened': True}), content_type='application/json', **headers)
self.assertEqual(response.status_code, 200, response.content[:500])
can.refresh_from_db()
other.refresh_from_db()
self.assertEqual((can.remaining_amount, can.remaining_pieces, can.quantity),
(Decimal('92'), 4, 1))
self.assertEqual(other.quantity, 3)
stock = self.client.get('/api/v1/kitchen/stock/',
{'product_id': str(self.product.api_id)}, **headers).json()['products'][0]
self.assertEqual(Decimal(stock['totals']['g']), Decimal('92'))
self.assertEqual(stock['totals']['pieces'], '4')
def test_api_piece_update_rollback_on_invalid_metadata(self):
_, token = create_token(self.user, 'atomic correction', {'inventory:read', 'inventory:write'})
location = InventoryLocation.objects.create(user=self.user, name='Pantry')
can = KitchenInventoryItem.objects.create(user=self.user, product=self.product,
location=location, original_amount=Decimal('230'), remaining_amount=Decimal('230'),
inventory_unit='g', pieces_per_package=10, remaining_pieces=10,
piece_amount=Decimal('23'))
response = self.client.patch(f'/api/v1/kitchen/items/{can.api_id}/',
data=json.dumps({'remaining_pieces': 4, 'location': ''}),
content_type='application/json', HTTP_AUTHORIZATION=f'Bearer {token}')
self.assertEqual(response.status_code, 400)
can.refresh_from_db()
self.assertEqual((can.remaining_amount, can.remaining_pieces), (Decimal('230'), 10))
self.assertFalse(InventoryConsumption.objects.filter(user=self.user).exists())
+368
View File
@@ -0,0 +1,368 @@
from datetime import timedelta
from decimal import Decimal
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
from django.utils import timezone
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, 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
from food.services.openfoodfacts import OpenFoodFactsTransientError
from planner.services.notifications import NotificationError
class InventoryScanQueueTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='scanner-owner', password='test-password')
self.other = get_user_model().objects.create_user(username='scanner-other', password='test-password')
self.fridge = InventoryLocation.objects.create(user=self.user, name='Fridge')
self.shelf = InventoryLocation.objects.create(user=self.user, name='Shelf')
self.product = FoodProduct.objects.create(owner=self.user, barcode='12345678',
product_name='Oat drink', package_amount=Decimal('1000'), package_unit='ml')
def _confirmed_item(self, location=None, barcode='12345678'):
run = get_or_create_active_run(self.user, (location or self.fridge).pk)
item = create_active_scan(run, self.user, barcode)
confirm_scan_item(self.user, item.pk, {
'location_id': (location or self.fridge).pk, 'product_name': 'Oat drink',
'package_count': 2, 'package_amount': '1000', 'package_unit': 'ml',
})
return run, item
def test_location_batches_are_atomic_and_keep_original_locations(self):
run, item = self._confirmed_item()
batch = item.batch
updated = submit_batch(self.user, batch_id=batch.pk, next_location_id=self.shelf.pk)
batch.refresh_from_db()
new_batch = updated.batches.get(status=InventoryScanBatch.Status.DRAFT)
self.assertEqual((batch.status, batch.location), (InventoryScanBatch.Status.QUEUED, self.fridge))
self.assertEqual(new_batch.location, self.shelf)
self.assertEqual(item.location, self.fridge)
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')
with self.assertRaises(ScanWorkflowError):
submit_batch(self.user, batch_id=item.batch_id, next_location_id=foreign.pk)
item.refresh_from_db()
self.assertEqual(item.status, InventoryScanItem.Status.CONFIRMED)
def test_active_run_resumes_and_rejects_second_active_scan(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, '12345678')
self.assertEqual(get_or_create_active_run(self.user, self.shelf.pk).pk, run.pk)
with self.assertRaises(ScanWorkflowError):
create_active_scan(run, self.user, '87654321')
def test_done_enqueues_and_worker_creates_separate_tracked_packages(self):
run, item = self._confirmed_item()
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner._send_completion_notification') as notify:
self.assertTrue(process_next_scan_item())
item.refresh_from_db()
run.refresh_from_db()
self.assertEqual(item.status, InventoryScanItem.Status.COMPLETE)
self.assertEqual(item.inventory_item.product, self.product)
stock = KitchenInventoryItem.objects.filter(user=self.user, product=self.product)
self.assertEqual(stock.count(), 2)
self.assertTrue(all(row.original_amount == Decimal('1000') and row.inventory_unit == 'ml' for row in stock))
self.assertEqual(run.status, InventoryScanRun.Status.COMPLETE)
notify.assert_called_once_with(run.pk)
def test_transient_error_is_scheduled_and_bounded_by_ten_attempts(self):
run, item = self._confirmed_item(barcode='87654321')
submit_batch(self.user, batch_id=item.batch_id, finish=True)
def transient_request(*args, **kwargs):
kwargs['on_request_start']()
raise OpenFoodFactsTransientError('temporary failure', retry_after=30)
with patch('food.services.inventory_scanner.cached_product', side_effect=transient_request):
process_next_scan_item()
item.refresh_from_db()
self.assertEqual(item.attempts, 1)
self.assertEqual(item.status, InventoryScanItem.Status.QUEUED)
self.assertGreaterEqual(item.next_attempt_at, timezone.now() + timedelta(seconds=29))
def test_tenth_actual_transient_request_moves_item_to_review(self):
run, item = self._confirmed_item(barcode='87654321')
submit_batch(self.user, batch_id=item.batch_id, finish=True)
InventoryScanItem.objects.filter(pk=item.pk).update(attempts=9)
def transient_request(*args, **kwargs):
kwargs['on_request_start']()
raise OpenFoodFactsTransientError('temporary failure')
with patch('food.services.inventory_scanner.cached_product', side_effect=transient_request):
process_next_scan_item()
item.refresh_from_db()
self.assertEqual(item.attempts, 10)
self.assertEqual(item.status, InventoryScanItem.Status.NEEDS_REVIEW)
def test_unknown_product_moves_to_review_without_losing_user_fields(self):
run, item = self._confirmed_item(barcode='87654321')
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None):
process_next_scan_item()
item.refresh_from_db()
self.assertEqual(item.status, InventoryScanItem.Status.NEEDS_REVIEW)
self.assertEqual(item.product_name, 'Oat drink')
self.assertEqual(item.location, self.fridge)
self.assertIsNone(item.inventory_item)
class OpenFoodFactsGlobalLimitTests(TestCase):
def test_non_waiting_request_is_refused_when_shared_budget_is_full(self):
now = timezone.now()
OpenFoodFactsRequest.objects.bulk_create([
OpenFoodFactsRequest(requested_at=now - timedelta(seconds=10 * index), endpoint='product')
for index in range(5)
])
with self.assertRaises(OpenFoodFactsRateLimited):
with off_http_request('search', wait=False):
self.fail('The sixth actual request must not start.')
self.assertEqual(OpenFoodFactsRequest.objects.count(), 5)
def test_failed_actual_request_still_consumes_budget(self):
with self.assertRaises(RuntimeError):
with off_http_request('product', wait=False):
raise RuntimeError('network error after request start')
self.assertEqual(OpenFoodFactsRequest.objects.count(), 1)
class InventoryReviewServiceTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(username='review-owner', password='test-password')
self.fridge = InventoryLocation.objects.create(user=self.user, name='Fridge')
self.shelf = InventoryLocation.objects.create(user=self.user, name='Shelf')
def _staged_item(self, barcode):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, barcode)
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk,
'product_name': 'Review beans', 'package_count': 2})
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None):
process_next_scan_item()
item.refresh_from_db()
return item
def test_mode_preference_persists_and_review_edits_are_saved(self):
item = self._staged_item('87654321')
self.assertEqual(update_review_preference(self.user, 'bulk').mode, 'bulk')
saved = save_review_item(self.user, item.pk, {'product_name': 'Edited beans',
'package_count': '3', 'location_id': self.shelf.pk, 'energy_kcal_100': '0'})
self.assertEqual((saved.product_name, saved.package_count, saved.location),
('Edited beans', 3, self.shelf))
self.assertEqual(saved.source_data['nutrition']['energy_kcal_100'], '0.000')
self.assertEqual(InventoryReviewPreference.objects.get(user=self.user).mode, 'bulk')
def test_repeated_confirmed_barcode_increments_pending_package_with_undo(self):
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': 'Beans'})
repeated = create_active_scan(run, self.user, '87654321')
self.assertEqual(repeated.pk, item.pk)
self.assertEqual(repeated.package_count, 2)
adjusted = adjust_confirmed_count(self.user, item.pk, -1)
self.assertEqual(adjusted.package_count, 1)
def test_individual_approval_keeps_unknown_nutrition_null_and_zero_known(self):
item = self._staged_item('87654321')
approved = approve_scan_item(self.user, item.pk, {
'product_name': 'Review beans', 'package_count': '2', 'location_id': self.fridge.pk,
'energy_kcal_100': '0', 'fat_100': '',
})
approved.product.refresh_from_db()
self.assertEqual(approved.status, InventoryScanItem.Status.COMPLETE)
self.assertEqual(approved.product.energy_kcal_100, Decimal('0.000'))
self.assertIsNone(approved.product.fat_100)
stock = KitchenInventoryItem.objects.get(product=approved.product)
self.assertEqual(stock.quantity, 2)
def test_completion_notification_retries_with_stable_ntfy_sequence_id(self):
run = InventoryScanRun.objects.create(user=self.user, selected_location=self.fridge,
status=InventoryScanRun.Status.COMPLETE_WITH_REVIEW, completed_at=timezone.now())
with patch('planner.services.notifications.send_notification', side_effect=NotificationError('offline')) as send:
dispatch_pending_scan_notifications()
run.refresh_from_db()
self.assertIsNotNone(run.notification_attempted_at)
self.assertIsNone(run.notification_sent_at)
first_sequence_id = send.call_args.kwargs['sequence_id']
InventoryScanRun.objects.filter(pk=run.pk).update(
notification_attempted_at=timezone.now() - timedelta(seconds=61))
with patch('planner.services.notifications.send_notification', return_value=True) as send:
dispatch_pending_scan_notifications()
self.assertEqual(send.call_args.kwargs['sequence_id'], first_sequence_id)
dispatch_pending_scan_notifications()
send.assert_called_once()
run.refresh_from_db()
self.assertIsNotNone(run.notification_sent_at)
def test_bulk_approval_applies_shared_fields_to_selected_items_atomically(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
items = []
for barcode, name in (('87654321', 'Beans'), ('87654322', 'Rice')):
item = create_active_scan(run, self.user, barcode)
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk, 'product_name': name})
items.append(item)
submit_batch(self.user, batch_id=items[0].batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None), \
patch('food.services.inventory_scanner._send_completion_notification'):
process_next_scan_item()
process_next_scan_item()
approved = approve_scan_items(self.user, [item.pk for item in items], {
'location_id': self.shelf.pk, 'category_name': 'Dry goods'})
self.assertEqual(len(approved), 2)
self.assertTrue(all(item.status == InventoryScanItem.Status.COMPLETE for item in approved))
self.assertTrue(all(item.inventory_item.location == self.shelf for item in approved))
self.assertEqual(KitchenInventoryItem.objects.filter(user=self.user, category__name='Dry goods').count(), 2)
@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')
self.assertContains(response, '<option value="" selected disabled>Choose a location</option>', 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)
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_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'<option value="{self.pantry.pk}" selected>Pantry</option>', 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]),
{'barcode': '1234567890123'})
self.assertEqual(response.status_code, 200)
item_id = response.json()['item']['id']
self.assertIn('Confirm &amp; 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)
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()
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)
def test_review_mode_switch_saves_edits_and_bulk_preview_shows_selected_products(self):
run = get_or_create_active_run(self.user, self.fridge.pk)
item = create_active_scan(run, self.user, '1234567890123')
confirm_scan_item(self.user, item.pk, {'location_id': self.fridge.pk, 'product_name': 'Lentils'})
submit_batch(self.user, batch_id=item.batch_id, finish=True)
with patch('food.services.inventory_scanner.cached_product', return_value=None):
process_next_scan_item()
item.refresh_from_db()
response = self.client.post(reverse('food:inventory-review-item', args=[item.pk]), {
'action': 'mode', 'mode': 'bulk', 'product_name': 'Green lentils', 'brand': '',
'location_id': self.pantry.pk, 'category_name': 'Pulses', 'package_count': '1',
'package_amount': '', 'package_unit': '', 'notes': '',
})
self.assertRedirects(response, reverse('food:inventory-review') + '?mode=bulk', fetch_redirect_response=False)
item.refresh_from_db()
self.assertEqual((item.product_name, item.location, item.category_name),
('Green lentils', self.pantry, 'Pulses'))
response = self.client.post(reverse('food:inventory-review'), {
'action': 'preview', 'item_ids': [str(item.pk)], 'location_id': self.fridge.pk,
'category_name': 'Dry goods',
})
self.assertContains(response, 'Preview selected products')
self.assertContains(response, 'Green lentils')
def test_deferred_items_have_separate_state_and_missing_names_are_individual_only(self):
run = InventoryScanRun.objects.create(user=self.user, selected_location=self.fridge)
batch = InventoryScanBatch.objects.create(run=run, location=self.fridge, sequence=1)
item = InventoryScanItem.objects.create(batch=batch, location=self.fridge, barcode='9876543210123',
status=InventoryScanItem.Status.DEFERRED, last_error='A name is needed.')
response = self.client.post(reverse('food:inventory-review'), {
'action': 'mode', 'mode': 'bulk', 'state': 'deferred'})
self.assertRedirects(response, reverse('food:inventory-review') + '?mode=bulk&state=deferred',
fetch_redirect_response=False)
response = self.client.get(reverse('food:inventory-review'), {'mode': 'bulk', 'state': 'deferred'})
self.assertContains(response, 'Deferred scan items')
self.assertContains(response, f'name="item_ids" value="{item.pk}" disabled')
self.assertEqual(response.context['eligible_bulk_count'], 0)
self.assertContains(response, 'data-bulk-preview-submit disabled')
+30 -1
View File
@@ -12,7 +12,9 @@ from planner.models import UserSettings
from .services.diary import diary_context, ring_progress
from .models import FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit, InventoryLocation, KitchenInventoryItem, InventoryConsumption
from .models import (FoodFavourite, FoodLogAttachment, FoodLogEntry, FoodPortion, FoodProduct, MealType, Unit,
InventoryLocation, KitchenInventoryItem, InventoryConsumption, InventoryScanRun,
InventoryScanBatch, InventoryScanItem)
class FoodFoundationTests(TestCase):
@@ -21,6 +23,33 @@ class FoodFoundationTests(TestCase):
self.other = get_user_model().objects.create_user(username='food-two', password='test-password')
self.product = FoodProduct.objects.create(owner=self.user, product_name='Yoghurt', barcode='123', base_unit=Unit.GRAM)
def test_inventory_staging_counts_refresh_and_are_user_scoped(self):
location = InventoryLocation.objects.create(user=self.user, name='Fridge')
run = InventoryScanRun.objects.create(user=self.user)
batch = InventoryScanBatch.objects.create(run=run, location=location, sequence=1)
InventoryScanItem.objects.create(batch=batch, location=location, barcode='111',
status=InventoryScanItem.Status.QUEUED)
InventoryScanItem.objects.create(batch=batch, location=location, barcode='222',
status=InventoryScanItem.Status.FAILED)
other_location = InventoryLocation.objects.create(user=self.other, name='Other fridge')
other_run = InventoryScanRun.objects.create(user=self.other)
other_batch = InventoryScanBatch.objects.create(run=other_run, location=other_location, sequence=1)
InventoryScanItem.objects.create(batch=other_batch, location=other_location, barcode='333',
status=InventoryScanItem.Status.PROCESSING)
self.client.force_login(self.user)
url = reverse('food:inventory-staging-counts')
response = self.client.get(url, secure=True)
self.assertEqual(response.status_code, 200)
self.assertContains(response, '<strong>1</strong>', html=True)
self.assertContains(response, '<strong>1</strong>', html=True)
self.assertContains(response, 'hx-trigger="every 5s"')
InventoryScanItem.objects.filter(batch=batch, barcode='111').update(status=InventoryScanItem.Status.COMPLETE)
response = self.client.get(url, secure=True)
self.assertContains(response, '<strong>0</strong>', html=True)
self.assertContains(response, '<strong>1</strong>', html=True)
def test_meals_are_fixed(self):
self.assertEqual(list(MealType.values), ['breakfast', 'lunch', 'dinner', 'snacks'])
+13 -1
View File
@@ -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'
@@ -8,6 +8,7 @@ urlpatterns = [
path('settings/tokens/', token_views.tokens, name='tokens'),
path('settings/tokens/<int:pk>/revoke/', token_views.revoke_token, name='token-revoke'),
path('inventory/', inventory.overview, name='inventory'),
path('inventory/staging-counts/', inventory.inventory_staging_counts, name='inventory-staging-counts'),
path('inventory/add/', inventory.add, name='inventory-add'),
path('inventory/lookup/', inventory.lookup, name='inventory-lookup'),
path('inventory/search/openfoodfacts/', inventory.external_search, name='inventory-external'),
@@ -18,6 +19,17 @@ 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/batches/<int:batch_id>/location/', scan_views.change_scan_location, name='inventory-scan-location'),
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('inventory/review/', scan_views.inventory_review, name='inventory-review'),
path('inventory/review/items/<int:item_id>/', scan_views.review_item, name='inventory-review-item'),
path('', views.diary, name='diary'),
path('add/', views.add_food, name='add'),
path('search/openfoodfacts/', views.external_search, name='external-search'),
+1 -1
View File
@@ -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
+1 -1
View File
@@ -40,7 +40,7 @@ cd main/frontend
npm ci
npm run build
cd /home/jorenmartijn/django
VITE_USE_DEV_SERVER=false tasksnest/bin/python main/manage.py collectstatic
VITE_USE_DEV_SERVER=false tasksnest-host/bin/python main/manage.py collectstatic
```
`npm run build` writes hashed assets and `.vite/manifest.json` to
+2 -2
View File
@@ -5,10 +5,10 @@
"scripts": {
"dev": "concurrently --kill-others-on-fail --names assets,django --prefix-colors cyan,green \"npm run dev:assets\" \"npm run dev:django\"",
"dev:assets": "vite build --watch",
"dev:django": "VITE_USE_DEV_SERVER=false ../../tasksnest/bin/python ../manage.py runserver 0.0.0.0:1234",
"dev:django": "VITE_USE_DEV_SERVER=false ../../tasksnest-host/bin/python ../manage.py runserver 0.0.0.0:1234",
"dev:hmr": "concurrently --kill-others-on-fail --names vite,django --prefix-colors cyan,green \"npm run dev:vite\" \"npm run dev:django:hmr\"",
"dev:vite": "vite",
"dev:django:hmr": "VITE_USE_DEV_SERVER=true ../../tasksnest/bin/python ../manage.py runserver 0.0.0.0:1234",
"dev:django:hmr": "VITE_USE_DEV_SERVER=true ../../tasksnest-host/bin/python ../manage.py runserver 0.0.0.0:1234",
"build": "vite build",
"preview": "vite preview"
},
+42 -4
View File
@@ -105,6 +105,16 @@ class GroceryInput(BaseModel):
notes: str = ''
opened: bool = False
best_before: str | None = None
original_amount: Decimal | None = Field(default=None, gt=0)
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None
pieces_per_package: int | None = Field(default=None, ge=1)
remaining_pieces: int | None = Field(default=None, ge=0)
piece_amount: Decimal | None = Field(default=None, gt=0)
inner_packs_per_package: int | None = Field(default=None, ge=1)
pieces_per_inner_pack: int | None = Field(default=None, ge=1)
inner_pack_amount: Decimal | None = Field(default=None, gt=0)
inner_pack_label: str | None = None
piece_label: str | None = None
class InventoryUpdate(BaseModel):
@@ -115,6 +125,16 @@ class InventoryUpdate(BaseModel):
notes: str | None = None
opened: bool | None = None
remaining_amount: Decimal | None = Field(default=None, ge=0)
original_amount: Decimal | None = Field(default=None, gt=0)
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None
pieces_per_package: int | None = Field(default=None, ge=1)
remaining_pieces: int | None = Field(default=None, ge=0)
piece_amount: Decimal | None = Field(default=None, gt=0)
inner_packs_per_package: int | None = Field(default=None, ge=1)
pieces_per_inner_pack: int | None = Field(default=None, ge=1)
inner_pack_amount: Decimal | None = Field(default=None, gt=0)
inner_pack_label: str | None = None
piece_label: str | None = None
best_before: str | None = None
@@ -355,7 +375,10 @@ def _entry(entry):
def _inventory(item):
return {key: item.get(key) for key in ('id', 'product_id', 'product_name', 'brand', 'barcode',
'quantity', 'location', 'category', 'opened', 'best_before', 'notes',
'remaining_amount', 'original_amount', 'unit', 'status', 'archived_at')}
'remaining_amount', 'original_amount', 'unit', 'package_count', 'pieces_per_package',
'remaining_pieces', 'piece_amount', 'inner_packs_per_package', 'pieces_per_inner_pack',
'inner_pack_amount', 'inner_pack_label', 'piece_label', 'remaining_full_inner_packs',
'opened_inner_pack_pieces', 'status', 'archived_at')}
def _key(value):
@@ -534,15 +557,30 @@ def create_server() -> MCPServer:
data = await api_request('GET', 'kitchen/items/', params={'search': query, 'limit': min(max(limit, 1), 100)})
return {'count': data['count'], 'items': [_inventory(item) for item in data['results']]}
@server.tool(structured_output=True, description='Add an owned saved food product to the authenticated user’s kitchen inventory. Quantity counts whole items; location and category use TaskNest’s existing names. Reuse idempotency_key on retries.')
@server.tool(structured_output=True, description='Add an owned saved food product to the authenticated user’s kitchen inventory. Quantity counts outer packages. Optional nested fields define inner_packs_per_package × pieces_per_inner_pack; inner_pack_amount is the measured amount per inner pack, from which per-piece weight is estimated. Do not infer measured amounts. Reuse idempotency_key on retries.')
async def inventory_add(product_id: str, quantity: int, location: str, category: str | None = None,
notes: str = '', opened: bool = False, best_before: str | None = None,
original_amount: Decimal | None = None,
unit: Literal['mg', 'g', 'kg', 'ml', 'L', 'pieces', 'packs', 'portions'] | None = None,
pieces_per_package: int | None = None, remaining_pieces: int | None = None,
piece_amount: Decimal | None = None,
inner_packs_per_package: int | None = None, pieces_per_inner_pack: int | None = None,
inner_pack_amount: Decimal | None = None, inner_pack_label: str | None = None,
piece_label: str | None = None,
idempotency_key: str | None = None) -> dict[str, Any]:
key = _key(idempotency_key)
payload = {'product_id': product_id, 'quantity': quantity, 'location': location,
'notes': notes, 'opened': opened}
if category is not None: payload['category'] = category
if best_before is not None: payload['best_before'] = best_before
for name, value in (('original_amount', original_amount), ('unit', unit),
('pieces_per_package', pieces_per_package),
('remaining_pieces', remaining_pieces), ('piece_amount', piece_amount),
('inner_packs_per_package', inner_packs_per_package),
('pieces_per_inner_pack', pieces_per_inner_pack),
('inner_pack_amount', inner_pack_amount), ('inner_pack_label', inner_pack_label),
('piece_label', piece_label)):
if value is not None: payload[name] = str(value) if isinstance(value, Decimal) else value
item = await api_request('POST', 'kitchen/items/', payload=payload, idempotency_key=key)
return {'success': True, 'item': _inventory(item), 'idempotency_key': key}
@@ -555,7 +593,7 @@ def create_server() -> MCPServer:
'create_missing_products': create_missing_products}, idempotency_key=key)
return {**data, 'idempotency_key': key}
@server.tool(structured_output=True, description='Update only the supplied fields of one inventory item belonging to the authenticated user. Changes existing data.')
@server.tool(structured_output=True, description='Update only supplied inventory fields. Quantity is outer-package count. Nested packages can specify inner-pack count, pieces per inner pack, and measured amount per inner pack; estimated piece amounts are derived from those values. Partial deductions by pieces, inner_packs, or matching g/ml are atomic; unsupported conversions return an error.')
async def inventory_update(item_id: str, changes: InventoryUpdate) -> dict[str, Any]:
item = await api_request('PATCH', f'kitchen/items/{item_id}/',
payload=changes.model_dump(mode='json', exclude_unset=True), return_validation=True)
@@ -595,7 +633,7 @@ def create_server() -> MCPServer:
params = {'product_id': product_id, 'query': query, 'location_id': location_id}
return await api_request('GET', 'kitchen/stock/', params={k: v for k, v in params.items() if v is not None})
@server.tool(structured_output=True, description='Preview exact package deductions for one owned product without changing stock. A shortage is reported rather than silently consumed.')
@server.tool(structured_output=True, description='Preview package deductions for one owned product without changing stock. Supports pieces and inner_packs when packaging is configured, plus matching g/ml amounts. Nested per-piece weights are estimates derived from measured inner-pack amounts; unsupported conversions return a clear error.')
async def inventory_preview_consumption(product_id: str, amount: Decimal, unit: str,
package_id: str | None = None) -> dict[str, Any]:
return await api_request('POST', 'kitchen/consumption/preview/', payload={
+7 -4
View File
@@ -9,11 +9,14 @@ class NotificationError(Exception):
"""A delivery error safe to display without exposing the topic URL."""
def send_ntfy_notification(url, title, message, timeout=10):
def send_ntfy_notification(url, title, message, timeout=10, sequence_id=None):
headers = {'Content-Type': 'text/plain; charset=utf-8', 'Title': title}
if sequence_id:
headers['X-Sequence-ID'] = str(sequence_id)[:64]
request = Request(
url,
data=message.encode('utf-8'),
headers={'Content-Type': 'text/plain; charset=utf-8', 'Title': title},
headers=headers,
method='POST',
)
try:
@@ -29,9 +32,9 @@ def send_ntfy_notification(url, title, message, timeout=10):
raise NotificationError(f'ntfy server responded with HTTP {status}.')
def send_notification(user, title, message):
def send_notification(user, title, message, *, sequence_id=None):
preferences = UserSettings.objects.filter(user=user).first()
if not preferences or not preferences.ntfy_enabled or not preferences.ntfy_url:
return False
send_ntfy_notification(preferences.ntfy_url, title, message)
send_ntfy_notification(preferences.ntfy_url, title, message, sequence_id=sequence_id)
return True
+13 -1
View File
@@ -5,7 +5,7 @@ from django.test import TestCase
from django.urls import reverse
from .models import UserSettings
from .services.notifications import NotificationError, send_notification
from .services.notifications import NotificationError, send_notification, send_ntfy_notification
class NtfySettingsTests(TestCase):
@@ -47,3 +47,15 @@ class NtfySettingsTests(TestCase):
def test_disabled_preference_suppresses_delivery(self, sender):
self.assertFalse(send_notification(self.user, 'Title', 'Message'))
sender.assert_not_called()
@patch('planner.services.notifications.urlopen')
def test_send_ntfy_notification_includes_stable_sequence_id(self, urlopen):
response = Mock()
response.getcode.return_value = 200
urlopen.return_value.__enter__.return_value = response
send_ntfy_notification(self.topic, 'Title', 'Message', sequence_id='inventory-scan-123')
request = urlopen.call_args.args[0]
headers = {key.lower(): value for key, value in request.header_items()}
self.assertEqual(headers['x-sequence-id'], 'inventory-scan-123')