crud.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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: str,
  78. start_date: Optional[datetime] = None,
  79. end_date: Optional[datetime] = None,
  80. ) -> Decimal:
  81. conditions = [
  82. TransferModel.enterprise_id == enterprise_id,
  83. TransferModel.status == "SUCCESS",
  84. ]
  85. if start_date:
  86. conditions.append(TransferModel.created_time >= start_date)
  87. if end_date:
  88. conditions.append(TransferModel.created_time <= end_date)
  89. try:
  90. # 统计转时间范围内的转账总金额,字段amount
  91. sql = select(func.sum(TransferModel.amount).label("total_amount")).where(
  92. *conditions
  93. )
  94. sql = await self.filter_permissions(sql)
  95. result: Result = await self.auth.db.execute(sql)
  96. return result.scalars().first() or Decimal(0)
  97. except Exception as e:
  98. raise CustomException(msg=f"列表查询失败: {e!s}")
  99. class DepositCRUD(CRUDBase[DepositModel, AccountDepositSchema, AccountDepositSchema]):
  100. """充值记录 CRUD 操作"""
  101. def __init__(self, auth: AuthSchema) -> None:
  102. self.auth = auth
  103. super().__init__(model=DepositModel, auth=auth)
  104. async def get_by_out_biz_no(
  105. self, out_biz_no: str
  106. ) -> DepositModel | None:
  107. return await self.get(out_biz_no=out_biz_no)
  108. async def get_by_enterprise_id(
  109. self, enterprise_id: str
  110. ) -> DepositModel | None:
  111. return await self.get(enterprise_id=enterprise_id)
  112. async def update_by_out_biz_no(
  113. self, out_biz_no: str, data: dict
  114. ) -> DepositModel | None:
  115. obj = await self.get(out_biz_no=out_biz_no, preload=[])
  116. if not obj:
  117. raise CustomException(msg="充值记录不存在")
  118. if self.auth.user and hasattr(obj, "updated_id"):
  119. setattr(obj, "updated_id", self.auth.user.id)
  120. for key, value in data.items():
  121. if hasattr(obj, key):
  122. setattr(obj, key, value)
  123. await self.auth.db.flush()
  124. await self.auth.db.refresh(obj)
  125. return obj
  126. class WithdrawCRUD(CRUDBase[WithdrawModel, AccountWithdrawSchema, AccountWithdrawSchema]):
  127. """提现记录 CRUD 操作"""
  128. def __init__(self, auth: AuthSchema) -> None:
  129. self.auth = auth
  130. super().__init__(model=WithdrawModel, auth=auth)
  131. async def get_by_out_biz_no(
  132. self, out_biz_no: str
  133. ) -> WithdrawModel | None:
  134. return await self.get(out_biz_no=out_biz_no)
  135. async def update_by_out_biz_no(
  136. self, out_biz_no: str, data: dict
  137. ) -> WithdrawModel | None:
  138. obj = await self.get(out_biz_no=out_biz_no, preload=[])
  139. if not obj:
  140. raise CustomException(msg="提现记录不存在")
  141. if self.auth.user and hasattr(obj, "updated_id"):
  142. setattr(obj, "updated_id", self.auth.user.id)
  143. for key, value in data.items():
  144. if hasattr(obj, key):
  145. setattr(obj, key, value)
  146. await self.auth.db.flush()
  147. await self.auth.db.refresh(obj)
  148. return obj