Add nested inventory package tracking

This commit is contained in:
Joren de Graaf
2026-10-26 00:25:00 +01:00
parent 4d76a2bc9c
commit 5217c7f30c
19 changed files with 838 additions and 44 deletions
+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