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

597 lines
21 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 decimal import Decimal
from functools import partial
from uuid import uuid4
from django.conf import settings
from django.core.validators import (
FileExtensionValidator,
MaxValueValidator,
MinValueValidator,
RegexValidator,
)
from django.db import models, transaction
from django.db.models.signals import post_delete, pre_delete
from django.dispatch import receiver
from django.utils.functional import cached_property
from .bambu_color_names import bambu_color_label
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
@property
def color_label(self):
if self.manufacturer.name.casefold() == "bambu lab":
return bambu_color_label(
self.product_type.name, self.manufacturer_color_code, self.color.name
)
return self.color.name
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_label} · {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)]
)
revision = models.UUIDField(default=uuid4, editable=False)
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}"
def save(self, *args, update_fields=None, **kwargs):
if not self._state.adding and (update_fields is None or update_fields):
self.revision = uuid4()
if update_fields is not None:
update_fields = {*update_fields, "revision"}
return super().save(*args, update_fields=update_fields, **kwargs)
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_label} · "
f"{self.get_spool_type_display()}"
)
return f"{description} (Bambu-Lab-Spule)" if self.bambu_spool else description
@property
def reorder_spool_note(self):
variant = self.reorder_variant
if variant and (variant.pk != self.variant_id or self.spool_type != variant.spool_type):
return f"Nachbestellung als {variant.get_spool_type_display()}."
return ""
@cached_property
def reorder_variant(self):
if self.variant.is_active:
return self.variant
return Variant.objects.filter(
product_type_id=self.variant.product_type_id,
color_id=self.variant.color_id,
is_active=True,
).first()
def __str__(self):
return f"{self.quantity} × {self.stock_description}"
@property
def available_quantity(self):
return self.quantity - self.reserved_quantity
class MarketplaceOffer(models.Model):
class Status(models.TextChoices):
OPEN = "open", "Angeboten"
TAKEN = "taken", "Übernommen"
WITHDRAWN = "withdrawn", "Zurückgezogen"
# SET_NULL keeps a buyer's purchase history when the seller account is deleted.
seller = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
related_name="marketplace_offers",
null=True,
)
buyer = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
related_name="marketplace_purchases",
null=True,
blank=True,
)
stock = models.ForeignKey(
InventoryItem, on_delete=models.SET_NULL, related_name="marketplace_offers", null=True
)
variant = models.ForeignKey(Variant, on_delete=models.PROTECT)
spool_type = models.CharField(
max_length=10, choices=InventoryItem._meta.get_field("spool_type").choices
)
bambu_spool = models.BooleanField()
quantity = models.PositiveSmallIntegerField(
"Anzahl Rollen", validators=[MinValueValidator(1), MaxValueValidator(9999)]
)
price = models.DecimalField(
"Preis pro Rolle (€)",
max_digits=4,
decimal_places=2,
default=Decimal("10.00"),
validators=[MinValueValidator(Decimal("9.00")), MaxValueValidator(Decimal("12.00"))],
)
status = models.CharField(max_length=10, choices=Status, default=Status.OPEN)
created_at = models.DateTimeField(auto_now_add=True)
completed_at = models.DateTimeField(null=True, blank=True)
class Meta:
ordering = ["-created_at", "-pk"]
constraints = [
models.CheckConstraint(
condition=models.Q(quantity__gte=1, quantity__lte=9999),
name="marketplace_quantity_range",
),
models.CheckConstraint(
condition=models.Q(price__gte=9, price__lte=12), name="marketplace_price_range"
),
models.CheckConstraint(
condition=models.Q(status__in=["open", "taken", "withdrawn"]),
name="marketplace_valid_status",
),
models.CheckConstraint(
condition=models.Q(spool_type__in=["spool", "refill"]),
name="marketplace_valid_spool",
),
models.CheckConstraint(
condition=models.Q(bambu_spool=False) | models.Q(spool_type="spool"),
name="marketplace_bambu_requires_spool",
),
models.CheckConstraint(
condition=~models.Q(seller=models.F("buyer")), name="marketplace_different_users"
),
]
verbose_name = "Marktplatzangebot"
verbose_name_plural = "Marktplatzangebote"
@property
def total_price(self):
return self.price * self.quantity
def __str__(self):
return f"{self.quantity} × {self.variant.product_type} · {self.variant.color_label}"
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 StockMovement(models.Model):
class Kind(models.TextChoices):
OPENING = "opening", "Startbestand"
ADDED = "added", "Hinzugefügt"
CONSUMED = "consumed", "Verbraucht"
HANDOVER = "handover", "Aus Sammelbestellung übernommen"
HANDOVER_UNDONE = "handover_undone", "Übergabe rückgängig gemacht"
ADJUSTED = "adjusted", "Stückzahl korrigiert"
REMOVED = "removed", "Aus Bestand entfernt"
SPOOLED = "spooled", "Spule zugeordnet oder gewechselt"
MARKETPLACE_IN = "marketplace_in", "Auf Marktplatz übernommen"
MARKETPLACE_OUT = "marketplace_out", "Auf Marktplatz abgegeben"
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
manufacturer = models.CharField(max_length=100)
product = models.CharField(max_length=100)
color = models.CharField(max_length=100)
article_number = models.CharField(max_length=40, blank=True)
spool_type = models.CharField(
max_length=10, choices=InventoryItem._meta.get_field("spool_type").choices
)
bambu_spool = models.BooleanField()
kind = models.CharField(max_length=16, choices=Kind)
quantity_change = models.SmallIntegerField()
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created_at", "-pk"]
indexes = [models.Index(fields=["owner", "-created_at", "-id"])]
verbose_name = "Bestandsbewegung"
verbose_name_plural = "Bestandsbewegungen"
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)
handover_previous_status = models.CharField(max_length=16, choices=Status, blank=True)
handover_stock = models.ForeignKey(
InventoryItem, on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
)
handover_stock_revision = models.UUIDField(null=True, editable=False)
handover_remainder = models.ForeignKey(
"self", on_delete=models.SET_NULL, null=True, blank=True, related_name="+"
)
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"
class SharedModel(models.Model):
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Hochgeladen von"
)
title = models.CharField("Titel", max_length=120)
description = models.TextField("Beschreibung", blank=True, max_length=1000)
file = models.FileField(
"Modelldatei",
upload_to="shared-models",
validators=[FileExtensionValidator(["stl", "3mf", "zip"])],
)
original_filename = models.CharField("Dateiname", max_length=255)
# NULL means the preview is still pending; an empty value means none could be made.
preview = models.BinaryField(null=True)
created_at = models.DateTimeField("Hochgeladen am", auto_now_add=True)
class Meta:
ordering = ["owner__username", "-created_at", "-pk"]
verbose_name = "Geteiltes Modell"
verbose_name_plural = "Geteilte Modelle"
def __str__(self):
return self.title
@receiver(post_delete, sender=SharedModel)
def delete_shared_model_file(sender, instance, using, **kwargs):
if instance.file:
transaction.on_commit(
partial(instance.file.storage.delete, instance.file.name), using=using, robust=True
)
class SlicerTip(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Verfasst von"
)
title = models.CharField("Titel", max_length=120)
text = models.TextField("Tipp", max_length=1000)
created_at = models.DateTimeField("Veröffentlicht am", auto_now_add=True)
class Meta:
ordering = ["-created_at", "-pk"]
verbose_name = "Slicer-Tipp"
verbose_name_plural = "Slicer-Tipps"
def __str__(self):
return self.title
@receiver(pre_delete, sender=settings.AUTH_USER_MODEL)
def delete_unfinished_marketplace_offers(sender, instance, **kwargs):
# Taken offers stay as the buyer's purchase history; everything else leaves with the seller.
MarketplaceOffer.objects.filter(seller=instance).exclude(
status=MarketplaceOffer.Status.TAKEN
).delete()