Track reusable Bambu Lab spools in personal inventory

This commit is contained in:
Mikei386 committed 2026-11-14 17:57:24 +01:00
1 parent 0287643b97
commit 47efe317bf
17 files changed
+560 -32

No files matched your search

+4
View File
@@ -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
+2
View File
@@ -36,10 +36,12 @@ urlpatterns = [
path("drucker/<int:pk>/bearbeiten/", views.printer_edit, name="printer_edit"),
path("drucker/<int:pk>/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/<int:pk>/bearbeiten/", views.inventory_edit, name="inventory_edit"),
path("bestand/<int:pk>/verbrauchen/", views.inventory_consume, name="inventory_consume"),
path("bestand/<int:pk>/aufziehen/", views.inventory_mount, name="inventory_mount"),
path("bestand/<int:pk>/loeschen/", views.inventory_delete, name="inventory_delete"),
path("bestellung/", views.orders, name="orders"),
path("bestellung/historie/", views.order_history, name="order_history"),
+52
View File
@@ -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
@@ -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",
)
],
},
),
]
+33 -2
View File
@@ -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"
+76 -11
View File
@@ -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:
+33
View File
@@ -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;
+3 -1
View File
@@ -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) => {
+128
View File
@@ -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())
+96 -13
View File
@@ -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)
+1
View File
@@ -1,4 +1,5 @@
<p>Aktueller Bestand: <strong data-consume-count>{{ item.quantity }}</strong>. Eine Rolle wird abgezogen.</p>
<p data-return-spool-note{% if not item.bambu_spool %} hidden{% endif %}>Eine Bambu-Lab-Leerrolle wird zurückgebucht.</p>
<form method="post" data-consume-form>
{% csrf_token %}
<input type="hidden" name="quantity" value="{{ item.quantity|default:'' }}">
+19
View File
@@ -0,0 +1,19 @@
{% extends "base.html" %}
{% block title %}Leerrollen · Fil-A-Management{% endblock %}
{% block content %}
<div class="page-heading">
<div><h1>Mein Bestand</h1></div>
</div>
{% include "filament/inventory_tabs.html" with active="spools" empty_count=quantity only %}
<section class="panel form-panel">
<h2>Bambu-Lab-Leerrollen</h2>
<p class="muted">Trag deine vorhandenen Leerrollen ein. Beim Aufziehen und Verbrauchen passt sich die Stückzahl automatisch an.</p>
<form method="post" class="empty-spool-form">
{% csrf_token %}{{ form.non_field_errors }}{{ form.expected_quantity }}{{ form.expected_quantity.errors }}
<div class="field">
{{ form.quantity.label_tag }}{{ form.quantity }}{{ form.quantity.errors }}
</div>
<button class="button" type="submit">Bestand speichern</button>
</form>
</section>
{% endblock %}
+2 -1
View File
@@ -12,7 +12,8 @@
<section class="panel form-panel">
<form method="post">
{% 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 %}
<div class="field">
{{ field.label_tag }}{{ field }}{{ field.errors }}
{% if field.help_text %}<div class="helptext" id="{{ field.auto_id }}_helptext">{{ field.help_text }}</div>{% endif %}
+2 -1
View File
@@ -1,5 +1,6 @@
{% extends "base.html" %}{% block title %}Mein Bestand · Fil-A-Management{% endblock %}
{% block content %}<div class="page-heading"><div><p class="eyebrow">DEINE WERKSTATT</p><h1>Mein Filamentbestand</h1><p class="muted">Alles, was für dein nächstes Projekt bereitliegt.</p></div><a class="button" href="{% url 'inventory_add' %}">+ Filament hinzufügen</a></div>
{% block content %}<div class="page-heading"><div><h1>Mein Bestand</h1></div><a class="button" href="{% url 'inventory_add' %}">+ Filament hinzufügen</a></div>
{% include "filament/inventory_tabs.html" with active="filament" empty_count=empty_count only %}
<div class="stats">
<section class="stat">
<span>Rollen im Bestand</span><strong>{{ total }}</strong><small>dein persönlicher Vorrat</small>
+4
View File
@@ -0,0 +1,4 @@
<nav class="inventory-tabs" aria-label="Bestandsbereiche">
<a href="{% url 'inventory' %}"{% if active == "filament" %} aria-current="page"{% endif %}>Filamente</a>
<a href="{% url 'empty_spools' %}"{% if active == "spools" %} aria-current="page"{% endif %}>Leerrollen <span class="badge">{{ empty_count }}</span></a>
</nav>
+21
View File
@@ -0,0 +1,21 @@
{% extends "base.html" %}
{% block title %}Auf Leerrolle aufziehen · Fil-A-Management{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'inventory' %}">← Zurück zum Bestand</a>
<div class="page-heading">
<div><h1>Auf Leerrolle aufziehen</h1><p class="muted">{{ item.stock_description }}</p></div>
</div>
<section class="panel form-panel">
<p>Eine Bambu-Lab-Leerrolle wird abgebucht. Das Filament erscheint anschließend im Bestand <strong>Mit Spule</strong>.</p>
<p>Verfügbare Leerrollen <strong>{{ empty_count }}</strong></p>
<form method="post" class="form-actions">
{% csrf_token %}{{ form.quantity }}{{ form.quantity.errors }}{{ form.non_field_errors }}
{% if empty_count %}
<button class="button" type="submit">Eine Rolle aufziehen</button>
{% else %}
<a class="button" href="{% url 'empty_spools' %}">Leerrollen erfassen</a>
{% endif %}
<a class="button secondary" href="{% url 'inventory' %}">Abbrechen</a>
</form>
</section>
{% endblock %}
+4 -3
View File
@@ -24,14 +24,15 @@
<td rowspan="{{ group|length }}">{{ item.variant.product_type.name }}</td>
<th class="stock-color" scope="rowgroup" rowspan="{{ group|length }}"><div class="variant-preview">{% include "filament/variant_thumbnail.html" with variant=item.variant only %}<strong>{{ item.variant.color }}</strong></div></th>
{% endif %}
<td><span class="badge">{{ item.get_spool_type_display }}</span>{% if not item.variant.is_active %}<small class="warning">Deaktiviert</small>{% endif %}</td>
<td><span class="badge">{{ item.get_spool_type_display }}</span>{% if editable and item.bambu_spool %}<small class="stock-spool-brand">Bambu Lab</small>{% endif %}{% if not item.variant.is_active %}<small class="warning">Deaktiviert</small>{% endif %}</td>
<td class="article-number">{{ item.variant.manufacturer_color_code|default:"–" }}</td>
<td class="quantity">{{ item.quantity }}</td>
{% if editable %}
<td class="actions">
<a class="button secondary consume-button" href="{% url 'inventory_consume' item.pk %}"
data-consume data-variant="{{ item.stock_description }}" data-quantity="{{ item.quantity }}" data-reorder-note="{{ item.reorder_spool_note }}"{% if not item.variant.is_active %} data-inactive{% endif %}>Spule verbraucht</a>
<a href="{% url 'inventory_edit' item.pk %}">Stückzahl ändern</a>
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</a>
{% if item.spool_type == "refill" %}<a href="{% url 'inventory_mount' item.pk %}">Auf Leerrolle aufziehen</a>{% endif %}
<a href="{% url 'inventory_edit' item.pk %}">Bearbeiten</a>
</td>
{% endif %}
</tr>