crud.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 ExpenseInstitutionModel
  5. from .schema import InstitutionCreateSchema, InstitutionUpdateSchema
  6. class InstitutionCRUD(
  7. CRUDBase[ExpenseInstitutionModel, InstitutionCreateSchema, InstitutionUpdateSchema]
  8. ):
  9. """费控制度 CRUD 操作"""
  10. def __init__(self, auth: AuthSchema) -> None:
  11. self.auth = auth
  12. super().__init__(model=ExpenseInstitutionModel, auth=auth)
  13. async def get_by_institution_id(
  14. self, institution_id: str
  15. ) -> ExpenseInstitutionModel | None:
  16. """根据费控规则ID查询费控制度"""
  17. return await self.get(institution_id=institution_id)
  18. async def update_by_institution_id(
  19. self, institution_id: str, data: dict
  20. ) -> ExpenseInstitutionModel | None:
  21. """根据费控规则ID更新费控制度"""
  22. obj = await self.get(institution_id=institution_id, preload=[])
  23. if not obj:
  24. raise CustomException(msg="更新失败!对象不存在")
  25. if self.auth.user and hasattr(obj, "updated_id"):
  26. setattr(obj, "updated_id", self.auth.user.id)
  27. for key, value in data.items():
  28. if hasattr(obj, key):
  29. setattr(obj, key, value)
  30. await self.auth.db.flush()
  31. await self.auth.db.refresh(obj)
  32. verify_obj = await self.get(institution_id=institution_id, preload=[])
  33. if not verify_obj:
  34. raise CustomException(msg="更新失败!对象不存在或无权限访问")
  35. return obj