work_record.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """WorkRecord model for Work Statistics System."""
  2. from datetime import datetime, timezone, date
  3. from app import db
  4. class WorkRecord(db.Model):
  5. """WorkRecord model representing a work entry for a person on a specific date.
  6. Attributes:
  7. id: Primary key, auto-incremented
  8. person_id: Foreign key to Person
  9. item_id: Foreign key to Item
  10. work_date: Date of the work
  11. quantity: Number of items produced (positive integer)
  12. created_at: Timestamp when the record was created
  13. updated_at: Timestamp when the record was last updated
  14. """
  15. __tablename__ = 'work_records'
  16. id = db.Column(db.Integer, primary_key=True, autoincrement=True)
  17. person_id = db.Column(db.Integer, db.ForeignKey('persons.id'), nullable=False)
  18. item_id = db.Column(db.Integer, db.ForeignKey('items.id'), nullable=False)
  19. work_date = db.Column(db.Date, nullable=False)
  20. quantity = db.Column(db.Integer, nullable=False)
  21. created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
  22. updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc), onupdate=lambda: datetime.now(timezone.utc))
  23. # Relationships
  24. person = db.relationship('Person', backref=db.backref('work_records', lazy='dynamic'))
  25. item = db.relationship('Item', backref=db.backref('work_records', lazy='dynamic'))
  26. @property
  27. def total_price(self):
  28. """Calculate total price as unit_price * quantity.
  29. Returns:
  30. Float representing the total price
  31. """
  32. if self.item:
  33. return self.item.unit_price * self.quantity
  34. return 0.0
  35. def to_dict(self):
  36. """Convert model to dictionary for JSON serialization.
  37. Returns:
  38. Dictionary representation of the work record
  39. """
  40. return {
  41. 'id': self.id,
  42. 'person_id': self.person_id,
  43. 'person_name': self.person.name if self.person else None,
  44. 'item_id': self.item_id,
  45. 'item_name': self.item.name if self.item else None,
  46. 'unit_price': self.item.unit_price if self.item else None,
  47. 'work_date': self.work_date.isoformat() if self.work_date else None,
  48. 'quantity': self.quantity,
  49. 'total_price': self.total_price,
  50. 'created_at': self.created_at.isoformat() if self.created_at else None,
  51. 'updated_at': self.updated_at.isoformat() if self.updated_at else None
  52. }
  53. def __repr__(self):
  54. return f'<WorkRecord {self.id}: Person {self.person_id}, Item {self.item_id}, Qty {self.quantity}>'