import math from django.db import models from django.utils import timezone class Product(models.Model): code = models.CharField(max_length=50, unique=True) description = models.CharField(max_length=200) default_net_weight = models.FloatField(default=5.0) requires_dates = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['code'] def __str__(self): return f"{self.code} — {self.description}" class Order(models.Model): STATUS_CHOICES = [ ('pending', 'Pending'), ('printing', 'Printing'), ('done', 'Done'), ('cancelled', 'Cancelled'), ] product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='orders') batch_number = models.CharField(max_length=50) production_date = models.DateField(default=timezone.now, null=True, blank=True) next_control_date = models.DateField(null=True, blank=True) total_weight = models.FloatField(default=0) canister_weight = models.FloatField(default=5) canisters_per_box = models.PositiveIntegerField(default=4) # Label counts (set from weight on create; editable afterwards) canister_count = models.PositiveIntegerField(default=0) box_count = models.PositiveIntegerField(default=0) canister_pages = models.PositiveIntegerField(editable=False, default=0) box_pages = models.PositiveIntegerField(editable=False, default=0) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending') created_at = models.DateTimeField(auto_now_add=True) printed_at = models.DateTimeField(null=True, blank=True) class Meta: ordering = ['-created_at'] def __str__(self): return f"Order #{self.id} — {self.product.code} — {self.batch_number}" def apply_weight(self): """Derive canister/box counts from total_weight (create path).""" self.canister_count = math.ceil(self.total_weight / self.canister_weight) self.box_count = math.ceil(self.canister_count / self.canisters_per_box) def set_counts(self, canister_count=None, box_count=None): """Edit label counts; keep total_weight aligned with canisters.""" if canister_count is not None: self.canister_count = canister_count self.total_weight = canister_count * self.canister_weight if box_count is not None: self.box_count = box_count def save(self, *args, **kwargs): if not self.canister_count and self.total_weight and self.canister_weight: self.apply_weight() # Mixed sheets: canister + box labels share pages; total in canister_pages n = self.canister_count + self.box_count self.canister_pages = math.ceil(n / 4) if n else 0 self.box_pages = 0 super().save(*args, **kwargs)