Improve inventory editing and shared equipment views

This commit is contained in:
Mikei386 committed 2026-11-17 09:16:11 +01:00
1 parent a85de26ee7
commit 84ed7da07f
19 files changed
+631 -206

No files matched your search

+22 -5
View File
@@ -1,5 +1,6 @@
from django import forms
from django.contrib.auth import get_user_model
from django.db.models import Q
from django.forms.models import ModelChoiceIterator
from .models import (
@@ -311,9 +312,14 @@ class VariantSelectionForm(forms.Form):
)
quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999, initial=1)
def __init__(self, *args, selection=None, for_inventory=False, **kwargs):
def __init__(self, *args, selection=None, for_inventory=False, current_variant=None, **kwargs):
super().__init__(*args, **kwargs)
self.for_inventory = for_inventory
self.available_variants = Variant.objects.filter(is_active=True)
if current_variant is not None:
self.available_variants = Variant.objects.filter(
Q(is_active=True) | Q(pk=current_variant.pk)
)
if not for_inventory:
del self.fields["spool_brand"]
values = self.data if self.is_bound else (selection or {})
@@ -325,7 +331,7 @@ class VariantSelectionForm(forms.Form):
Variant.SpoolType.SPOOL,
):
self.initial.pop("spool_brand", None)
active = Variant.objects.filter(is_active=True)
active = self.available_variants
maker = selection_id(values.get("manufacturer"))
product = selection_id(values.get("product_type"))
color = selection_id(values.get("color"))
@@ -391,13 +397,15 @@ class VariantSelectionForm(forms.Form):
cleaned.get(k)
for k in ("manufacturer", "material", "product_type", "color", "spool_type")
):
variants = Variant.objects.filter(
is_active=True,
variants = self.available_variants.filter(
product_type=cleaned["product_type"],
product_type__manufacturer=cleaned["manufacturer"],
color=cleaned["color"],
)
self.variant = variants.filter(spool_type=cleaned["spool_type"]).first()
preferred = selection_id(cleaned.get("catalog_variant"))
self.variant = variants.filter(pk=preferred).first() if preferred else None
if self.variant is None:
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:
@@ -409,3 +417,12 @@ class VariantSelectionForm(forms.Form):
else:
self.bambu_spool = False
return cleaned
class InventoryEditForm(VariantSelectionForm):
expected_quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput)
expected_revision = forms.UUIDField(widget=forms.HiddenInput)
catalog_variant = forms.CharField(required=False, max_length=19, widget=forms.HiddenInput)
def __init__(self, *args, item, **kwargs):
super().__init__(*args, for_inventory=True, current_variant=item.variant, **kwargs)
+80 -28
View File
@@ -5,7 +5,7 @@ from pathlib import Path
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Case, Value, When
from django.db.models import Case, Q, Value, When
from django.shortcuts import get_object_or_404
from django.utils import timezone
@@ -34,19 +34,7 @@ def add_quantity(model, owner, variant, quantity, *, spool_type=None, bambu_spoo
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(
owner_id=owner_id,
spool_type=spool_type,
bambu_spool=bambu_spool,
variant__product_type_id=variant.product_type_id,
variant__color_id=variant.color_id,
)
# Old catalog edits may have left several matches. Keep those rows and prefer the exact offer.
existing = (
positions.select_for_update()
.order_by(Case(When(variant_id=variant.pk, then=Value(0)), default=Value(1)), "pk")
.first()
)
existing = _matching_stock(owner_id, variant, spool_type, bambu_spool).first()
if existing is not None:
return _increase_quantity(existing, quantity)
return _increment_position(
@@ -59,6 +47,21 @@ def _increment_inventory(owner_id, variant, spool_type, quantity, *, bambu_spool
)
def _matching_stock(owner_id, variant, spool_type, bambu_spool):
# The stock position may already use the other catalog packaging for the same filament.
return (
InventoryItem.objects.select_for_update()
.filter(
owner_id=owner_id,
spool_type=spool_type,
bambu_spool=bambu_spool,
variant__product_type_id=variant.product_type_id,
variant__color_id=variant.color_id,
)
.order_by(Case(When(variant_id=variant.pk, then=Value(0)), default=Value(1)), "pk")
)
def _increment_position(positions, quantity, **lookup):
position, created = positions.select_for_update().get_or_create(
defaults={"quantity": quantity}, **lookup
@@ -291,23 +294,72 @@ def _assign_spool(item, bambu_spool):
@transaction.atomic
def update_inventory_position(owner, item_id, expected_quantity, quantity, *, bambu_spool=None):
def update_inventory_position(
owner,
item_id,
expected_quantity,
quantity,
*,
variant=None,
spool_type=None,
bambu_spool=None,
expected_revision=None,
):
item = _locked_inventory_item(owner, item_id, expected_quantity)
delta = quantity - item.quantity
if bambu_spool is None or bambu_spool == item.bambu_spool:
if not delta:
return
item.quantity = quantity
item.save(update_fields=["quantity"])
_record_stock_movement(item, StockMovement.Kind.ADJUSTED, delta)
if expected_revision is not None and item.revision != expected_revision:
raise ValidationError("Der Bestand hat sich geändert. Öffne die Position erneut.")
variant = variant or item.variant
if (
variant.pk != item.variant_id
and not Variant.objects.filter(pk=variant.pk, is_active=True).exists()
):
raise ValidationError("Diese Variante ist deaktiviert. Bitte wähle eine aktive Variante.")
if spool_type is None:
spool_type = item.spool_type
bambu_spool = item.bambu_spool if bambu_spool is None else bambu_spool
elif bambu_spool is None:
bambu_spool = variant.is_bambu_spool(spool_type)
if spool_type == Variant.SpoolType.REFILL:
bambu_spool = False
variant_changed = item.variant_id != variant.pk
spool_changed = (item.spool_type, item.bambu_spool) != (spool_type, bambu_spool)
old_quantity = item.quantity
delta = quantity - old_quantity
if not (variant_changed or spool_changed):
if delta:
item.quantity = quantity
item.save(update_fields=["quantity"])
_record_stock_movement(item, StockMovement.Kind.ADJUSTED, delta)
return
moved = _increment_inventory(
item.owner_id, item.variant, item.spool_type, quantity, bambu_spool=bambu_spool
if variant_changed:
_record_stock_movement(item, StockMovement.Kind.ADJUSTED, -old_quantity)
destination = (
_matching_stock(owner.pk, variant, spool_type, bambu_spool)
.exclude(pk=item.pk)
.filter(
Q(variant_id=variant.pk)
| Q(variant__manufacturer_color_code=variant.manufacturer_color_code)
)
.first()
)
_record_stock_movement(moved, StockMovement.Kind.SPOOLED, 0)
if delta:
_record_stock_movement(moved, StockMovement.Kind.ADJUSTED, delta)
item.delete()
if destination is None:
item.variant = variant
item.spool_type = spool_type
item.bambu_spool = bambu_spool
item.quantity = quantity
item.save(update_fields=["variant", "spool_type", "bambu_spool", "quantity"])
destination = item
else:
_increase_quantity(destination, quantity)
item.delete()
if variant_changed:
_record_stock_movement(destination, StockMovement.Kind.ADJUSTED, quantity)
else:
_record_stock_movement(destination, StockMovement.Kind.SPOOLED, 0)
if delta:
_record_stock_movement(destination, StockMovement.Kind.ADJUSTED, delta)
@transaction.atomic
+21 -4
View File
@@ -673,6 +673,18 @@ td.quantity {
.consume-dialog h2 {
margin-bottom: 8px;
}
.inventory-dialog {
width: min(46rem, calc(100% - 2rem));
}
.inventory-dialog-heading {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
}
.inventory-dialog [role="status"]:empty {
display: none;
}
.consume-options {
display: flex;
flex-wrap: wrap;
@@ -759,6 +771,9 @@ td.quantity {
margin-bottom: 16px;
border-bottom: 1px solid var(--line);
}
.article-search-visible {
padding-bottom: 16px;
}
.article-search summary {
padding: 0 0 12px;
color: var(--green);
@@ -1028,12 +1043,14 @@ td.quantity {
.shared-printers {
padding: 18px;
}
.profile-printers .printer-card,
.shared-printers ul {
.profile-printers .printer-card {
margin-bottom: 0;
}
.shared-printers h3 {
margin: 0;
.shared-printers .profile-printers {
padding: 0;
}
.shared-printers > h3 {
margin: 0 0 12px;
font-size: 1rem;
}
.sharing-options {
+87 -5
View File
@@ -33,7 +33,7 @@ if (consumeDialog?.showModal) {
});
}
function enhanceColorSelect(select) {
function enhanceColorSelect(select, signal) {
const options = [...select.options].filter((option) => option.value && !option.disabled);
if (!options.some((option) => option.dataset.swatch)) return;
@@ -136,7 +136,7 @@ function enhanceColorSelect(select) {
});
document.addEventListener("pointerdown", (event) => {
if (!picker.contains(event.target)) close();
});
}, { signal });
select.addEventListener("invalid", (event) => {
event.preventDefault();
@@ -149,13 +149,18 @@ function enhanceColorSelect(select) {
select.hidden = true;
}
const form = document.querySelector("[data-catalog-form]");
if (form) {
function initCatalogForm(form, signal) {
if (!form) return;
form.querySelector("[data-article-number]").addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
event.preventDefault();
form.requestSubmit(form.querySelector("[data-article-lookup]"));
});
form.querySelector("[name=quantity]").addEventListener("keydown", (event) => {
if (event.key !== "Enter" || event.isComposing) return;
event.preventDefault();
form.requestSubmit(form.querySelector("[data-catalog-save]"));
});
const selects = [...form.querySelectorAll(".form-grid select:not([data-spool-brand])")];
selects.forEach((select, index) => {
select.addEventListener("change", () => {
@@ -166,5 +171,82 @@ if (form) {
});
});
const colorSelect = form.querySelector("[data-color-select]");
if (colorSelect) enhanceColorSelect(colorSelect);
if (colorSelect) enhanceColorSelect(colorSelect, signal);
}
initCatalogForm(document.querySelector("[data-catalog-form]"));
const inventoryDialog = document.querySelector("[data-inventory-dialog]");
if (inventoryDialog?.showModal) {
const dialogContent = inventoryDialog.querySelector("[data-inventory-dialog-content]");
const dialogStatus = inventoryDialog.querySelector("[data-inventory-dialog-status]");
let pending;
let catalogControls;
async function loadEditor(url, options = {}) {
pending = new AbortController();
const controller = pending;
dialogContent.inert = true;
dialogStatus.textContent = options.method === "POST" ? "Änderung wird verarbeitet …" : "Position wird geladen …";
try {
const response = await fetch(url, {
...options,
headers: { "X-Inventory-Dialog": "1" },
signal: controller.signal,
});
if (response.status === 204) {
window.location.reload();
return;
}
if (!response.ok || response.redirected) throw new Error("Inventory editor unavailable");
const markup = new DOMParser().parseFromString(await response.text(), "text/html");
const editor = markup.querySelector("[data-inventory-editor]");
if (!editor) throw new Error("Missing inventory form");
if (pending !== controller || !inventoryDialog.open) return;
catalogControls?.abort();
catalogControls = new AbortController();
dialogContent.replaceChildren(editor);
initCatalogForm(dialogContent.querySelector("[data-catalog-form]"), catalogControls.signal);
dialogStatus.textContent = "";
} catch (error) {
if (controller.signal.aborted) return;
if (!options.method) {
window.location.assign(url);
} else {
dialogStatus.textContent = "Die Antwort konnte nicht geladen werden. Öffne die Position erneut und prüfe den Bestand.";
}
} finally {
if (pending === controller) {
pending = null;
dialogContent.inert = false;
}
}
}
document.querySelectorAll("[data-inventory-edit]").forEach((link) => {
link.addEventListener("click", (event) => {
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
event.preventDefault();
dialogContent.replaceChildren();
inventoryDialog.showModal();
loadEditor(link.href);
});
});
inventoryDialog.addEventListener("submit", (event) => {
if (!event.target.matches("[data-catalog-form]")) return;
event.preventDefault();
if (pending) return;
const body = new FormData(event.target);
if (event.submitter?.name) body.set(event.submitter.name, event.submitter.value);
loadEditor(event.target.getAttribute("action"), { method: "POST", body });
});
inventoryDialog.addEventListener("close", () => {
pending?.abort();
catalogControls?.abort();
pending = null;
dialogContent.replaceChildren();
dialogStatus.textContent = "";
});
}
+10 -2
View File
@@ -151,7 +151,11 @@ class CatalogTests(CatalogTestCase):
url = f"/{path}/hinzufuegen/"
response = self.client.get(url)
article_input = response.context["lookup"]["article_number"].as_widget()
self.assertContains(response, '<details class="article-search">')
if path == "bestand":
self.assertContains(response, 'class="article-search article-search-visible"')
self.assertNotContains(response, '<details class="article-search"')
else:
self.assertContains(response, '<details class="article-search">')
self.assertIn('name="article_number"', article_input)
self.assertNotIn("required", article_input)
self.assertRedirects(
@@ -159,7 +163,11 @@ class CatalogTests(CatalogTestCase):
)
self.assertEqual(model.objects.get(variant=self.spool).quantity, 1)
response = self.client.post(url, {"action": "lookup", "article_number": ""})
self.assertContains(response, '<details class="article-search" open>')
if path == "bestand":
self.assertContains(response, 'class="article-search article-search-visible"')
self.assertNotContains(response, '<details class="article-search"')
else:
self.assertContains(response, '<details class="article-search" open>')
self.assertContains(response, "Bitte gib eine Artikelnummer ein.")
def test_article_lookup_prefills_both_forms_and_preserves_quantity(self):
+17 -4
View File
@@ -229,11 +229,14 @@ class ProfilePrinterTests(CatalogTestCase):
self.assertFalse(PrinterAddon.objects.exists())
self.assertFalse(PrinterNozzle.objects.exists())
def test_printer_equipment_is_private_and_permissions_follow_the_printer(self):
def test_printer_equipment_shares_read_only_with_its_printer(self):
printer = Printer.objects.create(owner=self.alice, manufacturer="Bambu Lab", model="H2C")
another = Printer.objects.create(owner=self.alice, manufacturer="Bambu Lab", model="A1")
addon = PrinterAddon.objects.create(printer=printer, name="Filament Track Switch")
SharingPreferences.objects.create(owner=self.alice, share_printers=True)
PrinterNozzle.objects.create(
printer=printer, hotend_type="induction", diameter_mm="0.6", description="Gehärtet"
)
preferences = SharingPreferences.objects.create(owner=self.alice, share_inventory=True)
edit = reverse("printer_equipment_edit", args=[printer.pk, "zubehoer", addon.pk])
wrong_printer = reverse("printer_equipment_edit", args=[another.pk, "zubehoer", addon.pk])
self.assertEqual(self.client.get(wrong_printer).status_code, 404)
@@ -241,6 +244,11 @@ class ProfilePrinterTests(CatalogTestCase):
csrf.force_login(self.alice)
self.assertEqual(csrf.post(edit, {"accessory": "AMS HT", "quantity": 1}).status_code, 403)
self.client.force_login(self.bob)
shared_url = reverse("shared_inventory")
self.assertNotContains(self.client.get(shared_url), addon.name)
self.assertNotContains(self.client.get(shared_url), "Gehärtet")
preferences.share_printers = True
preferences.save(update_fields=["share_printers"])
for url in (
reverse("printer_equipment_add", args=[printer.pk, "zubehoer"]),
edit,
@@ -250,6 +258,11 @@ class ProfilePrinterTests(CatalogTestCase):
self.assertEqual(
self.client.post(url, {"accessory": "AMS HT", "quantity": 1}).status_code, 404
)
shared = self.client.get(reverse("shared_inventory"))
shared = self.client.get(shared_url)
self.assertContains(shared, "H2C")
self.assertNotContains(shared, addon.name)
self.assertContains(shared, addon.name)
self.assertContains(shared, "Gehärtet")
self.assertContains(shared, "0,6 mm")
self.assertNotContains(shared, edit)
self.assertNotContains(shared, "+ Zubehör")
self.assertNotContains(shared, "+ Düse")
+132 -1
View File
@@ -1,4 +1,15 @@
from filament.models import Color, InventoryItem, Manufacturer, ProductType, Variant
from django.test import Client
from django.urls import reverse
from filament.models import (
Color,
InventoryItem,
Manufacturer,
ProductType,
SharingPreferences,
StockMovement,
Variant,
)
from .base import CatalogTestCase
@@ -30,6 +41,126 @@ class InventoryWebTests(CatalogTestCase):
spool.refresh_from_db()
self.assertEqual((refill_on_spool.quantity, spool.quantity), (1, 3))
def test_inventory_dialog_edits_full_position_and_merges_an_identical_destination(self):
source = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=2)
maker = Manufacturer.objects.create(name="SUNLU")
product = ProductType.objects.create(manufacturer=maker, name="PETG Standard")
target_variant = Variant.objects.create(
product_type=product,
color=self.black,
spool_type="refill",
manufacturer_color_code="42",
)
target = InventoryItem.objects.create(owner=self.alice, variant=target_variant, quantity=3)
InventoryItem.objects.create(owner=self.bob, variant=target_variant, quantity=8)
client = Client(enforce_csrf_checks=True)
client.force_login(self.alice)
self.assertContains(client.get(reverse("inventory")), "data-inventory-edit")
url = reverse("inventory_edit", args=[source.pk])
headers = {"X-Inventory-Dialog": "1"}
response = client.get(url, headers=headers)
self.assertTemplateUsed(response, "filament/inventory_edit_form.html")
self.assertNotContains(response, "<!DOCTYPE html>")
self.assertEqual(response.context["form"].initial["catalog_variant"], source.variant_id)
initial = response.context["form"].initial
response = client.post(
url,
initial
| {
"article_number": "42",
"action": "lookup",
"csrfmiddlewaretoken": client.cookies["csrftoken"].value,
},
headers=headers,
)
selected = response.context["form"].initial
self.assertEqual(selected["catalog_variant"], target_variant.pk)
self.assertEqual(selected["expected_revision"], str(source.revision))
self.assertContains(response, "Kohleschwarz")
data = selected | {"quantity": 4}
self.assertEqual(client.post(url, data, headers=headers).status_code, 403)
data["csrfmiddlewaretoken"] = client.cookies["csrftoken"].value
self.assertEqual(client.post(url, data, headers=headers).status_code, 204)
self.assertFalse(InventoryItem.objects.filter(pk=source.pk).exists())
target.refresh_from_db()
self.assertEqual(
(target.quantity, target.spool_type, target.bambu_spool), (7, "refill", False)
)
self.assertEqual(InventoryItem.objects.get(owner=self.bob).quantity, 8)
self.assertEqual(
list(
StockMovement.objects.filter(owner=self.alice)
.order_by("pk")
.values_list("quantity_change", flat=True)
),
[-2, 4],
)
def test_inventory_edit_keeps_mounted_refill_reference_and_rejects_stale_changes(self):
self.refill.is_active = False
self.refill.save(update_fields=["is_active"])
item = InventoryItem.objects.create(
owner=self.alice, variant=self.refill, quantity=2, spool_type="spool"
)
self.client.force_login(self.alice)
url = reverse("inventory_edit", args=[item.pk])
initial = self.client.get(url).context["form"].initial
self.assertEqual(initial["spool_type"], "spool")
self.assertRedirects(
self.client.post(url, initial | {"spool_brand": "other"}), reverse("inventory")
)
item.refresh_from_db()
self.assertEqual(
(item.variant_id, item.quantity, item.bambu_spool), (self.refill.pk, 2, False)
)
response = self.client.post(url, initial | {"quantity": 1})
self.assertContains(response, "Der Bestand hat sich geändert.")
item.refresh_from_db()
self.assertEqual(item.quantity, 2)
def test_inventory_edit_merges_physical_spool_state_even_with_different_catalog_packaging(self):
Variant.objects.filter(pk__in=[self.spool.pk, self.refill.pk]).update(
manufacturer_color_code="11200"
)
spool = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=2)
refill = InventoryItem.objects.create(owner=self.alice, variant=self.refill, quantity=3)
self.client.force_login(self.alice)
url = reverse("inventory_edit", args=[spool.pk])
initial = self.client.get(url).context["form"].initial
response = self.client.post(url, initial | {"spool_type": "refill"})
self.assertRedirects(response, reverse("inventory"))
self.assertFalse(InventoryItem.objects.filter(pk=spool.pk).exists())
refill.refresh_from_db()
self.assertEqual(
(refill.spool_type, refill.quantity, refill.bambu_spool), ("refill", 5, False)
)
def test_shared_inventory_can_sort_members_own_tables(self):
maker = Manufacturer.objects.create(name="Zulu")
product = ProductType.objects.create(manufacturer=maker, name="ABS Basic")
color = Color.objects.create(name="Aquablau")
other = Variant.objects.create(product_type=product, color=color, spool_type="spool")
first = InventoryItem.objects.create(owner=self.alice, variant=self.spool, quantity=2)
second = InventoryItem.objects.create(owner=self.alice, variant=other, quantity=3)
SharingPreferences.objects.create(owner=self.alice, share_inventory=True)
self.client.force_login(self.bob)
url = reverse("shared_inventory")
for key, ascending in (
("manufacturer", [first, second]),
("product", [second, first]),
("color", [second, first]),
):
for direction, expected in (("asc", ascending), ("desc", ascending[::-1])):
with self.subTest(key=key, direction=direction):
response = self.client.get(url, {"sort": key, "direction": direction})
groups = response.context["members"][0]["groups"]
self.assertEqual([item for group in groups for item in group], expected)
self.assertContains(
response,
f'aria-sort="{"ascending" if direction == "asc" else "descending"}"',
)
self.assertNotContains(response, "data-inventory-edit")
def test_inventory_search_matches_each_field_and_preserves_sorting(self):
self.client.force_login(self.alice)
asa = ProductType.objects.create(manufacturer=self.maker, name="ASA Basic")
+168 -95
View File
@@ -21,6 +21,7 @@ from .forms import (
ConsumeSpoolForm,
EmptySpoolForm,
FeedbackForm,
InventoryEditForm,
InventoryQuantityForm,
MountRefillForm,
OrderHandoverForm,
@@ -228,45 +229,28 @@ def _edit_position(request, pk, positions, back):
pk=pk,
owner=request.user,
)
inventory_item = isinstance(item, InventoryItem)
form_class = InventoryQuantityForm if inventory_item else QuantityForm
form = form_class(
form = QuantityForm(
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():
quantity = form.cleaned_data["quantity"]
try:
if inventory_item:
update_inventory_position(
request.user,
item.pk,
form.cleaned_data["expected_quantity"],
quantity,
bambu_spool=form.cleaned_data.get("bambu_spool"),
)
else:
if item.quantity != form.cleaned_data["expected_quantity"]:
raise ValidationError(
"Die Stückzahl hat sich geändert. Öffne die Position erneut und prüfe den aktuellen Wert."
)
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."
if item.quantity != form.cleaned_data["expected_quantity"]:
form.add_error(
None,
"Die Stückzahl hat sich geändert. Öffne die Position erneut und prüfe den aktuellen Wert.",
)
else:
item.quantity = form.cleaned_data["quantity"]
item.save(update_fields=["quantity"])
messages.success(request, "Stückzahl geändert.")
return redirect(back)
return render(
request,
"filament/form.html",
{
"form": form,
"title": "Bestand bearbeiten" if inventory_item else "Stückzahl ändern",
"description": item.stock_description if inventory_item else str(item.variant),
"title": "Stückzahl ändern",
"description": str(item.variant),
"back_name": back,
},
)
@@ -287,7 +271,56 @@ def _delete_position(request, pk, model, back, success_url=None):
@login_required
@require_http_methods(["GET", "POST"])
def inventory_edit(request, pk):
return _edit_position(request, pk, InventoryItem.objects.all(), "inventory")
item = get_object_or_404(_stock_items(), pk=pk, owner=request.user)
modal = request.headers.get("X-Inventory-Dialog") == "1"
initial = _variant_selection(item.variant) | {
"quantity": item.quantity,
"spool_type": item.spool_type,
"spool_brand": "bambu" if item.bambu_spool else "other",
"expected_quantity": item.quantity,
"expected_revision": item.revision,
"article_number": item.variant.manufacturer_color_code,
}
save = _is_catalog_save(request)
selection, lookup, matches = _catalog_selection(request, initial)
form = InventoryEditForm(request.POST if save else None, item=item, selection=selection)
# Quantity-only submissions from forms opened before this update still work.
legacy = save and "manufacturer" not in request.POST
if legacy:
form = InventoryQuantityForm(request.POST, item=item)
if save and form.is_valid():
values = form.cleaned_data
changes = (
{"bambu_spool": values.get("bambu_spool")}
if legacy
else {
"variant": form.variant,
"spool_type": values["spool_type"],
"bambu_spool": form.bambu_spool,
"expected_revision": values["expected_revision"],
}
)
try:
update_inventory_position(
request.user, item.pk, values["expected_quantity"], values["quantity"], **changes
)
except ValidationError as error:
form.add_error(None, error)
else:
messages.success(request, "Bestand geändert.")
return HttpResponse(status=204) if modal else redirect("inventory")
return render(
request,
"filament/inventory_edit_form.html" if modal else "filament/inventory_edit.html",
{
"item": item,
"form": form,
"lookup": lookup,
"matches": matches,
"editing": True,
"legacy": legacy,
},
)
@login_required
@@ -476,37 +509,8 @@ def inventory(request):
search = request.GET.get("q", "").strip()
terms = search.casefold().split()
visible_items = [item for item in items if _stock_matches(item, terms)] if terms else items
sort = request.GET.get("sort")
descending = request.GET.get("direction") == "desc"
sort_keys = {
"manufacturer": lambda item: item.variant.manufacturer.name.casefold(),
"product": lambda item: item.variant.product_type.name.casefold(),
"color": lambda item: item.variant.color_label.casefold(),
"spool": lambda item: item.get_spool_type_display().casefold(),
"article": _stock_article_sort_key,
"quantity": lambda item: item.quantity,
}
sort = sort if sort in sort_keys else ""
if sort:
visible_items.sort(key=sort_keys[sort], reverse=descending)
if sort == "article":
visible_items.sort(key=lambda item: not item.variant.manufacturer_color_code.strip())
# These columns can put rows of the same product and color in different places.
groups = (
[[item] for item in visible_items]
if sort in {"spool", "article", "quantity"}
else _group_stock(visible_items)
)
columns = [
{
"key": key,
"label": label,
"title": title,
"direction": ("descending" if descending else "ascending") if sort == key else "",
"next_direction": "desc" if sort == key and not descending else "asc",
}
for key, label, title in STOCK_COLUMNS
]
sort, descending, columns = _stock_sort(request)
groups = _sort_and_group_stock(visible_items, sort, descending)
return render(
request,
"filament/inventory.html",
@@ -525,6 +529,42 @@ def inventory(request):
)
def _stock_sort(request):
requested = request.GET.get("sort", "")
sort = requested if any(requested == key for key, _, _ in STOCK_COLUMNS) else ""
descending = request.GET.get("direction") == "desc"
columns = [
{
"key": key,
"label": label,
"title": title,
"direction": ("descending" if descending else "ascending") if sort == key else "",
"next_direction": "desc" if sort == key and not descending else "asc",
}
for key, label, title in STOCK_COLUMNS
]
return sort, descending, columns
def _sort_and_group_stock(items, sort, descending):
sort_keys = {
"manufacturer": lambda item: item.variant.manufacturer.name.casefold(),
"product": lambda item: item.variant.product_type.name.casefold(),
"color": lambda item: item.variant.color_label.casefold(),
"spool": lambda item: item.get_spool_type_display().casefold(),
"article": _stock_article_sort_key,
"quantity": lambda item: item.quantity,
}
if sort:
items.sort(key=sort_keys[sort], reverse=descending)
if sort == "article":
items.sort(key=lambda item: not item.variant.manufacturer_color_code.strip())
# These columns can put rows of the same product and color in different places.
if sort in {"spool", "article", "quantity"}:
return [[item] for item in items]
return _group_stock(items)
@login_required
@require_http_methods(["GET", "HEAD"])
def stock_history(request):
@@ -592,6 +632,7 @@ def _group_stock(items):
@login_required
@require_http_methods(["GET", "HEAD"])
def shared_inventory(request):
sort, descending, columns = _stock_sort(request)
members = {}
items = (
_stock_items()
@@ -606,6 +647,7 @@ def shared_inventory(request):
Printer.objects.filter(owner__is_active=True, owner__sharing__share_printers=True)
.exclude(owner=request.user)
.select_related("owner")
.prefetch_related("addons", "nozzles")
)
for printer in printers:
members.setdefault(printer.owner.username, {"items": [], "printers": []})[
@@ -615,12 +657,14 @@ def shared_inventory(request):
shared = [
{
"username": username,
"groups": _group_stock(member["items"]),
"groups": _sort_and_group_stock(member["items"], sort, descending),
"printers": member["printers"],
}
for username, member in sorted(members.items(), key=lambda entry: entry[0].casefold())
]
return render(request, "filament/shared_inventory.html", {"members": shared})
return render(
request, "filament/shared_inventory.html", {"members": shared, "columns": columns}
)
@login_required
@@ -633,39 +677,8 @@ 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"}
lookup = ArticleLookupForm(request.POST if action in {"lookup", "pick"} else None)
matches = []
if lookup.is_bound and lookup.is_valid():
matches = list(
Variant.objects.filter(
is_active=True,
manufacturer_color_code__iexact=lookup.cleaned_data["article_number"],
).select_related("product_type__manufacturer", "color")
)
if not matches:
lookup.add_error(
"article_number", "Zu dieser Artikelnummer gibt es keinen aktiven Eintrag."
)
else:
match = matches[0] if len(matches) == 1 else None
if action == "pick":
picked = selection_id(request.POST.get("article_variant"))
match = next((variant for variant in matches if variant.pk == picked), None)
if match is None:
lookup.add_error("article_number", "Bitte wähle eine der gefundenen Varianten.")
if match is not None:
selection = {
"manufacturer": match.manufacturer.pk,
"material": match.product_type.material_and_subtype[0],
"product_type": match.product_type_id,
"color": match.color_id,
"spool_type": match.spool_type,
"quantity": selection.get("quantity", 1),
}
matches = []
selection, lookup, matches = _catalog_selection(request)
is_add = _is_catalog_save(request)
form = VariantSelectionForm(
request.POST if is_add else None,
selection=selection,
@@ -702,6 +715,66 @@ def _add_position(request, model, back, title, destination):
)
def _is_catalog_save(request):
return request.method == "POST" and request.POST.get("action") not in {
"filter",
"lookup",
"pick",
}
def _variant_selection(variant):
return {
"manufacturer": variant.manufacturer.pk,
"material": variant.product_type.material_and_subtype[0],
"product_type": variant.product_type_id,
"color": variant.color_id,
"spool_type": variant.spool_type,
"catalog_variant": variant.pk,
}
def _catalog_selection(request, initial=None):
selection = (
request.POST
if request.method == "POST"
else (initial if initial is not None else request.GET)
)
action = request.POST.get("action")
lookup = ArticleLookupForm(
request.POST if action in {"lookup", "pick"} else None,
initial={"article_number": selection.get("article_number", "")},
)
matches = []
if lookup.is_bound and lookup.is_valid():
matches = list(
Variant.objects.filter(
is_active=True,
manufacturer_color_code__iexact=lookup.cleaned_data["article_number"],
).select_related("product_type__manufacturer", "color")
)
if not matches:
lookup.add_error(
"article_number", "Zu dieser Artikelnummer gibt es keinen aktiven Eintrag."
)
else:
match = matches[0] if len(matches) == 1 else None
if action == "pick":
picked = selection_id(request.POST.get("article_variant"))
match = next((variant for variant in matches if variant.pk == picked), None)
if match is None:
lookup.add_error("article_number", "Bitte wähle eine der gefundenen Varianten.")
if match is not None:
selection = _variant_selection(match) | {
key: selection[key]
for key in ("expected_quantity", "expected_revision", "spool_brand")
if key in selection
}
selection["quantity"] = request.POST.get("quantity", 1)
matches = []
return selection, lookup, matches
@login_required
def orders(request):
entries = list(
+8
View File
@@ -36,6 +36,14 @@
</div>
{% if groups %}
{% include "filament/stock_table.html" with groups=groups columns=columns editable=True search=search only %}
<dialog class="consume-dialog inventory-dialog" aria-labelledby="inventory-edit-title" data-inventory-dialog>
<div class="inventory-dialog-heading">
<h2 id="inventory-edit-title">Bestand bearbeiten</h2>
<form method="dialog"><button class="button secondary" type="submit">Schließen</button></form>
</div>
<p data-inventory-dialog-status role="status"></p>
<div data-inventory-dialog-content></div>
</dialog>
<dialog class="consume-dialog" aria-labelledby="consume-title" data-consume-dialog>
<h2 id="consume-title">Spule verbraucht</h2>
<p class="muted" data-consume-variant></p>
+9
View File
@@ -0,0 +1,9 @@
{% extends "base.html" %}
{% block title %}Bestand bearbeiten · Fil-A-Management{% endblock %}
{% block content %}
<a class="back-link" href="{% url 'inventory' %}">← Zurück zum Bestand</a>
<div class="page-heading"><h1>Bestand bearbeiten</h1></div>
<section class="panel form-panel variant-panel">
{% include "filament/inventory_edit_form.html" %}
</section>
{% endblock %}
@@ -0,0 +1,4 @@
<div data-inventory-editor>
<p class="muted">{{ item.stock_description }}</p>
{% include "filament/variant_form.html" %}
</div>
+3 -3
View File
@@ -5,11 +5,11 @@
<span class="badge">{{ printer.manufacturer }}</span>
<h3>{{ printer.model }}</h3>
{% if printer.name %}<p class="muted">{{ printer.name }}</p>{% endif %}
<div class="actions">
{% if editable %}<div class="actions">
<a href="{% url 'printer_edit' printer.pk %}">Bearbeiten</a>
<a class="danger-link" href="{% url 'printer_delete' printer.pk %}">Entfernen</a>
</div>
{% include "filament/printer_equipment.html" with printer=printer only %}
</div>{% endif %}
{% include "filament/printer_equipment.html" with printer=printer editable=editable only %}
</section>
{% endfor %}
</div>
+10 -10
View File
@@ -1,25 +1,25 @@
<div class="printer-equipment">
<div class="printer-equipment-heading">
{% if editable or printer.addons.all %}<div class="printer-equipment-heading">
<h4>Zubehör</h4>
<a href="{% url 'printer_equipment_add' printer.pk 'zubehoer' %}">+ Zubehör</a>
</div>
{% if editable %}<a href="{% url 'printer_equipment_add' printer.pk 'zubehoer' %}">+ Zubehör</a>{% endif %}
</div>{% endif %}
{% if printer.addons.all %}
<ul class="printer-equipment-list">
{% for item in printer.addons.all %}
<li>
<span>{{ item.quantity }} × {{ item.name }}</span>
<div class="actions">
{% if editable %}<div class="actions">
<a href="{% url 'printer_equipment_edit' printer.pk 'zubehoer' item.pk %}" aria-label="{{ item.name }} bearbeiten">Bearbeiten</a>
<a class="danger-link" href="{% url 'printer_equipment_delete' printer.pk 'zubehoer' item.pk %}" aria-label="{{ item.name }} entfernen">Entfernen</a>
</div>
</div>{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
<div class="printer-equipment-heading">
{% if editable or printer.nozzles.all %}<div class="printer-equipment-heading">
<h4>Düsen</h4>
<a href="{% url 'printer_equipment_add' printer.pk 'duesen' %}">+ Düse</a>
</div>
{% if editable %}<a href="{% url 'printer_equipment_add' printer.pk 'duesen' %}">+ Düse</a>{% endif %}
</div>{% endif %}
{% if printer.nozzles.all %}
<ul class="printer-equipment-list">
{% for item in printer.nozzles.all %}
@@ -29,10 +29,10 @@
<span class="badge">{{ item.get_hotend_type_display }}</span>
{% if item.description %}<small class="muted">{{ item.description }}</small>{% endif %}
</div>
<div class="actions">
{% if editable %}<div class="actions">
<a href="{% url 'printer_equipment_edit' printer.pk 'duesen' item.pk %}" aria-label="{{ item }} bearbeiten">Bearbeiten</a>
<a class="danger-link" href="{% url 'printer_equipment_delete' printer.pk 'duesen' item.pk %}" aria-label="{{ item }} entfernen">Entfernen</a>
</div>
</div>{% endif %}
</li>
{% endfor %}
</ul>
+1 -1
View File
@@ -7,6 +7,6 @@
<h1>Meine Drucker</h1>
<a class="button" href="{% url 'printer_add' %}">+ Drucker hinzufügen</a>
</div>
{% include "filament/printer_cards.html" with printers=printers only %}
{% include "filament/printer_cards.html" with printers=printers editable=True only %}
</section>
{% endblock %}
+1 -1
View File
@@ -32,6 +32,6 @@
<h2>Meine Drucker</h2>
<a class="button" href="{% url 'printer_add' %}">+ Drucker hinzufügen</a>
</div>
{% include "filament/printer_cards.html" with printers=printers only %}
{% include "filament/printer_cards.html" with printers=printers editable=True only %}
</section>
{% endblock %}
+2 -40
View File
@@ -1,44 +1,6 @@
{% extends "base.html" %}{% block title %}{{ title }} · Fil-A-Management{% endblock %}{% block content %}
<a class="back-link" href="{% url back_name %}">← Zurück</a><div class="page-heading"><div><p class="eyebrow">AUS DEM GEMEINSAMEN KATALOG</p><h1>{{ title }}</h1><p class="muted">Wähle eine Variante für {{ destination }} oder suche nach ihrer Artikelnummer.</p></div></div>
<section class="panel form-panel variant-panel"><form method="post" data-catalog-form>{% csrf_token %}{{ form.non_field_errors }}
<details class="article-search"{% if lookup.is_bound %} open{% endif %}>
<summary>Nach Artikelnummer suchen <span class="muted">(optional)</span></summary>
<div class="field">
{{ lookup.article_number.label_tag }}
<div class="article-lookup">
{{ lookup.article_number }}
<button class="button secondary" type="submit" name="action" value="lookup" formnovalidate data-article-lookup>Variante suchen</button>
</div>
{{ lookup.article_number.errors }}
</div>
{% if matches %}
<div class="field">
<label for="article-variant">Mehrere Varianten gefunden</label>
<div class="article-lookup">
<select id="article-variant" name="article_variant">
<option value="">Variante auswählen</option>
{% for variant in matches %}
<option value="{{ variant.pk }}">{{ variant }}{% if variant.net_weight_g %} · {{ variant.net_weight_g }} g{% endif %}</option>
{% endfor %}
</select>
<button class="button secondary" type="submit" name="action" value="pick" formnovalidate>Auswahl übernehmen</button>
</div>
</div>
{% endif %}
</details>
<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">{% 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"
name="action"
value="filter"
formnovalidate
data-filter-button>Auswahl aktualisieren</button><button class="button" type="submit">Hinzufügen</button>
</div>
<noscript>
<p>Nach jeder Dropdown-Auswahl bitte „Auswahl aktualisieren“ drücken.</p>
</noscript>
</form>
<section class="panel form-panel variant-panel">
{% include "filament/variant_form.html" %}
</section>
{% endblock %}
+2 -6
View File
@@ -6,16 +6,12 @@
<section class="panel shared-member">
<div class="panel-heading"><h2>{{ member.username }}</h2></div>
{% if member.groups %}
{% include "filament/stock_table.html" with groups=member.groups only %}
{% include "filament/stock_table.html" with groups=member.groups columns=columns only %}
{% endif %}
{% if member.printers %}
<div class="shared-printers">
<h3>Drucker</h3>
<ul>
{% for printer in member.printers %}
<li>{{ printer.manufacturer }} {{ printer.model }}{% if printer.name %} <small>· {{ printer.name }}</small>{% endif %}</li>
{% endfor %}
</ul>
{% include "filament/printer_cards.html" with printers=member.printers only %}
</div>
{% endif %}
</section>
+1 -1
View File
@@ -32,7 +32,7 @@
<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 item.spool_type == "spool" %} data-has-spool{% endif %}{% if not item.reorder_variant %} 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>
<a href="{% url 'inventory_edit' item.pk %}" data-inventory-edit>Bearbeiten</a>
</td>
{% endif %}
</tr>
+53
View File
@@ -0,0 +1,53 @@
<form method="post"{% if editing %} action="{% url 'inventory_edit' item.pk %}"{% endif %}{% if not legacy %} data-catalog-form{% endif %}>
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form.hidden_fields %}{{ field }}{{ field.errors }}{% endfor %}
{% if not legacy %}
{% if form.for_inventory %}
<div class="article-search article-search-visible">
{% else %}
<details class="article-search"{% if lookup.is_bound %} open{% endif %}>
<summary>Nach Artikelnummer suchen <span class="muted">(optional)</span></summary>
{% endif %}
<div class="field">
{{ lookup.article_number.label_tag }}
<div class="article-lookup">
{{ lookup.article_number }}
<button class="button secondary" type="submit" name="action" value="lookup" formnovalidate data-article-lookup>Variante suchen</button>
</div>
{{ lookup.article_number.errors }}
</div>
{% if matches %}
<div class="field">
<label for="article-variant">Mehrere Varianten gefunden</label>
<div class="article-lookup">
<select id="article-variant" name="article_variant">
<option value="">Variante auswählen</option>
{% for variant in matches %}
<option value="{{ variant.pk }}">{{ variant }}{% if variant.net_weight_g %} · {{ variant.net_weight_g }} g{% endif %}</option>
{% endfor %}
</select>
<button class="button secondary" type="submit" name="action" value="pick" formnovalidate>Auswahl übernehmen</button>
</div>
</div>
{% endif %}
{% if form.for_inventory %}</div>{% else %}</details>{% endif %}
{% endif %}
<div class="form-grid">
{% for field in form.visible_fields %}
<div class="field">{{ field.label_tag }}{{ field }}{{ field.errors }}{% if field.help_text %}<small>{{ field.help_text }}</small>{% endif %}</div>
{% endfor %}
</div>
{% if not legacy %}
<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>
{% endif %}
<div class="form-actions">
{% if not legacy %}
<button class="button secondary" type="submit" name="action" value="filter" formnovalidate data-filter-button>Auswahl aktualisieren</button>
{% endif %}
<button class="button" type="submit" data-catalog-save>{% if editing %}Speichern{% else %}Hinzufügen{% endif %}</button>
</div>
{% if not legacy %}
<noscript><p>Nach jeder Dropdown-Auswahl bitte „Auswahl aktualisieren“ drücken.</p></noscript>
{% endif %}
</form>