item.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """Item model for Work Statistics System."""
  2. from datetime import datetime, timezone
  3. from app import db
  4. class Item(db.Model):
  5. """Item model representing a work item with unit price.
  6. Attributes:
  7. id: Primary key, auto-incremented
  8. name: Item's name (required, unique)
  9. unit_price: Price per unit (required, positive float)
  10. supplier_id: Foreign key to supplier (optional)
  11. created_at: Timestamp when the record was created
  12. updated_at: Timestamp when the record was last updated
  13. """
  14. __tablename__ = 'items'
  15. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  16. name = db.Column(db.String(100), nullable=False, unique=True, index=True)
  17. unit_price = db.Column(db.Float, nullable=False)
  18. supplier_id = db.Column(db.Integer, db.ForeignKey('suppliers.id'), nullable=True)
  19. created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
  20. updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
  21. # Relationship to Supplier
  22. supplier = db.relationship('Supplier', backref=db.backref('items', lazy='dynamic'))
  23. def to_dict(self):
  24. """Convert model to dictionary for JSON serialization.
  25. Returns:
  26. Dictionary representation of the item
  27. """
  28. return {
  29. 'id': self.id,
  30. 'name': self.name,
  31. 'unit_price': self.unit_price,
  32. 'supplier_id': self.supplier_id,
  33. 'supplier_name': self.supplier.name if self.supplier else '',
  34. 'created_at': self.created_at.isoformat() if self.created_at else None,
  35. 'updated_at': self.updated_at.isoformat() if self.updated_at else None
  36. }
  37. def __repr__(self):
  38. return f'<Item {self.id}: {self.name} @ {self.unit_price}>'