crud.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. from datetime import datetime
  2. from decimal import Decimal
  3. from sqlalchemy import func, select
  4. from app.api.v1.module_system.auth.schema import AuthSchema
  5. from app.core.base_crud import CRUDBase
  6. from app.core.exceptions import CustomException
  7. from typing import TYPE_CHECKING, Optional
  8. from .model import AccountModel, TransferModel, DepositModel, WithdrawModel
  9. from .schema import (
  10. AccountCreateSchema,
  11. AccountTransferSchema,
  12. AccountDepositSchema,
  13. AccountWithdrawSchema,
  14. )
  15. if TYPE_CHECKING:
  16. from sqlalchemy.engine import Result
  17. class AccountCRUD(CRUDBase[AccountModel, AccountCreateSchema, AccountCreateSchema]):
  18. """资金专户 CRUD 操作"""
  19. def __init__(self, auth: AuthSchema) -> None:
  20. self.auth = auth
  21. super().__init__(model=AccountModel, auth=auth)
  22. async def get_by_enterprise_id(
  23. self, enterprise_id: str
  24. ) -> AccountModel | None:
  25. return await self.get(enterprise_id=enterprise_id)
  26. async def get_by_account_book_id(
  27. self, account_book_id: str
  28. ) -> AccountModel | None:
  29. return await self.get(account_book_id=account_book_id)
  30. async def update_by_enterprise_id(
  31. self, enterprise_id: str, data: dict
  32. ) -> AccountModel | None:
  33. obj = await self.get(enterprise_id=enterprise_id, preload=[])
  34. if not obj:
  35. raise CustomException(msg="更新失败!对象不存在")
  36. if self.auth.user and hasattr(obj, "updated_id"):
  37. setattr(obj, "updated_id", self.auth.user.id)
  38. for key, value in data.items():
  39. if hasattr(obj, key):
  40. setattr(obj, key, value)
  41. await self.auth.db.flush()
  42. await self.auth.db.refresh(obj)
  43. verify_obj = await self.get(enterprise_id=enterprise_id, preload=[])
  44. if not verify_obj:
  45. raise CustomException(msg="更新失败!对象不存在或无权限访问")
  46. return obj
  47. class TransferCRUD(CRUDBase[TransferModel, AccountTransferSchema, AccountTransferSchema]):
  48. """转账记录 CRUD 操作"""
  49. def __init__(self, auth: AuthSchema) -> None:
  50. self.auth = auth
  51. super().__init__(model=TransferModel, auth=auth)
  52. async def get_by_out_biz_no(
  53. self, out_biz_no: str
  54. ) -> TransferModel | None:
  55. return await self.get(out_biz_no=out_biz_no)
  56. async def get_by_order_no(
  57. self, order_no: str
  58. ) -> TransferModel | None:
  59. return await self.get(order_no=order_no)
  60. async def update_by_order_no(
  61. self, order_no: str, data: dict
  62. ) -> TransferModel | None:
  63. obj = await self.get(order_no=order_no, preload=[])
  64. if not obj:
  65. raise CustomException(msg="转账记录不存在")
  66. if self.auth.user and hasattr(obj, "updated_id"):
  67. setattr(obj, "updated_id", self.auth.user.id)
  68. for key, value in data.items():
  69. if hasattr(obj, key):
  70. setattr(obj, key, value)
  71. await self.auth.db.flush()
  72. await self.auth.db.refresh(obj)
  73. return obj
  74. # 统计企业在指定时间范围内的转账总金额以及每天的转账金额。
  75. async def get_transfer_amount(
  76. self,
  77. enterprise_id: Optional[str] = None,
  78. start_date: Optional[datetime] = None,
  79. end_date: Optional[datetime] = None,
  80. tenant_id: Optional[int] = None,
  81. ) -> Decimal:
  82. conditions = [
  83. TransferModel.status == "SUCCESS",
  84. ]
  85. if tenant_id:
  86. conditions.append(TransferModel.tenant_id == tenant_id)
  87. if enterprise_id:
  88. conditions.append(TransferModel.enterprise_id == enterprise_id)
  89. if start_date:
  90. conditions.append(TransferModel.created_time >= start_date)
  91. if end_date:
  92. conditions.append(TransferModel.created_time <= end_date)
  93. try:
  94. # 统计转时间范围内的转账总金额,字段amount
  95. sql = select(func.sum(TransferModel.amount).label("total_amount")).where(
  96. *conditions
  97. )
  98. sql = await self.filter_permissions(sql)
  99. result: Result = await self.auth.db.execute(sql)
  100. return result.scalars().first() or Decimal(0)
  101. except Exception as e:
  102. raise CustomException(msg=f"列表查询失败: {e!s}")
  103. class DepositCRUD(CRUDBase[DepositModel, AccountDepositSchema, AccountDepositSchema]):
  104. """充值记录 CRUD 操作"""
  105. def __init__(self, auth: AuthSchema) -> None:
  106. self.auth = auth
  107. super().__init__(model=DepositModel, auth=auth)
  108. async def get_by_out_biz_no(
  109. self, out_biz_no: str
  110. ) -> DepositModel | None:
  111. return await self.get(out_biz_no=out_biz_no)
  112. async def get_by_enterprise_id(
  113. self, enterprise_id: str
  114. ) -> DepositModel | None:
  115. return await self.get(enterprise_id=enterprise_id)
  116. async def update_by_out_biz_no(
  117. self, out_biz_no: str, data: dict
  118. ) -> DepositModel | None:
  119. obj = await self.get(out_biz_no=out_biz_no, preload=[])
  120. if not obj:
  121. raise CustomException(msg="充值记录不存在")
  122. if self.auth.user and hasattr(obj, "updated_id"):
  123. setattr(obj, "updated_id", self.auth.user.id)
  124. for key, value in data.items():
  125. if hasattr(obj, key):
  126. setattr(obj, key, value)
  127. await self.auth.db.flush()
  128. await self.auth.db.refresh(obj)
  129. return obj
  130. class WithdrawCRUD(CRUDBase[WithdrawModel, AccountWithdrawSchema, AccountWithdrawSchema]):
  131. """提现记录 CRUD 操作"""
  132. def __init__(self, auth: AuthSchema) -> None:
  133. self.auth = auth
  134. super().__init__(model=WithdrawModel, auth=auth)
  135. async def get_by_out_biz_no(
  136. self, out_biz_no: str
  137. ) -> WithdrawModel | None:
  138. return await self.get(out_biz_no=out_biz_no)
  139. async def update_by_out_biz_no(
  140. self, out_biz_no: str, data: dict
  141. ) -> WithdrawModel | None:
  142. obj = await self.get(out_biz_no=out_biz_no, preload=[])
  143. if not obj:
  144. raise CustomException(msg="提现记录不存在")
  145. if self.auth.user and hasattr(obj, "updated_id"):
  146. setattr(obj, "updated_id", self.auth.user.id)
  147. for key, value in data.items():
  148. if hasattr(obj, key):
  149. setattr(obj, key, value)
  150. await self.auth.db.flush()
  151. await self.auth.db.refresh(obj)
  152. return obj