Track physical spool state independently in inventory

This commit is contained in:
Mikei386 committed 2026-11-14 16:46:35 +01:00
1 parent f354eee799
commit 351b09d2f8
14 files changed
+231 -36

No files matched your search

+5 -3
View File
@@ -14,7 +14,9 @@ Keine SPA, keine externen Schriften/Skripte, kein externer Datenbankserver.
für angemeldete Mitglieder freigeben. Fremde Bearbeitungs-URLs liefern **404**.
- Kaskadierende Dropdowns: Hersteller → Material → Unterart → Farbe → Spulenausführung.
Ohne JavaScript mit **„Auswahl aktualisieren“** bedienbar.
- Eine Position je Benutzer/Variante; erneutes Hinzufügen addiert die Menge.
- Im Bestand zählt je Farbe und Produktart der tatsächliche Spulenzustand. Erneutes
Hinzufügen zur gleichen Ausführung addiert die Menge. In der Sammelbestellung
gelten die angebotenen Spulenausführungen des Katalogs.
- Sammelbestellung mit separater Tabelle je Person und sichtbarem Lieferstatus.
Angemeldete Mitglieder pflegen den Status aller Wünsche und bearbeiten ihre eigenen offenen Wünsche.
Bei Übergabe wird die Menge in den Bestand der Person gebucht. Mit Spule und Refill
@@ -25,8 +27,8 @@ Keine SPA, keine externen Schriften/Skripte, kein externer Datenbankserver.
- Einmalig ladbare Startkataloge für Bambu Lab, SUNLU, eSUN, JAYO und Anycubic sowie konsistentes
SQLite-Online-Backup.
Unter „Spule verbraucht“ lässt sich eine Rolle ausbuchen und dieselbe Variante optional in
die Sammelbestellung übernehmen. Die Sammelbestellung ist eine Planungsliste.
Unter „Spule verbraucht“ lässt sich eine Rolle ausbuchen und optional ihre Katalogvariante
in die Sammelbestellung übernehmen. Die Sammelbestellung ist eine Planungsliste.
Dieses Projekt ist unabhängig vom älteren PHP-Projekt `michael/filament`.
## Betrieb: fertiges Alpine-Python-Image, kein Build
+7 -5
View File
@@ -14,8 +14,10 @@ User 1 ── n Printer
- Eine Variante identifiziert Hersteller (über Produktart), Produktart, Farbe und Spulenausführung.
Unique-Constraint auf `(product_type, color, spool_type)` verhindert Dubletten.
- Farbcode, Nettogewicht und Durchmesser sind optionale Varianteneigenschaften.
- Bestand und Bestellwünsche sind getrennte Tabellen. Pro `(owner, variant)` existiert höchstens
eine Position; Datenbank-Constraints begrenzen Mengen auf 1–9999.
- Bestand und Bestellwünsche sind getrennte Tabellen. Der Bestand speichert den tatsächlichen
Spulenzustand separat neben der Katalogvariante. Datenbank-Constraints begrenzen Mengen auf
1–9999 und verhindern doppelte Bestandspositionen mit derselben Katalogreferenz und demselben
Spulenzustand.
- Geschützte Katalog-Fremdschlüssel und das Deaktivieren von Varianten erhalten Katalogreferenzen.
- Beim bestätigten Löschen eines Kontos entfernt Django kaskadierend dessen Bestand, Bestellungen
samt Historie, Drucker, Freigaben und Feedback.
@@ -75,9 +77,9 @@ Der Snapshot-Befehl verwendet die SQLite-Backup-API statt einer Live-Dateikopie.
## Eine Rolle ausbuchen
Der Bestand gruppiert Positionen nach Produktart und Farbe. Mit Spule und Refill haben je eine
eigene Stückzahl und Aktion. Das POST-Formular für „Spule verbraucht“ bietet die Ausbuchung
mit oder ohne Aufnahme derselben Variante in die Sammelbestellung.
Der Bestand gruppiert Positionen nach Produktart und Farbe. Rollen mit und ohne Spule haben
je eine eigene Stückzahl und Aktion. Bei einer Nachbestellung übernimmt „Spule verbraucht“
die hinterlegte Katalogvariante mit ihrer angebotenen Spulenausführung.
Die Transaktion lädt die eigene Position erneut und prüft die im Dialog angezeigte Stückzahl.
Dann verringert sie die Menge um eins, löscht die Position bei null und erhöht auf Wunsch die
+22 -11
View File
@@ -4,6 +4,7 @@ from django.contrib.auth import get_user_model
from .models import (
Color,
Feedback,
InventoryItem,
Manufacturer,
OrderItem,
Printer,
@@ -106,8 +107,9 @@ class VariantSelectionForm(forms.Form):
spool_type = forms.ChoiceField(label="Spulenausführung", choices=[])
quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999, initial=1)
def __init__(self, *args, selection=None, **kwargs):
def __init__(self, *args, selection=None, for_inventory=False, **kwargs):
super().__init__(*args, **kwargs)
self.for_inventory = for_inventory
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})
@@ -142,17 +144,24 @@ class VariantSelectionForm(forms.Form):
.values_list("color_id", "swatch")
)
spools = set(narrowed.filter(color_id=color).values_list("spool_type", flat=True))
spool_choices = [
(key, "Filament auf Spule" if key == Variant.SpoolType.SPOOL else label)
for key, label in Variant.SpoolType.choices
if key in spools
]
choices = (
InventoryItem._meta.get_field("spool_type").choices
if for_inventory
else Variant.SpoolType.choices
)
spool_choices = []
if spools:
spool_choices = [
(key, "Filament auf Spule" if key == Variant.SpoolType.SPOOL else label)
for key, label in choices
if for_inventory or key in spools
]
spool_field = self.fields["spool_type"]
spool_field.choices = spool_choices
if not spool_choices:
spool_field.widget.attrs["disabled"] = True
elif not self.is_bound and values.get("spool_type") not in spools:
self.initial["spool_type"] = spool_choices[0][0]
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)
def clean(self):
cleaned = super().clean()
@@ -160,13 +169,15 @@ class VariantSelectionForm(forms.Form):
cleaned.get(k)
for k in ("manufacturer", "material", "product_type", "color", "spool_type")
):
self.variant = Variant.objects.filter(
variants = Variant.objects.filter(
is_active=True,
product_type=cleaned["product_type"],
product_type__manufacturer=cleaned["manufacturer"],
color=cleaned["color"],
spool_type=cleaned["spool_type"],
).first()
)
self.variant = variants.filter(spool_type=cleaned["spool_type"]).first()
if self.variant is None and self.for_inventory:
self.variant = variants.first()
if self.variant is None:
raise forms.ValidationError(
"Diese Variante ist nicht mehr verfügbar. Bitte neu auswählen."
@@ -0,0 +1,50 @@
from django.db import migrations, models
def copy_spool_types(apps, schema_editor):
db = schema_editor.connection.alias
inventory = apps.get_model("filament", "InventoryItem").objects.using(db)
variants = apps.get_model("filament", "Variant").objects.using(db)
inventory.update(
spool_type=models.Subquery(
variants.filter(pk=models.OuterRef("variant_id")).values("spool_type")
)
)
class Migration(migrations.Migration):
dependencies = [
("filament", "0011_esun_variant_images"),
]
operations = [
migrations.AddField(
model_name="inventoryitem",
name="spool_type",
field=models.CharField(max_length=10, null=True),
),
migrations.RunPython(copy_spool_types),
migrations.AlterField(
model_name="inventoryitem",
name="spool_type",
field=models.CharField(
"Spulenzustand",
choices=[("spool", "Mit Spule"), ("refill", "Ohne Spule")],
max_length=10,
),
),
migrations.RemoveConstraint(model_name="inventoryitem", name="inventoryitem_owner_variant"),
migrations.AddConstraint(
model_name="inventoryitem",
constraint=models.UniqueConstraint(
fields=("owner", "variant", "spool_type"), name="inventoryitem_owner_variant_spool"
),
),
migrations.AddConstraint(
model_name="inventoryitem",
constraint=models.CheckConstraint(
condition=models.Q(spool_type__in=["spool", "refill"]),
name="inventoryitem_valid_spool",
),
),
]
+39 -1
View File
@@ -174,7 +174,45 @@ class QuantityPosition(models.Model):
class InventoryItem(QuantityPosition):
"""Aggregate per owner and exact catalog variant."""
"""Physical stock with a catalog reference for reordering."""
spool_type = models.CharField(
"Spulenzustand",
max_length=10,
choices=[(Variant.SpoolType.SPOOL, "Mit Spule"), (Variant.SpoolType.REFILL, "Ohne Spule")],
)
class Meta(QuantityPosition.Meta):
constraints = [
models.UniqueConstraint(
fields=["owner", "variant", "spool_type"], name="inventoryitem_owner_variant_spool"
),
models.CheckConstraint(
condition=models.Q(spool_type__in=["spool", "refill"]),
name="inventoryitem_valid_spool",
),
*QuantityPosition.Meta.constraints[1:],
]
def save(self, *args, **kwargs):
if not self.spool_type:
self.spool_type = self.variant.spool_type
return super().save(*args, **kwargs)
@property
def stock_description(self):
return (
f"{self.variant.product_type} · {self.variant.color} · {self.get_spool_type_display()}"
)
@property
def reorder_spool_note(self):
if self.variant.is_active and self.spool_type != self.variant.spool_type:
return f"Nachbestellung als {self.variant.get_spool_type_display()}."
return ""
def __str__(self):
return f"{self.quantity} × {self.stock_description}"
class OrderItem(QuantityPosition):
+19 -8
View File
@@ -12,21 +12,32 @@ from .models import InventoryItem, OrderItem, Variant
@transaction.atomic
def add_quantity(model, owner, variant, quantity):
def add_quantity(model, owner, variant, quantity, *, spool_type=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)
positions = model.objects.all()
if model is OrderItem:
positions = positions.filter(status__in=OrderItem.PENDING_STATUSES)
return _increment_position(positions, owner.pk, variant.pk, quantity)
return _increment_position(positions, quantity, owner_id=owner.pk, variant_id=variant.pk)
def _increment_position(positions, owner_id, variant_id, quantity):
def _increment_inventory(owner_id, variant, spool_type, quantity):
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
)
def _increment_position(positions, quantity, defaults=None, **lookup):
position, created = positions.select_for_update().get_or_create(
owner_id=owner_id, variant_id=variant_id, defaults={"quantity": quantity}
defaults={"quantity": quantity} | (defaults or {}), **lookup
)
if not created:
if position.quantity + quantity > 9999:
@@ -38,7 +49,9 @@ def _increment_position(positions, owner_id, variant_id, quantity):
@transaction.atomic
def update_order_status(item_id, expected_status, expected_quantity, status):
item = get_object_or_404(OrderItem.objects.select_for_update(), pk=item_id)
item = get_object_or_404(
OrderItem.objects.select_for_update().select_related("variant"), pk=item_id
)
if item.status == OrderItem.Status.HANDED_OVER:
raise ValidationError("Diese Position wurde bereits übergeben.")
if item.status != expected_status or item.quantity != expected_quantity:
@@ -55,9 +68,7 @@ def update_order_status(item_id, expected_status, expected_quantity, status):
raise ValidationError("Für diese Variante gibt es bereits einen offenen Wunsch.")
if status == OrderItem.Status.HANDED_OVER:
# A delivered item belongs in stock even if the catalog variant was since deactivated.
_increment_position(
InventoryItem.objects.all(), item.owner_id, item.variant_id, item.quantity
)
_increment_inventory(item.owner_id, item.variant, item.variant.spool_type, item.quantity)
item.handed_over_at = timezone.now()
elif status == OrderItem.Status.ORDERED and item.ordered_at is None:
item.ordered_at = timezone.now()
+3
View File
@@ -10,6 +10,7 @@ if (consumeDialog?.showModal) {
const consumeForm = consumeDialog.querySelector("[data-consume-form]");
const reorderButton = consumeForm.querySelector('[value="reorder"]');
const inactiveNote = consumeForm.querySelector("[data-inactive-note]");
const reorderNote = consumeForm.querySelector("[data-reorder-note]");
document.querySelectorAll("[data-consume]").forEach((link) => {
link.addEventListener("click", (event) => {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
@@ -20,6 +21,8 @@ if (consumeDialog?.showModal) {
consumeDialog.querySelector("[data-consume-variant]").textContent = link.dataset.variant;
reorderButton.disabled = link.hasAttribute("data-inactive");
inactiveNote.hidden = !reorderButton.disabled;
reorderNote.textContent = link.dataset.reorderNote;
reorderNote.hidden = !link.dataset.reorderNote;
consumeDialog.showModal();
});
});
+55 -1
View File
@@ -129,7 +129,8 @@ class CatalogTests(CatalogTestCase):
field = response.context["form"]["spool_type"]
self.assertEqual(field.value(), variant.spool_type)
self.assertEqual(
"refill" in dict(field.field.choices), variant.color_id == self.red.pk
"refill" in dict(field.field.choices),
url.startswith("/bestand/") or variant.color_id == self.red.pk,
)
data = self.selection(self.black_spool) | {"spool_type": "", "action": "filter"}
self.assertEqual(
@@ -227,6 +228,8 @@ class CatalogTests(CatalogTestCase):
OrderItem.objects.create(owner=self.bob, variant=self.spool, quantity=1)
self.spool.is_active = False
self.spool.save()
self.refill.is_active = False
self.refill.save(update_fields=["is_active"])
for url in ("/bestand/", "/bestellung/"):
self.assertContains(self.client.get(url), "Deaktiviert")
for url in ("/bestand/hinzufuegen/", "/bestellung/hinzufuegen/"):
@@ -242,6 +245,57 @@ class CatalogTests(CatalogTestCase):
dict(VariantSelectionForm(selection=self.selection()).fields["spool_type"].choices),
)
def test_inventory_spool_state_is_independent_of_the_catalog_offer(self):
self.spool.delete()
self.refill.manufacturer_color_code = "REFILL-123"
self.refill.save(update_fields=["manufacturer_color_code"])
add_url = "/bestand/hinzufuegen/"
order_url = "/bestellung/hinzufuegen/"
response = self.client.post(add_url, {"action": "lookup", "article_number": "REFILL-123"})
self.assertEqual(response.context["form"]["spool_type"].value(), "refill")
self.assertContains(response, "Filament auf Spule")
self.assertContains(response, "Ohne Spule")
mounted = self.selection(self.refill) | {"spool_type": "spool"}
self.assertRedirects(self.client.post(add_url, mounted), "/bestand/")
self.assertRedirects(self.client.post(add_url, mounted), "/bestand/")
self.assertRedirects(self.client.post(add_url, self.selection(self.refill)), "/bestand/")
positions = InventoryItem.objects.filter(owner=self.alice, variant=self.refill)
self.assertEqual(positions.get(spool_type="spool").quantity, 2)
self.assertEqual(positions.get(spool_type="refill").quantity, 1)
self.assertContains(self.client.get("/bestand/"), ">Mit Spule</span>")
self.assertContains(self.client.get("/bestand/"), ">Ohne Spule</span>")
self.assertContains(self.client.get("/bestand/"), "REFILL-123")
response = self.client.post(order_url, mounted)
self.assertTrue(response.context["form"]["spool_type"].errors)
self.assertFalse(OrderItem.objects.exists())
self.assertFalse(
Variant.objects.filter(
product_type=self.product, color=self.red, spool_type="spool"
).exists()
)
spool_only_without_spool = self.selection(self.black_spool) | {"spool_type": "refill"}
self.assertRedirects(self.client.post(add_url, spool_only_without_spool), "/bestand/")
self.assertEqual(InventoryItem.objects.get(variant=self.black_spool).spool_type, "refill")
# If the manufacturer adds a spool offer later, deliveries join the existing stock.
spool_offer = Variant.objects.create(
product_type=self.product, color=self.red, spool_type="spool"
)
order = OrderItem.objects.create(owner=self.alice, variant=spool_offer, quantity=3)
self.assertRedirects(
self.client.post(
f"/bestellung/{order.pk}/status/",
{"status": "handed_over", "expected_status": "open", "expected_quantity": 3},
),
"/bestellung/",
)
stock = InventoryItem.objects.filter(owner=self.alice)
self.assertEqual(stock.get(variant__color=self.red, spool_type="spool").quantity, 5)
self.assertEqual(stock.get(variant__color=self.red, spool_type="refill").quantity, 1)
order.refresh_from_db()
self.assertEqual(order.status, OrderItem.Status.HANDED_OVER)
def test_bambu_catalog_is_complete_one_time_bootstrap(self):
self.assertIn("seed_catalog", get_commands())
call_command("seed_catalog", verbosity=0)
+13
View File
@@ -41,6 +41,19 @@ class ConsumptionTests(CatalogTestCase):
self.assertEqual(self.stock.quantity, 1)
self.assertFalse(OrderItem.objects.exists())
def test_mounted_refill_is_reordered_in_its_catalog_packaging(self):
self.stock.variant = self.refill
self.stock.save(update_fields=["variant"])
self.assertContains(self.client.get(self.url), "Nachbestellung als Refill (ohne Spule).")
self.assertRedirects(
self.client.post(self.url, {"action": "reorder", "quantity": 2}),
reverse("inventory"),
)
self.assertEqual(OrderItem.objects.get(owner=self.alice).variant, self.refill)
self.stock.refresh_from_db()
self.assertEqual(self.stock.spool_type, "spool")
self.assertEqual(self.stock.quantity, 1)
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}
+13 -3
View File
@@ -148,7 +148,9 @@ def _edit_position(request, pk, positions, back):
{
"form": form,
"title": "Stückzahl ändern",
"description": str(item.variant),
"description": item.stock_description
if isinstance(item, InventoryItem)
else str(item.variant),
"back_name": back,
},
)
@@ -228,7 +230,7 @@ def _stock_items():
"variant__product_type__manufacturer__name",
"variant__product_type__name",
"variant__color__name",
"-variant__spool_type",
"-spool_type",
)
@@ -284,6 +286,7 @@ def inventory_add(request):
def _add_position(request, model, back, title, destination):
for_inventory = model is InventoryItem
selection = request.POST if request.method == "POST" else request.GET
action = request.POST.get("action")
is_add = request.method == "POST" and action not in {"filter", "lookup", "pick"}
@@ -320,10 +323,17 @@ def _add_position(request, model, back, title, destination):
form = VariantSelectionForm(
request.POST if is_add else None,
selection=selection,
for_inventory=for_inventory,
)
if is_add and form.is_valid():
try:
add_quantity(model, request.user, form.variant, form.cleaned_data["quantity"])
add_quantity(
model,
request.user,
form.variant,
form.cleaned_data["quantity"],
spool_type=form.cleaned_data["spool_type"] if for_inventory else None,
)
except ValidationError as error:
form.add_error(None, error)
else:
+1
View File
@@ -7,4 +7,5 @@
<button class="button" type="submit" name="action" value="reorder" {% if item and not item.variant.is_active %}disabled{% endif %}>Neue Spule in die Bestellung legen</button>
</div>
<p class="hint" data-inactive-note {% if not item or item.variant.is_active %}hidden{% endif %}>Diese Variante ist deaktiviert und kann aktuell nicht bestellt werden.</p>
<p class="hint" data-reorder-note {% if not item.reorder_spool_note %}hidden{% endif %}>{{ item.reorder_spool_note }}</p>
</form>
+1 -1
View File
@@ -2,7 +2,7 @@
{% block title %}Spule verbraucht · Fil-A-Management{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'inventory' %}">← Zurück zum Bestand</a>
<div class="page-heading"><div><h1>Spule verbraucht</h1><p class="muted">{{ item.variant }}</p></div></div>
<div class="page-heading"><div><h1>Spule verbraucht</h1><p class="muted">{{ item.stock_description }}</p></div></div>
<section class="panel form-panel">
{% include "filament/consume_options.html" %}
<a class="button secondary" href="{% url 'inventory' %}">Abbrechen</a>
+1 -1
View File
@@ -24,7 +24,7 @@
</div>
{% endif %}
<div class="form-grid">{% for field in form %}<div class="field">{{ field.label_tag }}{{ field }}{{ field.errors }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}</div>{% endfor %}</div>
<p class="hint">Jede Auswahl grenzt die folgenden Optionen ein. Nur aktive, angelegte Varianten sind wählbar.</p>
<p class="hint">{% if form.for_inventory %}Wähle bei der Spulenausführung, wie die Rolle bei dir vorliegt.{% else %}Jede Auswahl grenzt die folgenden Optionen ein. Nur aktive, angelegte Varianten sind wählbar.{% endif %}</p>
<div class="form-actions">
<button class="button secondary"
type="submit"
+2 -2
View File
@@ -9,13 +9,13 @@
<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.variant.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 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.variant }}" data-quantity="{{ item.quantity }}"{% if not item.variant.is_active %} data-inactive{% endif %}>Spule verbraucht</a>
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>
</td>
{% endif %}