from decimal import Decimal from django.contrib.auth import get_user_model from django.test import TestCase from django.utils import timezone from .models import FoodProduct, InventoryConsumption, InventoryLocation, KitchenInventoryItem from .services.inventory_consumption import StockError, consume, normalized, preview, undo class InventoryConsumptionTests(TestCase): def setUp(self): self.user = get_user_model().objects.create_user(username='stock-owner') self.other = get_user_model().objects.create_user(username='stock-other') self.product = FoodProduct.objects.create(owner=self.user, product_name='Butter', package_amount=250, package_unit='g') self.location = InventoryLocation.objects.create(user=self.user, name='Fridge') def package(self, amount='250', remaining='250', opened=False, best_before=None): return KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location, original_amount=Decimal(amount), remaining_amount=Decimal(remaining), inventory_unit='g', opened=opened, best_before=best_before) def test_partial_across_packages_and_undo(self): first, second = self.package(), self.package() one = consume(self.user, self.product, '150', 'g') first.refresh_from_db(); second.refresh_from_db() self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250'))) self.assertTrue(first.opened) two = consume(self.user, self.product, '150', 'g') first.refresh_from_db(); second.refresh_from_db() self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('0'), Decimal('200'))) self.assertIsNotNone(first.archived_at) self.assertEqual(list(two.lines.values_list('amount', flat=True)), [Decimal('100'), Decimal('50')]) with self.assertRaises(StockError): undo(self.user, one.pk) undo(self.user, two.pk) first.refresh_from_db(); second.refresh_from_db() self.assertEqual((first.remaining_amount, second.remaining_amount), (Decimal('100'), Decimal('250'))) undo(self.user, one.pk) first.refresh_from_db() self.assertFalse(first.opened) self.assertEqual(first.remaining_amount, Decimal('250')) def test_priority_shortage_and_target(self): late = self.package(best_before=timezone.localdate() + timezone.timedelta(days=10)) early = self.package(best_before=timezone.localdate() + timezone.timedelta(days=1)) opened = self.package(remaining='80', opened=True) plan = preview(self.user, self.product, '100', 'g') self.assertEqual([row['package'].pk for row in plan['deductions']], [opened.pk, early.pk]) self.assertEqual(preview(self.user, self.product, '300', 'g', package_id=late.api_id)['shortage'], Decimal('50')) with self.assertRaises(StockError): consume(self.user, self.product, '300', 'g', package_id=late.api_id) late.refresh_from_db() self.assertEqual(late.remaining_amount, Decimal('250')) def test_units_idempotency_isolation_and_validation(self): package = self.package() self.assertEqual(normalized('0.25', 'kg')[0], Decimal('250')) self.assertEqual(normalized('1', 'L')[0], Decimal('1000')) operation = consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp') self.assertEqual(consume(self.user, self.product, '.1', 'kg', idempotency_key='use-once', source='mcp').pk, operation.pk) self.assertEqual(InventoryConsumption.objects.filter(user=self.user).count(), 1) with self.assertRaises(StockError): consume(self.user, self.product, '.2', 'kg', idempotency_key='use-once', source='mcp') with self.assertRaises(StockError): preview(self.other, self.product, 1, 'g') for amount, unit in [('-1', 'g'), ('0', 'g'), ('1.0001', 'g'), ('1', 'ml')]: if unit == 'ml': self.assertEqual(preview(self.user, self.product, amount, unit)['shortage'], Decimal(1)) else: with self.assertRaises(StockError): preview(self.user, self.product, amount, unit) package.refresh_from_db() self.assertEqual(package.remaining_amount, Decimal('150')) def test_count_based_legacy_stock(self): item = KitchenInventoryItem.objects.create(user=self.user, product=self.product, location=self.location, quantity=3) operation = consume(self.user, self.product, 2, 'packs') item.refresh_from_db() self.assertEqual(item.quantity, 1) undo(self.user, operation.pk) item.refresh_from_db() self.assertEqual(item.quantity, 3) def test_volume_count_and_explicit_partial_use(self): milk = FoodProduct.objects.create(owner=self.user, product_name='Milk') carton = KitchenInventoryItem.objects.create(user=self.user, product=milk, location=self.location, original_amount=Decimal('1'), remaining_amount=Decimal('1'), inventory_unit='L') consume(self.user, milk, '250', 'ml') carton.refresh_from_db() self.assertEqual(carton.remaining_amount, Decimal('.750')) self.assertEqual(preview(self.user, milk, '1', 'L')['shortage'], Decimal('.250')) with self.assertRaises(StockError): consume(self.user, milk, '1', 'L') operation = consume(self.user, milk, '1', 'L', allow_partial=True) self.assertEqual(operation.amount, Decimal('.750')) carton.refresh_from_db() self.assertEqual(carton.remaining_amount, Decimal(0)) eggs = FoodProduct.objects.create(owner=self.user, product_name='Eggs') box = KitchenInventoryItem.objects.create(user=self.user, product=eggs, location=self.location, original_amount=Decimal('6'), remaining_amount=Decimal('6'), inventory_unit='pieces') consume(self.user, eggs, 2, 'pieces') box.refresh_from_db() self.assertEqual(box.remaining_amount, Decimal(4)) with self.assertRaises(StockError): consume(self.user, eggs, '.5', 'pieces') from django.db import connection from django.db.migrations.executor import MigrationExecutor from django.test import TransactionTestCase class InventoryMigrationTests(TransactionTestCase): migrate_from = ('food', '0005_package_contents') migrate_to = ('food', '0007_inventory_reversal_state') def test_existing_counts_split_only_when_package_size_known(self): executor = MigrationExecutor(connection) executor.migrate([self.migrate_from]) old = executor.loader.project_state([self.migrate_from]).apps User = old.get_model('auth', 'User') Product = old.get_model('food', 'FoodProduct') Location = old.get_model('food', 'InventoryLocation') Item = old.get_model('food', 'KitchenInventoryItem') user = User.objects.create(username='migration-stock-user') location = Location.objects.create(user_id=user.pk, name='Pantry') known = Product.objects.create(owner_id=user.pk, product_name='Butter', package_amount=Decimal('250'), package_unit='g') unknown = Product.objects.create(owner_id=user.pk, product_name='Loose eggs') Item.objects.create(user_id=user.pk, product_id=known.pk, location_id=location.pk, quantity=2, opened=True, remaining_amount=Decimal('100')) Item.objects.create(user_id=user.pk, product_id=unknown.pk, location_id=location.pk, quantity=6) executor = MigrationExecutor(connection) executor.migrate([self.migrate_to]) new = executor.loader.project_state([self.migrate_to]).apps migrated = list(new.get_model('food', 'KitchenInventoryItem').objects.filter( user_id=user.pk, product_id=known.pk).order_by('pk')) self.assertEqual([(i.original_amount, i.remaining_amount, i.quantity, i.location_id) for i in migrated], [(Decimal('250'), Decimal('100'), 1, location.pk), (Decimal('250'), Decimal('250'), 1, location.pk)]) legacy = new.get_model('food', 'KitchenInventoryItem').objects.get(user_id=user.pk, product_id=unknown.pk) self.assertEqual((legacy.quantity, legacy.original_amount), (6, None)) from concurrent.futures import ThreadPoolExecutor from django.db import OperationalError, close_old_connections class ConcurrentInventoryConsumptionTests(TransactionTestCase): def test_competing_requests_do_not_overconsume(self): user = get_user_model().objects.create_user(username='parallel-stock-user') product = FoodProduct.objects.create(owner=user, product_name='One carton') location = InventoryLocation.objects.create(user=user, name='Fridge') item = KitchenInventoryItem.objects.create(user=user, product=product, location=location, original_amount=Decimal('100'), remaining_amount=Decimal('100'), inventory_unit='ml') def use(): close_old_connections() try: return consume(user, product, 80, 'ml').pk except (StockError, OperationalError): return None finally: close_old_connections() with ThreadPoolExecutor(max_workers=2) as pool: results = list(pool.map(lambda _: use(), range(2))) item.refresh_from_db() self.assertEqual(sum(result is not None for result in results), 1) self.assertEqual(item.remaining_amount, Decimal('20')) self.assertEqual(InventoryConsumption.objects.filter(user=user).count(), 1)