diff --git a/README.md b/README.md index 8d13253..71b1869 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,10 @@ Keine SPA, keine externen Schriften/Skripte, kein externer Datenbankserver. Unter „Spule verbraucht“ lässt sich eine Rolle ausbuchen und optional ihre Katalogvariante in die Sammelbestellung übernehmen. Die Sammelbestellung ist eine Planungsliste. +Unter **Mein Bestand → Leerrollen** lässt sich die Stückzahl leerer Bambu-Lab-Spulen erfassen. +**Auf Leerrolle aufziehen** bucht eine Spule ab und verschiebt ein Refill in den Bestand mit +Spule. Beim Verbrauch wird eine hinterlegte Bambu-Lab-Spule automatisch zurückgebucht, +auch ohne Nachbestellung. Der Spulenhersteller lässt sich bei Filament auf Spule bearbeiten. Dieses Projekt ist unabhängig vom älteren PHP-Projekt `michael/filament`. ## Betrieb: fertiges Alpine-Python-Image, kein Build diff --git a/config/urls.py b/config/urls.py index a96fe7e..5650de6 100644 --- a/config/urls.py +++ b/config/urls.py @@ -36,10 +36,12 @@ urlpatterns = [ path("drucker//bearbeiten/", views.printer_edit, name="printer_edit"), path("drucker//loeschen/", views.printer_delete, name="printer_delete"), path("bestand/", views.inventory, name="inventory"), + path("bestand/leerrollen/", views.empty_spools, name="empty_spools"), path("bestand/geteilt/", views.shared_inventory, name="shared_inventory"), path("bestand/hinzufuegen/", views.inventory_add, name="inventory_add"), path("bestand//bearbeiten/", views.inventory_edit, name="inventory_edit"), path("bestand//verbrauchen/", views.inventory_consume, name="inventory_consume"), + path("bestand//aufziehen/", views.inventory_mount, name="inventory_mount"), path("bestand//loeschen/", views.inventory_delete, name="inventory_delete"), path("bestellung/", views.orders, name="orders"), path("bestellung/historie/", views.order_history, name="order_history"), diff --git a/filament/forms.py b/filament/forms.py index 6e25cf9..36752c3 100644 --- a/filament/forms.py +++ b/filament/forms.py @@ -48,6 +48,34 @@ class QuantityForm(forms.Form): quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999) +class InventoryQuantityForm(QuantityForm): + expected_quantity = forms.IntegerField( + min_value=1, max_value=9999, required=False, widget=forms.HiddenInput + ) + bambu_spool = forms.TypedChoiceField( + label="Spulenhersteller", + required=False, + choices=[("bambu", "Bambu Lab"), ("other", "Andere Spule")], + coerce=lambda value: value == "bambu", + empty_value=None, + ) + + def __init__(self, *args, item, **kwargs): + super().__init__(*args, **kwargs) + self.initial["bambu_spool"] = "bambu" if item.bambu_spool else "other" + if item.spool_type != Variant.SpoolType.SPOOL: + del self.fields["bambu_spool"] + + +class EmptySpoolQuantityForm(forms.Form): + quantity = forms.IntegerField(label="Bambu-Lab-Leerrollen", min_value=0, max_value=9999) + expected_quantity = forms.IntegerField(min_value=0, max_value=9999, widget=forms.HiddenInput) + + +class MountRefillForm(forms.Form): + quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput) + + class ArticleLookupForm(forms.Form): use_required_attribute = False @@ -105,14 +133,32 @@ class VariantSelectionForm(forms.Form): widget=ColorSelect(attrs={"data-color-select": ""}), ) spool_type = forms.ChoiceField(label="Spulenausführung", choices=[]) + spool_brand = forms.ChoiceField( + label="Spulenhersteller", + required=False, + choices=[ + ("", "Automatisch nach Filamenthersteller"), + ("bambu", "Bambu Lab"), + ("other", "Andere Spule"), + ], + widget=forms.Select(attrs={"data-spool-brand": ""}), + ) quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999, initial=1) def __init__(self, *args, selection=None, for_inventory=False, **kwargs): super().__init__(*args, **kwargs) self.for_inventory = for_inventory + if not for_inventory: + del self.fields["spool_brand"] values = self.data if self.is_bound else (selection or {}) if not self.is_bound: self.initial.update({k: values[k] for k in self.fields if k in values}) + if for_inventory and values.get("spool_type") not in ( + None, + "", + Variant.SpoolType.SPOOL, + ): + self.initial.pop("spool_brand", None) active = Variant.objects.filter(is_active=True) maker = selection_id(values.get("manufacturer")) product = selection_id(values.get("product_type")) @@ -162,6 +208,8 @@ class VariantSelectionForm(forms.Form): spool_field.widget.attrs["disabled"] = True elif not self.is_bound and values.get("spool_type") not in dict(spool_choices): self.initial["spool_type"] = next(key for key, _ in spool_choices if key in spools) + if for_inventory and self["spool_type"].value() != Variant.SpoolType.SPOOL: + del self.fields["spool_brand"] def clean(self): cleaned = super().clean() @@ -182,4 +230,8 @@ class VariantSelectionForm(forms.Form): raise forms.ValidationError( "Diese Variante ist nicht mehr verfügbar. Bitte neu auswählen." ) + if self.for_inventory and cleaned["spool_type"] == Variant.SpoolType.SPOOL: + self.bambu_spool = {"bambu": True, "other": False}.get(cleaned.get("spool_brand")) + else: + self.bambu_spool = False return cleaned diff --git a/filament/migrations/0013_empty_spool_stock.py b/filament/migrations/0013_empty_spool_stock.py new file mode 100644 index 0000000..3392017 --- /dev/null +++ b/filament/migrations/0013_empty_spool_stock.py @@ -0,0 +1,80 @@ +import django.core.validators +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +def mark_existing_bambu_spools(apps, schema_editor): + inventory = apps.get_model("filament", "InventoryItem") + inventory.objects.using(schema_editor.connection.alias).filter( + spool_type="spool", variant__product_type__manufacturer__name__iexact="Bambu Lab" + ).update(bambu_spool=True) + + +class Migration(migrations.Migration): + dependencies = [ + ("filament", "0012_inventoryitem_spool_type"), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.AddField( + model_name="inventoryitem", + name="bambu_spool", + field=models.BooleanField("Bambu-Lab-Spule", default=False), + preserve_default=False, + ), + migrations.RunPython(mark_existing_bambu_spools, migrations.RunPython.noop), + migrations.RemoveConstraint( + model_name="inventoryitem", name="inventoryitem_owner_variant_spool" + ), + migrations.AddConstraint( + model_name="inventoryitem", + constraint=models.UniqueConstraint( + fields=("owner", "variant", "spool_type", "bambu_spool"), + name="inventoryitem_owner_variant_spool_brand", + ), + ), + migrations.AddConstraint( + model_name="inventoryitem", + constraint=models.CheckConstraint( + condition=models.Q(bambu_spool=False) | models.Q(spool_type="spool"), + name="inventoryitem_bambu_spool_requires_spool", + ), + ), + migrations.CreateModel( + name="EmptySpoolStock", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" + ), + ), + ( + "quantity", + models.PositiveIntegerField( + "Bambu-Lab-Leerrollen", + default=0, + validators=[django.core.validators.MaxValueValidator(9999)], + ), + ), + ( + "owner", + models.OneToOneField( + on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL + ), + ), + ], + options={ + "verbose_name": "Leerrollenbestand", + "verbose_name_plural": "Leerrollenbestände", + "constraints": [ + models.CheckConstraint( + condition=models.Q(quantity__gte=0, quantity__lte=9999), + name="emptyspoolstock_quantity_range", + ) + ], + }, + ), + ] diff --git a/filament/models.py b/filament/models.py index 284f056..22d2e18 100644 --- a/filament/models.py +++ b/filament/models.py @@ -140,6 +140,11 @@ class Variant(models.Model): def manufacturer(self): return self.product_type.manufacturer + def is_bambu_spool(self, spool_type): + return ( + spool_type == self.SpoolType.SPOOL and self.manufacturer.name.casefold() == "bambu lab" + ) + def __str__(self): return f"{self.product_type} · {self.color} · {self.get_spool_type_display()}" @@ -181,29 +186,38 @@ class InventoryItem(QuantityPosition): max_length=10, choices=[(Variant.SpoolType.SPOOL, "Mit Spule"), (Variant.SpoolType.REFILL, "Ohne Spule")], ) + bambu_spool = models.BooleanField("Bambu-Lab-Spule") class Meta(QuantityPosition.Meta): constraints = [ models.UniqueConstraint( - fields=["owner", "variant", "spool_type"], name="inventoryitem_owner_variant_spool" + fields=["owner", "variant", "spool_type", "bambu_spool"], + name="inventoryitem_owner_variant_spool_brand", ), models.CheckConstraint( condition=models.Q(spool_type__in=["spool", "refill"]), name="inventoryitem_valid_spool", ), + models.CheckConstraint( + condition=models.Q(bambu_spool=False) | models.Q(spool_type="spool"), + name="inventoryitem_bambu_spool_requires_spool", + ), *QuantityPosition.Meta.constraints[1:], ] def save(self, *args, **kwargs): if not self.spool_type: self.spool_type = self.variant.spool_type + if self.bambu_spool is None: + self.bambu_spool = self.variant.is_bambu_spool(self.spool_type) return super().save(*args, **kwargs) @property def stock_description(self): - return ( + description = ( f"{self.variant.product_type} · {self.variant.color} · {self.get_spool_type_display()}" ) + return f"{description} (Bambu-Lab-Spule)" if self.bambu_spool else description @property def reorder_spool_note(self): @@ -215,6 +229,23 @@ class InventoryItem(QuantityPosition): return f"{self.quantity} × {self.stock_description}" +class EmptySpoolStock(models.Model): + owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + quantity = models.PositiveIntegerField( + "Bambu-Lab-Leerrollen", default=0, validators=[MaxValueValidator(9999)] + ) + + class Meta: + constraints = [ + models.CheckConstraint( + condition=models.Q(quantity__gte=0, quantity__lte=9999), + name="emptyspoolstock_quantity_range", + ) + ] + verbose_name = "Leerrollenbestand" + verbose_name_plural = "Leerrollenbestände" + + class OrderItem(QuantityPosition): class Status(models.TextChoices): OPEN = "open", "Offen" diff --git a/filament/services.py b/filament/services.py index eaf294b..71054ab 100644 --- a/filament/services.py +++ b/filament/services.py @@ -8,30 +8,39 @@ from django.db import transaction from django.shortcuts import get_object_or_404 from django.utils import timezone -from .models import InventoryItem, OrderItem, Variant +from .models import EmptySpoolStock, InventoryItem, OrderItem, Variant @transaction.atomic -def add_quantity(model, owner, variant, quantity, *, spool_type=None): +def add_quantity(model, owner, variant, quantity, *, spool_type=None, bambu_spool=None): """Short IMMEDIATE transaction serializes concurrent SQLite additions.""" if not Variant.objects.filter(pk=variant.pk, is_active=True).exists(): raise ValidationError("Diese Variante ist deaktiviert.") if not 1 <= quantity <= 9999: raise ValidationError("Bitte eine Stückzahl zwischen 1 und 9999 eingeben.") if model is InventoryItem: - return _increment_inventory(owner.pk, variant, spool_type or variant.spool_type, quantity) + return _increment_inventory( + owner.pk, variant, spool_type or variant.spool_type, quantity, bambu_spool=bambu_spool + ) positions = model.objects.all() if model is OrderItem: positions = positions.filter(status__in=OrderItem.PENDING_STATUSES) return _increment_position(positions, quantity, owner_id=owner.pk, variant_id=variant.pk) -def _increment_inventory(owner_id, variant, spool_type, quantity): +def _increment_inventory(owner_id, variant, spool_type, quantity, *, bambu_spool=None): + if bambu_spool is None: + bambu_spool = variant.is_bambu_spool(spool_type) positions = InventoryItem.objects.filter( variant__product_type_id=variant.product_type_id, variant__color_id=variant.color_id ) return _increment_position( - positions, quantity, {"variant_id": variant.pk}, owner_id=owner_id, spool_type=spool_type + positions, + quantity, + {"variant_id": variant.pk}, + owner_id=owner_id, + spool_type=spool_type, + bambu_spool=bambu_spool, ) @@ -50,7 +59,8 @@ def _increment_position(positions, quantity, defaults=None, **lookup): @transaction.atomic def update_order_status(item_id, expected_status, expected_quantity, status): item = get_object_or_404( - OrderItem.objects.select_for_update().select_related("variant"), pk=item_id + OrderItem.objects.select_for_update().select_related("variant__product_type__manufacturer"), + pk=item_id, ) if item.status == OrderItem.Status.HANDED_OVER: raise ValidationError("Diese Position wurde bereits übergeben.") @@ -81,15 +91,70 @@ def update_order_status(item_id, expected_status, expected_quantity, status): @transaction.atomic def consume_spool(owner, item_id, expected_quantity, reorder): + item = _locked_inventory_item(owner, item_id, expected_quantity) + if reorder: + add_quantity(OrderItem, owner, item.variant, 1) + if item.bambu_spool: + _adjust_empty_spools(owner, 1) + _remove_one(item) + return item.bambu_spool + + +@transaction.atomic +def mount_refill(owner, item_id, expected_quantity): + item = _locked_inventory_item(owner, item_id, expected_quantity) + if item.spool_type != Variant.SpoolType.REFILL: + raise ValidationError("Dieses Filament liegt bereits auf einer Spule.") + _adjust_empty_spools(owner, -1) + _increment_inventory(owner.pk, item.variant, Variant.SpoolType.SPOOL, 1, bambu_spool=True) + _remove_one(item) + + +@transaction.atomic +def update_inventory_position(owner, item_id, expected_quantity, quantity, *, bambu_spool=None): + item = _locked_inventory_item(owner, item_id, expected_quantity) + if bambu_spool is None or bambu_spool == item.bambu_spool: + item.quantity = quantity + item.save(update_fields=["quantity"]) + return + _increment_inventory( + item.owner_id, item.variant, item.spool_type, quantity, bambu_spool=bambu_spool + ) + item.delete() + + +@transaction.atomic +def set_empty_spool_quantity(owner, quantity, expected_quantity): + stock, _ = EmptySpoolStock.objects.select_for_update().get_or_create(owner=owner) + if stock.quantity != expected_quantity: + raise ValidationError( + "Der Leerrollenbestand hat sich geändert. Bitte prüfe die aktuelle Stückzahl." + ) + stock.quantity = quantity + stock.save(update_fields=["quantity"]) + + +def _adjust_empty_spools(owner, amount): + stock, _ = EmptySpoolStock.objects.select_for_update().get_or_create(owner=owner) + quantity = stock.quantity + amount + if quantity < 0: + raise ValidationError("Du hast keine Bambu-Lab-Leerrolle im Bestand.") + if quantity > 9999: + raise ValidationError("Der Leerrollenbestand darf höchstens 9999 Stück betragen.") + stock.quantity = quantity + stock.save(update_fields=["quantity"]) + + +def _locked_inventory_item(owner, item_id, expected_quantity): item = get_object_or_404( - InventoryItem.objects.select_for_update().select_related("variant"), - pk=item_id, - owner=owner, + InventoryItem.objects.select_for_update().select_related("variant"), pk=item_id, owner=owner ) if item.quantity != expected_quantity: raise ValidationError("Der Bestand hat sich geändert. Bitte prüfe die aktuelle Stückzahl.") - if reorder: - add_quantity(OrderItem, owner, item.variant, 1) + return item + + +def _remove_one(item): if item.quantity == 1: item.delete() else: diff --git a/filament/static/filament/app.css b/filament/static/filament/app.css index 13ee378..f926178 100644 --- a/filament/static/filament/app.css +++ b/filament/static/filament/app.css @@ -374,6 +374,39 @@ p { .stock-search a { font-size: 13px; } +.inventory-tabs { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-bottom: 20px; +} +.inventory-tabs > a { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 40px; + padding: 7px 14px; + border: 1px solid var(--line); + border-radius: 10px; + background: var(--surface); + color: var(--ink); + font-size: 13px; +} +.inventory-tabs > a[aria-current="page"] { + background: var(--light); + color: var(--green); +} +.stock-spool-brand { + display: block; + margin-top: 4px; + color: var(--muted); +} +.empty-spool-form { + margin-top: 20px; +} +.empty-spool-form .field { + max-width: 14rem; +} .table-wrap { /* Keep absolute screen-reader labels inside the horizontally scrolling table. */ position: relative; diff --git a/filament/static/filament/catalog.js b/filament/static/filament/catalog.js index 2a47356..37ab5f3 100644 --- a/filament/static/filament/catalog.js +++ b/filament/static/filament/catalog.js @@ -11,6 +11,7 @@ if (consumeDialog?.showModal) { const reorderButton = consumeForm.querySelector('[value="reorder"]'); const inactiveNote = consumeForm.querySelector("[data-inactive-note]"); const reorderNote = consumeForm.querySelector("[data-reorder-note]"); + const returnSpoolNote = consumeDialog.querySelector("[data-return-spool-note]"); document.querySelectorAll("[data-consume]").forEach((link) => { link.addEventListener("click", (event) => { if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; @@ -23,6 +24,7 @@ if (consumeDialog?.showModal) { inactiveNote.hidden = !reorderButton.disabled; reorderNote.textContent = link.dataset.reorderNote; reorderNote.hidden = !link.dataset.reorderNote; + returnSpoolNote.hidden = !link.hasAttribute("data-return-spool"); consumeDialog.showModal(); }); }); @@ -151,7 +153,7 @@ if (form) { event.preventDefault(); form.requestSubmit(form.querySelector("[data-article-lookup]")); }); - const selects = [...form.querySelectorAll(".form-grid select")]; + const selects = [...form.querySelectorAll(".form-grid select:not([data-spool-brand])")]; selects.forEach((select, index) => { select.addEventListener("change", () => { selects.slice(index + 1).forEach((next) => { diff --git a/filament/tests/test_empty_spools.py b/filament/tests/test_empty_spools.py new file mode 100644 index 0000000..36ef3cc --- /dev/null +++ b/filament/tests/test_empty_spools.py @@ -0,0 +1,128 @@ +from django.test import Client +from django.urls import reverse + +from filament.models import ( + EmptySpoolStock, + InventoryItem, + Manufacturer, + OrderItem, + ProductType, + Variant, +) + +from .base import CatalogTestCase + + +class EmptySpoolTests(CatalogTestCase): + def setUp(self): + self.client.force_login(self.alice) + self.tab = reverse("empty_spools") + self.stock = EmptySpoolStock.objects.create(owner=self.alice, quantity=1) + maker = Manufacturer.objects.create(name="SUNLU") + product = ProductType.objects.create(manufacturer=maker, name="PLA Matte") + self.sunlu_refill = Variant.objects.create( + product_type=product, color=self.red, spool_type="refill" + ) + self.refills = InventoryItem.objects.create( + owner=self.alice, variant=self.sunlu_refill, quantity=2 + ) + self.mount_url = reverse("inventory_mount", args=[self.refills.pk]) + + def test_mount_spends_one_empty_spool_and_consumption_returns_it_with_either_action(self): + self.assertContains(self.client.get(reverse("inventory")), "Auf Leerrolle aufziehen") + self.assertContains(self.client.get(self.mount_url), "Eine Rolle aufziehen") + for action, remaining in (("consume", 2), ("reorder", 1)): + with self.subTest(action=action): + self.assertRedirects( + self.client.post(self.mount_url, {"quantity": remaining}), reverse("inventory") + ) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, 0) + mounted = InventoryItem.objects.get( + owner=self.alice, variant=self.sunlu_refill, spool_type="spool" + ) + self.assertTrue(mounted.bambu_spool) + self.assertEqual(mounted.quantity, 1) + consume = reverse("inventory_consume", args=[mounted.pk]) + self.assertContains( + self.client.get(consume), "Eine Bambu-Lab-Leerrolle wird zurückgebucht." + ) + self.assertRedirects( + self.client.post(consume, {"quantity": 1, "action": action}), + reverse("inventory"), + ) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, 1) + self.assertFalse(InventoryItem.objects.filter(pk=mounted.pk).exists()) + self.assertEqual( + OrderItem.objects.filter(variant=self.sunlu_refill).count(), + int(action == "reorder"), + ) + self.assertFalse(InventoryItem.objects.filter(pk=self.refills.pk).exists()) + + def test_mount_and_correction_validate_current_quantity_and_stay_private(self): + self.assertRedirects( + self.client.post(self.tab, {"quantity": 0, "expected_quantity": 1}), self.tab + ) + self.assertContains(self.client.get(self.mount_url), "Leerrollen erfassen") + response = self.client.post(self.mount_url, {"quantity": 2}) + self.assertContains(response, "Du hast keine Bambu-Lab-Leerrolle im Bestand.") + self.refills.refresh_from_db() + self.assertEqual(self.refills.quantity, 2) + self.assertRedirects( + self.client.post(self.tab, {"quantity": 10, "expected_quantity": 1}), self.tab + ) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, 0) + + csrf = Client(enforce_csrf_checks=True) + csrf.force_login(self.alice) + self.assertEqual( + csrf.post(self.tab, {"quantity": 1, "expected_quantity": 0}).status_code, 403 + ) + self.assertEqual(csrf.post(self.mount_url, {"quantity": 2}).status_code, 403) + self.client.force_login(self.bob) + self.assertEqual(self.client.post(self.mount_url, {"quantity": 2}).status_code, 404) + self.assertRedirects( + self.client.post( + self.tab, {"quantity": 3, "expected_quantity": 0, "owner": self.alice.pk} + ), + self.tab, + ) + self.assertEqual(EmptySpoolStock.objects.get(owner=self.bob).quantity, 3) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, 0) + + def test_spool_manufacturer_can_be_corrected_and_only_bambu_spools_are_credited(self): + add_url = reverse("inventory_add") + self.assertRedirects( + self.client.post(add_url, self.selection(self.spool) | {"spool_brand": "other"}), + reverse("inventory"), + ) + other = InventoryItem.objects.get(variant=self.spool) + self.assertFalse(other.bambu_spool) + old_amount = self.stock.quantity + consume = reverse("inventory_consume", args=[other.pk]) + self.assertRedirects( + self.client.post(consume, {"quantity": 1, "action": "consume"}), reverse("inventory") + ) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, old_amount) + + original = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=1) + self.assertTrue(original.bambu_spool) + edit = reverse("inventory_edit", args=[original.pk]) + self.assertRedirects( + self.client.post(edit, {"quantity": 1, "expected_quantity": 1, "bambu_spool": "other"}), + reverse("inventory"), + ) + self.assertFalse(InventoryItem.objects.get(variant=self.spool).bambu_spool) + + def test_failed_reorder_rolls_back_the_empty_spool_credit(self): + mounted = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=1) + OrderItem.objects.create(owner=self.alice, variant=self.spool, quantity=9999) + url = reverse("inventory_consume", args=[mounted.pk]) + self.assertRedirects(self.client.post(url, {"quantity": 1, "action": "reorder"}), url) + self.stock.refresh_from_db() + self.assertEqual(self.stock.quantity, 1) + self.assertTrue(InventoryItem.objects.filter(pk=mounted.pk).exists()) diff --git a/filament/views.py b/filament/views.py index 84f971f..7d53e30 100644 --- a/filament/views.py +++ b/filament/views.py @@ -15,7 +15,10 @@ from django.views.decorators.http import require_http_methods from .forms import ( ArticleLookupForm, ConsumeSpoolForm, + EmptySpoolQuantityForm, FeedbackForm, + InventoryQuantityForm, + MountRefillForm, OrderStatusForm, PrinterForm, ProfileForm, @@ -24,8 +27,15 @@ from .forms import ( VariantSelectionForm, selection_id, ) -from .models import InventoryItem, OrderItem, Printer, SharingPreferences, Variant -from .services import add_quantity, consume_spool, update_order_status +from .models import EmptySpoolStock, InventoryItem, OrderItem, Printer, SharingPreferences, Variant +from .services import ( + add_quantity, + consume_spool, + mount_refill, + set_empty_spool_quantity, + update_inventory_position, + update_order_status, +) STOCK_COLUMNS = ( ("manufacturer", "Hersteller", ""), @@ -144,23 +154,41 @@ def _edit_position(request, pk, positions, back): pk=pk, owner=request.user, ) - form = QuantityForm( - request.POST if request.method == "POST" else None, initial={"quantity": item.quantity} + inventory_item = isinstance(item, InventoryItem) + form_class = InventoryQuantityForm if inventory_item else QuantityForm + form = form_class( + request.POST if request.method == "POST" else None, + initial={"quantity": item.quantity, "expected_quantity": item.quantity}, + **({"item": item} if inventory_item else {}), ) if request.method == "POST" and form.is_valid(): - item.quantity = form.cleaned_data["quantity"] - item.save(update_fields=["quantity"]) - messages.success(request, "Stückzahl geändert.") - return redirect(back) + quantity = form.cleaned_data["quantity"] + try: + if inventory_item: + update_inventory_position( + request.user, + item.pk, + form.cleaned_data["expected_quantity"] or item.quantity, + quantity, + bambu_spool=form.cleaned_data.get("bambu_spool"), + ) + else: + item.quantity = quantity + item.save(update_fields=["quantity"]) + except ValidationError as error: + form.add_error(None, error) + else: + messages.success( + request, "Bestand geändert." if inventory_item else "Stückzahl geändert." + ) + return redirect(back) return render( request, "filament/form.html", { "form": form, - "title": "Stückzahl ändern", - "description": item.stock_description - if isinstance(item, InventoryItem) - else str(item.variant), + "title": "Bestand bearbeiten" if inventory_item else "Stückzahl ändern", + "description": item.stock_description if inventory_item else str(item.variant), "back_name": back, }, ) @@ -202,7 +230,7 @@ def inventory_consume(request, pk): if form.is_valid(): reorder = form.cleaned_data["action"] == "reorder" try: - consume_spool(request.user, pk, form.cleaned_data["quantity"], reorder) + credited = consume_spool(request.user, pk, form.cleaned_data["quantity"], reorder) except ValidationError as error: messages.error(request, error.messages[0]) return redirect("inventory_consume", pk=pk) @@ -212,12 +240,65 @@ def inventory_consume(request, pk): if reorder else "Eine Spule aus dem Bestand ausgebucht.", ) + if credited: + messages.success(request, "Eine Bambu-Lab-Leerrolle wurde zurückgebucht.") return redirect("inventory") messages.error(request, "Bitte wähle aus, ob du eine neue Spule bestellen möchtest.") return redirect("inventory_consume", pk=pk) return render(request, "filament/consume_spool.html", {"item": item}) +def _empty_spool_quantity(user): + return ( + EmptySpoolStock.objects.filter(owner=user).values_list("quantity", flat=True).first() or 0 + ) + + +@login_required +@require_http_methods(["GET", "POST"]) +def empty_spools(request): + quantity = _empty_spool_quantity(request.user) + form = EmptySpoolQuantityForm( + request.POST if request.method == "POST" else None, + initial={"quantity": quantity, "expected_quantity": quantity}, + ) + if request.method == "POST" and form.is_valid(): + try: + set_empty_spool_quantity(request.user, **form.cleaned_data) + except ValidationError as error: + messages.error(request, error.messages[0]) + else: + messages.success(request, "Leerrollenbestand gespeichert.") + return redirect("empty_spools") + return render(request, "filament/empty_spools.html", {"form": form, "quantity": quantity}) + + +@login_required +@require_http_methods(["GET", "POST"]) +def inventory_mount(request, pk): + item = get_object_or_404( + _stock_items(), pk=pk, owner=request.user, spool_type=Variant.SpoolType.REFILL + ) + form = MountRefillForm( + request.POST if request.method == "POST" else None, initial={"quantity": item.quantity} + ) + if request.method == "POST" and form.is_valid(): + try: + mount_refill(request.user, pk, form.cleaned_data["quantity"]) + except ValidationError as error: + form.add_error(None, error) + else: + messages.success( + request, "Filament aufgezogen. Eine Bambu-Lab-Leerrolle wurde abgebucht." + ) + return redirect("inventory") + return render( + request, + "filament/mount_refill.html", + {"form": form, "item": item, "empty_count": _empty_spool_quantity(request.user)}, + ) + + @login_required def inventory(request): items = list(_stock_items().filter(owner=request.user)) @@ -268,6 +349,7 @@ def inventory(request): "sort": sort, "sort_direction": "desc" if descending else "asc", "total": total, + "empty_count": _empty_spool_quantity(request.user), "sharing": getattr(request.user, "sharing", None), }, ) @@ -400,6 +482,7 @@ def _add_position(request, model, back, title, destination): form.variant, form.cleaned_data["quantity"], spool_type=form.cleaned_data["spool_type"] if for_inventory else None, + bambu_spool=form.bambu_spool, ) except ValidationError as error: form.add_error(None, error) diff --git a/templates/filament/consume_options.html b/templates/filament/consume_options.html index 7792b7f..029fd12 100644 --- a/templates/filament/consume_options.html +++ b/templates/filament/consume_options.html @@ -1,4 +1,5 @@

Aktueller Bestand: {{ item.quantity }}. Eine Rolle wird abgezogen.

+

Eine Bambu-Lab-Leerrolle wird zurückgebucht.

{% csrf_token %} diff --git a/templates/filament/empty_spools.html b/templates/filament/empty_spools.html new file mode 100644 index 0000000..d3202f3 --- /dev/null +++ b/templates/filament/empty_spools.html @@ -0,0 +1,19 @@ +{% extends "base.html" %} +{% block title %}Leerrollen · Fil-A-Management{% endblock %} +{% block content %} +
+

Mein Bestand

+
+{% include "filament/inventory_tabs.html" with active="spools" empty_count=quantity only %} +
+

Bambu-Lab-Leerrollen

+

Trag deine vorhandenen Leerrollen ein. Beim Aufziehen und Verbrauchen passt sich die Stückzahl automatisch an.

+ + {% csrf_token %}{{ form.non_field_errors }}{{ form.expected_quantity }}{{ form.expected_quantity.errors }} +
+ {{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }} +
+ + +
+{% endblock %} diff --git a/templates/filament/form.html b/templates/filament/form.html index e1cde4d..524b81c 100644 --- a/templates/filament/form.html +++ b/templates/filament/form.html @@ -12,7 +12,8 @@
{% csrf_token %}{{ form.non_field_errors }} - {% for field in form %} + {% for field in form.hidden_fields %}{{ field }}{{ field.errors }}{% endfor %} + {% for field in form.visible_fields %}
{{ field.label_tag }}{{ field }}{{ field.errors }} {% if field.help_text %}
{{ field.help_text }}
{% endif %} diff --git a/templates/filament/inventory.html b/templates/filament/inventory.html index e894dfe..a12a029 100644 --- a/templates/filament/inventory.html +++ b/templates/filament/inventory.html @@ -1,5 +1,6 @@ {% extends "base.html" %}{% block title %}Mein Bestand · Fil-A-Management{% endblock %} -{% block content %}

DEINE WERKSTATT

Mein Filamentbestand

Alles, was für dein nächstes Projekt bereitliegt.

+ Filament hinzufügen
+{% block content %} + {% include "filament/inventory_tabs.html" with active="filament" empty_count=empty_count only %}
Rollen im Bestand{{ total }}dein persönlicher Vorrat diff --git a/templates/filament/inventory_tabs.html b/templates/filament/inventory_tabs.html new file mode 100644 index 0000000..85b37c7 --- /dev/null +++ b/templates/filament/inventory_tabs.html @@ -0,0 +1,4 @@ + diff --git a/templates/filament/mount_refill.html b/templates/filament/mount_refill.html new file mode 100644 index 0000000..6b698d4 --- /dev/null +++ b/templates/filament/mount_refill.html @@ -0,0 +1,21 @@ +{% extends "base.html" %} +{% block title %}Auf Leerrolle aufziehen · Fil-A-Management{% endblock %} +{% block content %} +← Zurück zum Bestand +
+

Auf Leerrolle aufziehen

{{ item.stock_description }}

+
+
+

Eine Bambu-Lab-Leerrolle wird abgebucht. Das Filament erscheint anschließend im Bestand Mit Spule.

+

Verfügbare Leerrollen {{ empty_count }}

+ + {% csrf_token %}{{ form.quantity }}{{ form.quantity.errors }}{{ form.non_field_errors }} + {% if empty_count %} + + {% else %} + Leerrollen erfassen + {% endif %} + Abbrechen + +
+{% endblock %} diff --git a/templates/filament/stock_table.html b/templates/filament/stock_table.html index 8d5e1dd..caa9412 100644 --- a/templates/filament/stock_table.html +++ b/templates/filament/stock_table.html @@ -24,14 +24,15 @@ {{ item.variant.product_type.name }}
{% include "filament/variant_thumbnail.html" with variant=item.variant only %}{{ item.variant.color }}
{% endif %} - {{ item.get_spool_type_display }}{% if not item.variant.is_active %}Deaktiviert{% endif %} + {{ item.get_spool_type_display }}{% if editable and item.bambu_spool %}Bambu Lab{% endif %}{% if not item.variant.is_active %}Deaktiviert{% endif %} {{ item.variant.manufacturer_color_code|default:"–" }} {{ item.quantity }} {% if editable %} Spule verbraucht - Stückzahl ändern + data-consume data-variant="{{ item.stock_description }}" data-quantity="{{ item.quantity }}" data-reorder-note="{{ item.reorder_spool_note }}"{% if item.bambu_spool %} data-return-spool{% endif %}{% if not item.variant.is_active %} data-inactive{% endif %}>Spule verbraucht + {% if item.spool_type == "refill" %}Auf Leerrolle aufziehen{% endif %} + Bearbeiten {% endif %}