from django.test import Client from django.urls import reverse from filament.models import InventoryItem, OrderItem from .base import CatalogTestCase class ConsumptionTests(CatalogTestCase): def setUp(self): self.stock = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=2) self.url = reverse("inventory_consume", args=[self.stock.pk]) self.client.force_login(self.alice) def test_grouped_variants_keep_separate_counts_and_reorder_exact_variant(self): refill = InventoryItem.objects.create(owner=self.alice, variant=self.refill, quantity=1) self.assertContains(self.client.get(reverse("inventory")), 'class="stock-group"', count=1) self.assertContains(self.client.get(reverse("inventory")), "Spule verbraucht", count=3) reorder_url = reverse("inventory_consume", args=[refill.pk]) order = OrderItem.objects.create(owner=self.alice, variant=self.refill, quantity=2) self.assertRedirects( self.client.post( reorder_url, {"action": "reorder", "quantity": 1, "variant": self.spool.pk} ), reverse("inventory"), ) self.assertFalse(InventoryItem.objects.filter(pk=refill.pk).exists()) self.stock.refresh_from_db() order.refresh_from_db() self.assertEqual(self.stock.quantity, 2) self.assertEqual(order.quantity, 3) self.assertEqual(OrderItem.objects.count(), 1) def test_consume_only_is_post_and_repeated_confirmation_is_rejected(self): self.assertContains(self.client.get(self.url), "Keine neue Bestellung") body = {"action": "consume", "quantity": 2} self.assertRedirects(self.client.post(self.url, body), reverse("inventory")) self.assertRedirects(self.client.post(self.url, body), self.url) self.stock.refresh_from_db() self.assertEqual(self.stock.quantity, 1) self.assertFalse(OrderItem.objects.exists()) def test_reorder_failure_leaves_stock_untouched(self): order = OrderItem.objects.create(owner=self.alice, variant=self.spool, quantity=9999) payload = {"action": "reorder", "quantity": 2} self.assertRedirects(self.client.post(self.url, payload), self.url) self.spool.is_active = False self.spool.save(update_fields=["is_active"]) self.assertContains(self.client.get(self.url), "kann aktuell nicht bestellt werden") self.assertRedirects(self.client.post(self.url, payload), self.url) order.refresh_from_db() self.stock.refresh_from_db() self.assertEqual(order.quantity, 9999) self.assertEqual(self.stock.quantity, 2) self.assertRedirects( self.client.post(self.url, payload | {"action": "consume"}), reverse("inventory") ) def test_consumption_requires_ownership_and_csrf(self): self.client.force_login(self.bob) payload = {"action": "reorder", "quantity": 2} self.assertEqual(self.client.get(self.url).status_code, 404) self.assertEqual(self.client.post(self.url, payload).status_code, 404) csrf_client = Client(enforce_csrf_checks=True) csrf_client.force_login(self.alice) self.assertEqual(csrf_client.post(self.url, payload).status_code, 403) self.stock.refresh_from_db() self.assertEqual(self.stock.quantity, 2) self.assertFalse(OrderItem.objects.exists())