crud.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 EnterpriseModel
  5. from .schema import EnterpriseCreateOrUpdateSchema
  6. class EnterpriseCRUD(CRUDBase[EnterpriseModel, EnterpriseCreateOrUpdateSchema, EnterpriseCreateOrUpdateSchema]):
  7. """企业 CRUD 操作"""
  8. def __init__(self, auth: AuthSchema) -> None:
  9. """
  10. 初始化企业数据层。
  11. 参数:
  12. - auth (AuthSchema): 认证信息模型(含 DB 会话等上下文)。
  13. 返回:
  14. - None
  15. """
  16. self.auth = auth
  17. super().__init__(model=EnterpriseModel, auth=auth)
  18. async def get_by_enterprise_id(
  19. self, enterprise_id: str
  20. ) -> EnterpriseModel | None:
  21. """
  22. 根据企业ID查询企业
  23. 参数:
  24. - enterprise_id (str): 企业ID
  25. 返回:
  26. - EnterpriseModel | None: 企业信息,如果不存在则为 None
  27. """
  28. return await self.get(enterprise_id=enterprise_id)
  29. async def get_by_account_id(
  30. self, account_id: str
  31. ) -> EnterpriseModel | None:
  32. """
  33. 根据支付宝账号 ID 查询企业
  34. 参数:
  35. - account_id (str): 支付宝账号 ID
  36. 返回:
  37. - EnterpriseModel | None: 企业信息,如果不存在则为 None
  38. """
  39. return await self.get(account_id=account_id)
  40. async def update_by_enterprise_id(
  41. self, enterprise_id: str, data: dict
  42. ) -> EnterpriseModel | None:
  43. """
  44. 根据企业ID更新企业
  45. 参数:
  46. - enterprise_id (str): 企业ID
  47. - data (dict): 更新字段字典
  48. 返回:
  49. - EnterpriseModel: 更新后的企业信息
  50. """
  51. obj = await self.get(enterprise_id=enterprise_id, preload=[])
  52. if not obj:
  53. raise CustomException(msg="更新失败!对象不存在")
  54. # 设置字段值(只检查一次current_user)
  55. if self.auth.user and hasattr(obj, "updated_id"):
  56. setattr(obj, "updated_id", self.auth.user.id)
  57. for key, value in data.items():
  58. if hasattr(obj, key):
  59. setattr(obj, key, value)
  60. await self.auth.db.flush()
  61. await self.auth.db.refresh(obj)
  62. # 权限二次确认:flush后再次验证对象仍在权限范围内
  63. # 防止并发修改导致的权限逃逸(如其他事务修改了created_id)
  64. # 验证时也不自动预加载关系
  65. verify_obj = await self.get(enterprise_id=enterprise_id, preload=[])
  66. if not verify_obj:
  67. # 对象已被删除或权限已失效
  68. raise CustomException(msg="更新失败!对象不存在或无权限访问")
  69. return obj