crud.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from app.api.v1.module_system.auth.schema import AuthSchema
  2. from app.core.base_crud import CRUDBase
  3. from app.core.exceptions import CustomException
  4. from .model import DepartmentModel
  5. from .schema import DepartmentCreateSchema
  6. class DepartmentCRUD(CRUDBase[DepartmentModel, DepartmentCreateSchema, DepartmentCreateSchema]):
  7. """部门 CRUD 操作"""
  8. def __init__(self, auth: AuthSchema) -> None:
  9. self.auth = auth
  10. super().__init__(model=DepartmentModel, auth=auth)
  11. async def get_by_department_id(
  12. self, department_id: str
  13. ) -> DepartmentModel | None:
  14. """根据部门ID查询部门(业务主键)"""
  15. return await self.get(department_id=department_id)
  16. async def get_by_parent_id(
  17. self, parent_id: str | None
  18. ) -> list[DepartmentModel]:
  19. """根据父部门ID查询子部门列表"""
  20. if parent_id is None:
  21. return await self.get_all(parent_id=None)
  22. return await self.get_all(parent_id=parent_id)
  23. async def get_root_departments(self) -> list[DepartmentModel]:
  24. """获取根部门列表(parent_id为空的部门)"""
  25. return await self.get_all(parent_id=None)
  26. async def get_children(self, department_id: str) -> list[DepartmentModel]:
  27. """获取子部门列表"""
  28. return await self.get_all(parent_id=department_id)
  29. async def has_children(self, department_id: str) -> bool:
  30. """检查部门是否有子部门"""
  31. children = await self.get_children(department_id)
  32. return len(children) > 0
  33. async def update_by_department_id(
  34. self, department_id: str, data: dict
  35. ) -> DepartmentModel | None:
  36. """根据部门ID更新部门"""
  37. obj = await self.get(department_id=department_id, preload=[])
  38. if not obj:
  39. raise CustomException(msg="更新失败!对象不存在")
  40. if self.auth.user and hasattr(obj, "updated_id"):
  41. setattr(obj, "updated_id", self.auth.user.id)
  42. for key, value in data.items():
  43. if hasattr(obj, key):
  44. setattr(obj, key, value)
  45. await self.auth.db.flush()
  46. await self.auth.db.refresh(obj)
  47. verify_obj = await self.get(department_id=department_id, preload=[])
  48. if not verify_obj:
  49. raise CustomException(msg="更新失败!对象不存在或无权限访问")
  50. return obj