diff --git a/main/API.md b/main/API.md
index fcdf939..6c16f51 100644
--- a/main/API.md
+++ b/main/API.md
@@ -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
diff --git a/main/MCP.md b/main/MCP.md
index 531dc22..14d51e3 100644
--- a/main/MCP.md
+++ b/main/MCP.md
@@ -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.
diff --git a/main/food/api.py b/main/food/api.py
index 00122ba..506db63 100644
--- a/main/food/api.py
+++ b/main/food/api.py
@@ -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))
diff --git a/main/food/api_schema.py b/main/food/api_schema.py
index 411e156..dfaac8d 100644
--- a/main/food/api_schema.py
+++ b/main/food/api_schema.py
@@ -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},
diff --git a/main/food/forms.py b/main/food/forms.py
index 23c2e7a..d82d28a 100644
--- a/main/food/forms.py
+++ b/main/food/forms.py
@@ -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):
diff --git a/main/food/inventory.py b/main/food/inventory.py
index c6deb7c..6cae69f 100644
--- a/main/food/inventory.py
+++ b/main/food/inventory.py
@@ -58,11 +58,20 @@ 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]
return render(request, 'food/inventory_overview.html', {
'items': items, 'cards': list(cards.values()), 'recent_consumption': recent,
@@ -98,7 +107,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 +232,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 +252,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 +274,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', '')})
diff --git a/main/food/migrations/0012_inventoryconsumptionline_after_pieces_and_more.py b/main/food/migrations/0012_inventoryconsumptionline_after_pieces_and_more.py
new file mode 100644
index 0000000..7f01f1e
--- /dev/null
+++ b/main/food/migrations/0012_inventoryconsumptionline_after_pieces_and_more.py
@@ -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),
+ ),
+ ]
diff --git a/main/food/migrations/0013_kitcheninventoryitem_inner_pack_amount_and_more.py b/main/food/migrations/0013_kitcheninventoryitem_inner_pack_amount_and_more.py
new file mode 100644
index 0000000..1fd8d0d
--- /dev/null
+++ b/main/food/migrations/0013_kitcheninventoryitem_inner_pack_amount_and_more.py
@@ -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),
+ ),
+ ]
diff --git a/main/food/migrations/0014_alter_inventoryconsumption_unit.py b/main/food/migrations/0014_alter_inventoryconsumption_unit.py
new file mode 100644
index 0000000..a38bfb8
--- /dev/null
+++ b/main/food/migrations/0014_alter_inventoryconsumption_unit.py
@@ -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),
+ ),
+ ]
diff --git a/main/food/models.py b/main/food/models.py
index 686a8c1..3f6df9b 100644
--- a/main/food/models.py
+++ b/main/food/models.py
@@ -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):
diff --git a/main/food/services/inventory_consumption.py b/main/food/services/inventory_consumption.py
index 77f300e..13fe963 100644
--- a/main/food/services/inventory_consumption.py
+++ b/main/food/services/inventory_consumption.py
@@ -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
diff --git a/main/food/static/food/food.css b/main/food/static/food/food.css
index 2494bc6..94f7db3 100644
--- a/main/food/static/food/food.css
+++ b/main/food/static/food/food.css
@@ -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. */
diff --git a/main/food/static/food/inventory.js b/main/food/static/food/inventory.js
index 2364928..f602d54 100644
--- a/main/food/static/food/inventory.js
+++ b/main/food/static/food/inventory.js
@@ -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';
+});
diff --git a/main/food/templates/food/inventory_add.html b/main/food/templates/food/inventory_add.html
index 831b7cf..f74c7db 100644
--- a/main/food/templates/food/inventory_add.html
+++ b/main/food/templates/food/inventory_add.html
@@ -6,7 +6,7 @@
{% if product.image_url %}{% endif %}
Calculated amount: {{ plan.equivalent_amount|floatformat:-3 }} {{ plan.equivalent_unit }}{% if plan.estimated_piece_weight %} (estimated from measured inner-pack weight){% endif %}
{% endif %}
{% for deduction in plan.deductions %}
{{ 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 %}
{% endfor %}
{% if plan.nutrition %}
Estimated nutrition for this use: {% for nutrient in plan.nutrition %}{{ nutrient.value|floatformat:-1 }} {{ nutrient.unit }} {{ nutrient.label|lower }}{% if not forloop.last %} · {% endif %}{% endfor %}
{% endif %}{% if plan.shortage %}
Shortage: {{ plan.shortage|floatformat:-3 }} {{ plan.unit }}. Choose a partial use explicitly or cancel.