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

373 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from django.conf import settings
from django.core.validators import MaxValueValidator, MinValueValidator, RegexValidator
from django.db import models
class Manufacturer(models.Model):
name = models.CharField("Hersteller", max_length=100, unique=True)
class Meta:
ordering = ["name"]
verbose_name = "Hersteller"
verbose_name_plural = "Hersteller"
def __str__(self):
return self.name
class ProductType(models.Model):
manufacturer = models.ForeignKey(
Manufacturer, on_delete=models.PROTECT, verbose_name="Hersteller"
)
name = models.CharField("Produktart", max_length=100)
class Meta:
ordering = ["manufacturer__name", "name"]
constraints = [
models.UniqueConstraint(
fields=["manufacturer", "name"], name="unique_product_per_manufacturer"
)
]
verbose_name = "Produktart"
verbose_name_plural = "Produktarten"
def __str__(self):
return f"{self.manufacturer} · {self.name}"
@property
def material_and_subtype(self):
name = self.name.strip()
brand = self.manufacturer.name.strip() + " "
if name.casefold().startswith(brand.casefold()):
name = name[len(brand) :].lstrip(" ·-")
material, _, subtype = name.partition(" ")
if "-" in material:
material, suffix = material.split("-", 1)
subtype = " ".join(part for part in (suffix, subtype) if part)
return material or name, subtype.strip() or material or name
class Color(models.Model):
name = models.CharField("Farbe", max_length=100, unique=True)
class Meta:
ordering = ["name"]
verbose_name = "Farbe"
verbose_name_plural = "Farben"
def __str__(self):
return self.name
class Variant(models.Model):
class SpoolType(models.TextChoices):
SPOOL = "spool", "Mit Spule"
REFILL = "refill", "Refill (ohne Spule)"
product_type = models.ForeignKey(
ProductType, on_delete=models.PROTECT, related_name="variants", verbose_name="Produktart"
)
color = models.ForeignKey(
Color, on_delete=models.PROTECT, related_name="variants", verbose_name="Farbe"
)
spool_type = models.CharField("Spulenausführung", max_length=10, choices=SpoolType.choices)
manufacturer_color_code = models.CharField("Hersteller-Farbcode", max_length=40, blank=True)
swatch = models.CharField(
"Farbvorschau",
max_length=15,
blank=True,
validators=[
RegexValidator(
r"\A#[0-9A-Fa-f]{6}(,#[0-9A-Fa-f]{6})?\Z",
"Bitte einen oder zwei Hexwerte eingeben (z. B. #DE4343 oder #000000,#A34342).",
)
],
help_text="Ein Hexwert oder zwei durch ein Komma getrennte Hexwerte.",
)
image_url = models.URLField(
"Produktbild",
max_length=500,
blank=True,
validators=[
RegexValidator(
r"\Ahttps://(?:cdn\.shopify\.com/|store\.bblcdn\.eu/|store\.bblcdn\.com/"
r"|ueeshop\.ly200-cdn\.com/u_file/UPBB/UPBB609/)",
"Bitte eine HTTPS-Bildadresse von einer unterstützten CDN-Domain eingeben.",
)
],
help_text="HTTPS-Bildadresse aus dem CDN von Bambu Lab, SUNLU oder eSUN.",
)
net_weight_g = models.PositiveIntegerField(
"Nettogewicht (g)", null=True, blank=True, validators=[MinValueValidator(1)]
)
diameter_mm = models.DecimalField(
"Durchmesser (mm)",
max_digits=4,
decimal_places=2,
null=True,
blank=True,
validators=[MinValueValidator(0.01)],
)
is_active = models.BooleanField("Aktiv", default=True)
class Meta:
ordering = [
"product_type__manufacturer__name",
"product_type__name",
"color__name",
"spool_type",
]
constraints = [
models.UniqueConstraint(
fields=["product_type", "color", "spool_type"], name="unique_catalog_variant"
),
models.CheckConstraint(
condition=models.Q(spool_type__in=["spool", "refill"]), name="valid_spool_type"
),
models.CheckConstraint(
condition=models.Q(net_weight_g__isnull=True) | models.Q(net_weight_g__gt=0),
name="positive_net_weight",
),
models.CheckConstraint(
condition=models.Q(diameter_mm__isnull=True) | models.Q(diameter_mm__gt=0),
name="positive_diameter",
),
]
verbose_name = "Filamentvariante"
verbose_name_plural = "Filamentvarianten"
@property
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()}"
class QuantityPosition(models.Model):
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Person"
)
variant = models.ForeignKey(Variant, on_delete=models.PROTECT, verbose_name="Filamentvariante")
quantity = models.PositiveIntegerField(
"Stückzahl", validators=[MinValueValidator(1), MaxValueValidator(9999)]
)
class Meta:
abstract = True
ordering = [
"variant__product_type__manufacturer__name",
"variant__product_type__name",
"variant__color__name",
"variant__spool_type",
]
constraints = [
models.UniqueConstraint(fields=["owner", "variant"], name="%(class)s_owner_variant"),
models.CheckConstraint(
condition=models.Q(quantity__gte=1, quantity__lte=9999),
name="%(class)s_quantity_range",
),
]
def __str__(self):
return f"{self.quantity} × {self.variant}"
class InventoryItem(QuantityPosition):
"""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")],
)
bambu_spool = models.BooleanField("Bambu-Lab-Spule")
class Meta(QuantityPosition.Meta):
constraints = [
models.UniqueConstraint(
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):
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):
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 EmptySpool(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
bambu_spool = models.BooleanField("Bambu-Lab-Spule", default=True)
class Meta:
ordering = ["pk"]
verbose_name = "Leerrolle"
verbose_name_plural = "Leerrollen"
@property
def brand_name(self):
return "Bambu Lab" if self.bambu_spool else "Andere Spule"
def __str__(self):
return f"Leerrolle #{self.pk} · {self.brand_name}"
class OrderItem(QuantityPosition):
class Status(models.TextChoices):
OPEN = "open", "Offen"
UNAVAILABLE = "unavailable", "Aktuell nicht verfügbar"
ORDERED = "ordered", "Bestellt"
ARRIVED = "arrived", "Eingetroffen"
HANDED_OVER = "handed_over", "Übergeben"
PENDING_STATUSES = (Status.OPEN, Status.UNAVAILABLE)
status = models.CharField("Bestellstatus", max_length=16, choices=Status, default=Status.OPEN)
ordered_at = models.DateTimeField("Bestellt am", null=True, blank=True)
handed_over_at = models.DateTimeField("Übergeben am", null=True, blank=True)
class Meta(QuantityPosition.Meta):
constraints = [
models.UniqueConstraint(
fields=["owner", "variant"],
condition=models.Q(status__in=["open", "unavailable"]),
name="orderitem_pending_owner_variant",
),
models.CheckConstraint(
condition=models.Q(quantity__gte=1, quantity__lte=9999),
name="orderitem_quantity_range",
),
models.CheckConstraint(
condition=models.Q(
status__in=["open", "unavailable", "ordered", "arrived", "handed_over"]
),
name="orderitem_valid_status",
),
]
@property
def is_pending(self):
return self.status in self.PENDING_STATUSES
class Printer(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
manufacturer = models.CharField("Hersteller", max_length=100)
model = models.CharField("Modell", max_length=100)
name = models.CharField("Name (optional)", max_length=100, blank=True)
class Meta:
ordering = ["manufacturer", "model", "name"]
def __str__(self):
base = f"{self.manufacturer} {self.model}"
return f"{base} · {self.name}" if self.name else base
class PrinterAddon(models.Model):
printer = models.ForeignKey(Printer, on_delete=models.CASCADE, related_name="addons")
name = models.CharField("Zubehör", max_length=100)
quantity = models.PositiveSmallIntegerField(
"Stückzahl", default=1, validators=[MinValueValidator(1), MaxValueValidator(9999)]
)
class Meta:
ordering = ["name", "pk"]
verbose_name = "Druckerzubehör"
verbose_name_plural = "Druckerzubehör"
def __str__(self):
return self.name
class PrinterNozzle(models.Model):
class HotendType(models.TextChoices):
CONVENTIONAL = "conventional", "Konventionell"
INDUCTION = "induction", "Induktiv (Vortek)"
printer = models.ForeignKey(Printer, on_delete=models.CASCADE, related_name="nozzles")
hotend_type = models.CharField("Hotend-Typ", max_length=12, choices=HotendType.choices)
diameter_mm = models.DecimalField(
"Düsendurchmesser (mm)",
max_digits=4,
decimal_places=2,
validators=[MinValueValidator(0.01)],
)
description = models.CharField("Ausführung (optional)", max_length=100, blank=True)
quantity = models.PositiveSmallIntegerField(
"Stückzahl", default=1, validators=[MinValueValidator(1), MaxValueValidator(9999)]
)
class Meta:
ordering = ["hotend_type", "diameter_mm", "description", "pk"]
verbose_name = "Düse"
verbose_name_plural = "Düsen"
def __str__(self):
return f"{self.get_hotend_type_display()} · {self.diameter_display} mm"
@property
def diameter_display(self):
return format(self.diameter_mm.normalize(), "f").replace(".", ",")
class SharingPreferences(models.Model):
owner = models.OneToOneField(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="sharing"
)
share_inventory = models.BooleanField("Bestand mit anderen teilen", default=False)
share_printers = models.BooleanField("Drucker mit anderen teilen", default=False)
class CatalogBootstrap(models.Model):
"""Internal marker: bundled starter catalogs are imported only once."""
key = models.CharField(max_length=100, unique=True)
applied_at = models.DateTimeField(auto_now_add=True)
class Feedback(models.Model):
sender = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Absender"
)
message = models.TextField("Nachricht", max_length=2000)
created_at = models.DateTimeField("Gesendet am", auto_now_add=True)
class Meta:
ordering = ["-created_at", "-pk"]
verbose_name = "Feedback"
verbose_name_plural = "Feedback"