Files
Fil-A-Management/filament/forms.py
T

412 lines
15 KiB
Python

from django import forms
from django.contrib.auth import get_user_model
from django.forms.models import ModelChoiceIterator
from .models import (
Color,
EmptySpool,
Feedback,
InventoryItem,
Manufacturer,
OrderItem,
Printer,
PrinterAddon,
PrinterNozzle,
ProductType,
SharedModel,
SharingPreferences,
SlicerTip,
Variant,
)
def selection_id(value):
text = str(value or "")
return int(text) if text.isascii() and text.isdecimal() and len(text) < 19 else None
class ProfileForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = ["first_name", "last_name", "email"]
class SharingPreferencesForm(forms.ModelForm):
class Meta:
model = SharingPreferences
fields = ["share_inventory", "share_printers"]
class SharedModelForm(forms.ModelForm):
class Meta:
model = SharedModel
fields = ["title", "description"]
widgets = {"description": forms.Textarea(attrs={"rows": 4})}
class SharedModelUploadForm(SharedModelForm):
class Meta(SharedModelForm.Meta):
fields = ["title", "description", "file"]
widgets = {
**SharedModelForm.Meta.widgets,
"file": forms.FileInput(attrs={"accept": ".stl,.3mf,.zip"}),
}
help_texts = {"file": "STL, 3MF oder ZIP. Maximal 50 MiB pro Datei."}
def clean_file(self):
upload = self.cleaned_data["file"]
if upload.size > 50 * 1024 * 1024:
raise forms.ValidationError("Die Datei darf höchstens 50 MiB groß sein.")
return upload
class SlicerTipForm(forms.ModelForm):
class Meta:
model = SlicerTip
fields = ["title", "text"]
widgets = {"text": forms.Textarea(attrs={"rows": 5})}
help_texts = {
"text": "Bis zu 1.000 Zeichen. Nenne bei Bedarf Slicer, Material und Einstellwert."
}
class PrinterForm(forms.ModelForm):
class Meta:
model = Printer
fields = ["manufacturer", "model", "name"]
class PrinterAddonForm(forms.ModelForm):
PRESETS = ("AMS (1. Generation)", "AMS 2 Pro", "AMS HT", "Filament Track Switch")
accessory = forms.ChoiceField(
label="Zubehör",
choices=[
("", "Zubehör wählen"),
*((name, name) for name in PRESETS),
("other", "Sonstiges"),
],
)
custom_name = forms.CharField(
label="Name für sonstiges Zubehör",
required=False,
max_length=100,
widget=forms.TextInput(attrs={"placeholder": "z. B. Filamenttrockner"}),
)
class Meta:
model = PrinterAddon
fields = ["accessory", "custom_name", "quantity"]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk:
name = self.instance.name
self.initial["accessory"] = name if name in self.PRESETS else "other"
if name not in self.PRESETS:
self.initial["custom_name"] = name
def clean(self):
cleaned = super().clean()
name = cleaned.get("accessory")
if name == "other":
name = cleaned.get("custom_name")
if not name:
self.add_error("custom_name", "Gib einen Namen für das Zubehör ein.")
self.instance.name = name or ""
return cleaned
class PrinterNozzleForm(forms.ModelForm):
class Meta:
model = PrinterNozzle
fields = ["hotend_type", "diameter_mm", "description", "quantity"]
localized_fields = ["diameter_mm"]
widgets = {
"diameter_mm": forms.TextInput(
attrs={"inputmode": "decimal", "placeholder": "z. B. 0,4"}
),
"description": forms.TextInput(
attrs={"placeholder": "z. B. gehärteter Stahl oder High Flow"}
),
}
class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
fields = ["message"]
widgets = {"message": forms.Textarea(attrs={"rows": 6})}
class QuantityForm(forms.Form):
quantity = forms.IntegerField(label="Stückzahl", min_value=1, max_value=9999)
expected_quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput)
class InventoryQuantityForm(QuantityForm):
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 EmptySpoolForm(forms.Form):
bambu_spool = forms.TypedChoiceField(
label="Spule",
choices=[("bambu", "Bambu Lab"), ("other", "Andere Spule")],
coerce=lambda value: value == "bambu",
initial="bambu",
)
item = forms.ModelChoiceField(
label="Filament zuordnen",
queryset=InventoryItem.objects.none(),
required=False,
empty_label="Als freie Leerrolle erfassen",
help_text="Je Zuordnung wird eine Rolle aus der gewählten Filamentposition verwendet.",
)
def __init__(self, *args, items, **kwargs):
super().__init__(*args, **kwargs)
self.fields["item"].queryset = items
class MountRefillForm(forms.Form):
quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput)
spool = forms.ModelChoiceField(
label="Freie Leerrolle",
queryset=EmptySpool.objects.none(),
empty_label=None,
)
def __init__(self, *args, owner, **kwargs):
super().__init__(*args, **kwargs)
self.fields["spool"].queryset = EmptySpool.objects.filter(owner=owner)
class AssignEmptySpoolForm(forms.Form):
item = forms.ModelChoiceField(
label="Filament ohne Spule",
queryset=InventoryItem.objects.none(),
empty_label="Filament auswählen",
)
def __init__(self, *args, items, **kwargs):
super().__init__(*args, **kwargs)
self.fields["item"].queryset = items
class ArticleLookupForm(forms.Form):
use_required_attribute = False
article_number = forms.CharField(
label="Artikelnummer (optional)",
max_length=Variant._meta.get_field("manufacturer_color_code").max_length,
error_messages={"required": "Bitte gib eine Artikelnummer ein."},
widget=forms.TextInput(
attrs={
"autocomplete": "off",
"spellcheck": "false",
"placeholder": "z. B. 40101",
"data-article-number": "",
}
),
)
class ConsumeSpoolForm(forms.Form):
quantity = forms.IntegerField(min_value=1, max_value=9999, widget=forms.HiddenInput)
action = forms.ChoiceField(choices=[("consume", "Verbrauchen"), ("reorder", "Nachbestellen")])
discard_spool = forms.BooleanField(required=False)
class OrderStatusForm(forms.Form):
status = forms.ChoiceField(choices=OrderItem.Status.choices)
expected_status = forms.ChoiceField(choices=OrderItem.Status.choices)
expected_quantity = forms.IntegerField(min_value=1, max_value=9999)
confirmation = forms.CharField(required=False, max_length=100)
class OrderHandoverForm(OrderStatusForm):
handover_quantity = forms.IntegerField(
label="Jetzt übergebene Stückzahl", min_value=1, max_value=9999
)
def clean_handover_quantity(self):
quantity = self.cleaned_data["handover_quantity"]
available = self.cleaned_data.get("expected_quantity")
if available is not None and quantity > available:
raise forms.ValidationError(
"Die Menge darf höchstens %(available)s betragen.", params={"available": available}
)
return quantity
class UndoOrderHandoverForm(forms.Form):
expected_revision = forms.UUIDField(widget=forms.HiddenInput)
class SubtypeChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.material_and_subtype[1]
class ColorChoiceIterator(ModelChoiceIterator):
def __iter__(self):
if self.field.empty_label is not None:
yield "", self.field.empty_label
for color in sorted(
self.queryset, key=lambda color: self.field.label_from_instance(color).casefold()
):
yield self.choice(color)
class ColorChoiceField(forms.ModelChoiceField):
iterator = ColorChoiceIterator
def label_from_instance(self, obj):
return self.labels.get(obj.pk, obj.name)
class ColorSelect(forms.Select):
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None):
option = super().create_option(name, value, label, selected, index, subindex, attrs)
if value and (swatch := self.swatches.get(value.instance.pk)):
option["attrs"]["data-swatch"] = swatch
return option
class VariantSelectionForm(forms.Form):
manufacturer = forms.ModelChoiceField(
label="Hersteller", queryset=Manufacturer.objects.none(), empty_label="Hersteller wählen"
)
material = forms.ChoiceField(label="Material", choices=[])
product_type = SubtypeChoiceField(
label="Unterart", queryset=ProductType.objects.none(), empty_label="Unterart wählen"
)
color = ColorChoiceField(
label="Farbe",
queryset=Color.objects.none(),
empty_label="Farbe wählen",
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"))
color = selection_id(values.get("color"))
self.fields["manufacturer"].queryset = Manufacturer.objects.filter(
producttype__variants__in=active
).distinct()
products = (
ProductType.objects.filter(manufacturer_id=maker, variants__in=active)
.select_related("manufacturer")
.distinct()
)
selected_material = values.get("material")
materials = {}
for candidate in products:
material = candidate.material_and_subtype[0]
materials.setdefault(material, []).append(candidate.pk)
self.fields["material"].choices = [("", "Material wählen")] + [
(material, material) for material in sorted(materials, key=str.casefold)
]
allowed_products = materials.get(selected_material, [])
self.fields["product_type"].queryset = products.filter(pk__in=allowed_products)
narrowed = active.filter(product_type_id=product, product_type_id__in=allowed_products)
color_field = self.fields["color"]
color_field.queryset = Color.objects.filter(variants__in=narrowed).distinct()
color_field.labels = {}
color_field.widget.swatches = {}
spools = set()
# A spool's label and preview take precedence when both packaging options supply them.
for variant in narrowed.select_related("product_type__manufacturer", "color").order_by(
"spool_type", "pk"
):
label = variant.color_label
if label != variant.color.name:
color_field.labels[variant.color_id] = label
if variant.swatch:
color_field.widget.swatches[variant.color_id] = variant.swatch
if variant.color_id == color:
spools.add(variant.spool_type)
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 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()
if all(
cleaned.get(k)
for k in ("manufacturer", "material", "product_type", "color", "spool_type")
):
variants = Variant.objects.filter(
is_active=True,
product_type=cleaned["product_type"],
product_type__manufacturer=cleaned["manufacturer"],
color=cleaned["color"],
)
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."
)
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