person_service.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. """Person service for business logic operations."""
  2. from app import db
  3. from app.models.person import Person
  4. from app.utils.validators import is_valid_name
  5. class PersonService:
  6. """Service class for Person CRUD operations."""
  7. @staticmethod
  8. def create(name):
  9. """Create a new person.
  10. Args:
  11. name: Person's name
  12. Returns:
  13. Tuple of (person_dict, error_message)
  14. On success: (person_dict, None)
  15. On failure: (None, error_message)
  16. """
  17. if not is_valid_name(name):
  18. return None, "人员名称不能为空"
  19. person = Person(name=name.strip())
  20. db.session.add(person)
  21. db.session.commit()
  22. return person.to_dict(), None
  23. @staticmethod
  24. def get_all():
  25. """Get all persons.
  26. Returns:
  27. List of person dictionaries
  28. """
  29. persons = Person.query.order_by(Person.id).all()
  30. return [p.to_dict() for p in persons]
  31. @staticmethod
  32. def get_by_id(person_id):
  33. """Get a person by ID.
  34. Args:
  35. person_id: Person's ID
  36. Returns:
  37. Tuple of (person_dict, error_message)
  38. On success: (person_dict, None)
  39. On failure: (None, error_message)
  40. """
  41. person = db.session.get(Person, person_id)
  42. if not person:
  43. return None, f"未找到ID为 {person_id} 的人员"
  44. return person.to_dict(), None
  45. @staticmethod
  46. def update(person_id, name):
  47. """Update a person's name.
  48. Args:
  49. person_id: Person's ID
  50. name: New name
  51. Returns:
  52. Tuple of (person_dict, error_message)
  53. On success: (person_dict, None)
  54. On failure: (None, error_message)
  55. """
  56. if not is_valid_name(name):
  57. return None, "人员名称不能为空"
  58. person = db.session.get(Person, person_id)
  59. if not person:
  60. return None, f"未找到ID为 {person_id} 的人员"
  61. person.name = name.strip()
  62. db.session.commit()
  63. return person.to_dict(), None
  64. @staticmethod
  65. def delete(person_id):
  66. """Delete a person.
  67. Args:
  68. person_id: Person's ID
  69. Returns:
  70. Tuple of (success, error_message)
  71. On success: (True, None)
  72. On failure: (False, error_message)
  73. """
  74. person = db.session.get(Person, person_id)
  75. if not person:
  76. return False, f"未找到ID为 {person_id} 的人员"
  77. # Check if person has associated work records
  78. if person.work_records.count() > 0:
  79. return False, "无法删除已有工作记录的人员"
  80. db.session.delete(person)
  81. db.session.commit()
  82. return True, None