service.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. from datetime import datetime
  2. from decimal import Decimal
  3. from typing import Any, Optional
  4. from redis.asyncio import Redis
  5. from app.api.v1.module_system.auth.schema import AuthSchema
  6. from app.core.alipay import AlipayClient
  7. from app.core.exceptions import CustomException
  8. from app.core.logger import log
  9. from app.utils.snowflake import get_snowflake_id_str
  10. from app.plugin.module_payment.enterprise.crud import EnterpriseCRUD
  11. from .crud import AccountCRUD, TransferCRUD, DepositCRUD, WithdrawCRUD
  12. from .enums import (
  13. DepositStatusEnum,
  14. WithdrawStatusEnum,
  15. )
  16. from .schema import (
  17. AccountAuthorizeApplySchema,
  18. AccountAuthorizeApplyOutSchema,
  19. AccountCreateSchema,
  20. AccountDepositSchema,
  21. AccountDepositOutSchema,
  22. AccountOperationOutSchema,
  23. AccountQuerySchema,
  24. AccountTransferSchema,
  25. AccountTransferOutSchema,
  26. AccountWithdrawSchema,
  27. ReceiptApplySchema,
  28. TransferListOutSchema,
  29. TransferOutSchema,
  30. TenantTransferCreate,
  31. TenantTransferResponse,
  32. )
  33. from ..openapi.crud import OpenTransferCRUD
  34. def _parse_dt(val: str | None) -> datetime | None:
  35. """解析支付宝日期字符串"""
  36. if not val:
  37. return None
  38. for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d"):
  39. try:
  40. return datetime.strptime(val, fmt)
  41. except ValueError:
  42. continue
  43. return None
  44. class AccountService:
  45. """资金专户服务层"""
  46. @classmethod
  47. async def stat_transfer_amount_service(
  48. cls,
  49. auth: AuthSchema,
  50. tenant_id: Optional[int] = None,
  51. enterprise_id: Optional[str] = None,
  52. start_date: Optional[datetime] = None,
  53. end_date: Optional[datetime] = None,
  54. ) -> Decimal:
  55. """
  56. 统计转账金额(✅)
  57. 统计企业在指定时间范围内的转账总金额以及每天的转账金额。
  58. """
  59. crud = TransferCRUD(auth)
  60. return await crud.get_transfer_amount(
  61. tenant_id=tenant_id,
  62. enterprise_id=enterprise_id,
  63. start_date=start_date,
  64. end_date=end_date,
  65. )
  66. @classmethod
  67. async def authorize_apply_service(
  68. cls,
  69. auth: AuthSchema,
  70. data: AccountAuthorizeApplySchema
  71. ) -> AccountAuthorizeApplyOutSchema:
  72. """
  73. 申请转账授权签约(✅)
  74. 调用: alipay.commerce.ec.trans.authorize.apply
  75. """
  76. from alipay.aop.api.request.AlipayCommerceEcTransAuthorizeApplyRequest import (
  77. AlipayCommerceEcTransAuthorizeApplyRequest,
  78. )
  79. from alipay.aop.api.domain.AlipayCommerceEcTransAuthorizeApplyModel import (
  80. AlipayCommerceEcTransAuthorizeApplyModel,
  81. )
  82. from alipay.aop.api.response.AlipayCommerceEcTransAuthorizeApplyResponse import (
  83. AlipayCommerceEcTransAuthorizeApplyResponse,
  84. )
  85. model = AlipayCommerceEcTransAuthorizeApplyModel()
  86. model.enterprise_id = data.enterprise_id
  87. request = AlipayCommerceEcTransAuthorizeApplyRequest()
  88. request.biz_model = model
  89. client = AlipayClient.get_client()
  90. response = client.execute(request)
  91. if not response:
  92. raise CustomException(msg="申请转账授权失败: 无响应")
  93. result = AlipayCommerceEcTransAuthorizeApplyResponse()
  94. result.parse_response_content(response)
  95. if not result.is_success():
  96. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  97. raise CustomException(msg=f"申请转账授权失败: {result.msg}")
  98. return AccountAuthorizeApplyOutSchema(
  99. sign_url=result.sign_url,
  100. )
  101. @classmethod
  102. async def create_account_service(
  103. cls,
  104. auth: AuthSchema,
  105. data: AccountCreateSchema
  106. ) -> AccountOperationOutSchema:
  107. """
  108. 开通资金专户(✅)
  109. 调用: alipay.commerce.ec.trans.account.create
  110. """
  111. from alipay.aop.api.request.AlipayCommerceEcTransAccountCreateRequest import (
  112. AlipayCommerceEcTransAccountCreateRequest,
  113. )
  114. from alipay.aop.api.domain.AlipayCommerceEcTransAccountCreateModel import (
  115. AlipayCommerceEcTransAccountCreateModel,
  116. )
  117. from alipay.aop.api.response.AlipayCommerceEcTransAccountCreateResponse import (
  118. AlipayCommerceEcTransAccountCreateResponse,
  119. )
  120. model = AlipayCommerceEcTransAccountCreateModel()
  121. model.enterprise_id = data.enterprise_id
  122. # model.account_type = data.account_type or "ALL" # 收支全能户
  123. # model.scene = data.scene or "B2B_TRANS" # ToB转账场景
  124. model.account_type = "ALL"
  125. model.scene = "B2B_TRANS"
  126. request = AlipayCommerceEcTransAccountCreateRequest()
  127. request.biz_model = model
  128. client = AlipayClient.get_client()
  129. response = client.execute(request)
  130. if not response:
  131. raise CustomException(msg="开通资金专户失败: 无响应")
  132. result = AlipayCommerceEcTransAccountCreateResponse()
  133. result.parse_response_content(response)
  134. if not result.is_success():
  135. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  136. raise CustomException(msg=f"开通资金专户失败: {result.msg}")
  137. account_data = AccountCreateSchema(
  138. enterprise_id=model.enterprise_id,
  139. account_book_id=result.account_book_id,
  140. account_type=model.account_type,
  141. scene=model.scene,
  142. )
  143. if result.account_book_id:
  144. account_data.account_book_id = result.account_book_id
  145. await AccountCRUD(auth).create(account_data)
  146. return AccountOperationOutSchema(
  147. enterprise_id=account_data.enterprise_id,
  148. account_book_id=account_data.account_book_id,
  149. )
  150. @classmethod
  151. async def deposit_service(
  152. cls,
  153. auth: AuthSchema,
  154. data: AccountDepositSchema
  155. ) -> AccountDepositOutSchema:
  156. """
  157. 资金专户充值(✅)
  158. 调用: alipay.commerce.ec.trans.account.deposit
  159. """
  160. from alipay.aop.api.request.AlipayCommerceEcTransAccountDepositRequest import (
  161. AlipayCommerceEcTransAccountDepositRequest,
  162. )
  163. from alipay.aop.api.domain.AlipayCommerceEcTransAccountDepositModel import (
  164. AlipayCommerceEcTransAccountDepositModel,
  165. )
  166. from alipay.aop.api.response.AlipayCommerceEcTransAccountDepositResponse import (
  167. AlipayCommerceEcTransAccountDepositResponse,
  168. )
  169. model = AlipayCommerceEcTransAccountDepositModel()
  170. model.enterprise_id = data.enterprise_id
  171. model.account_book_id = data.account_book_id
  172. model.amount = str(data.amount)
  173. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  174. request = AlipayCommerceEcTransAccountDepositRequest()
  175. request.biz_model = model
  176. client = AlipayClient.get_client()
  177. response = client.execute(request)
  178. if not response:
  179. raise CustomException(msg="充值失败: 无响应")
  180. result = AlipayCommerceEcTransAccountDepositResponse()
  181. result.parse_response_content(response)
  182. if not result.is_success():
  183. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  184. raise CustomException(msg=f"充值失败: {result.msg}")
  185. deposit_crud = DepositCRUD(auth)
  186. deposit_data = {
  187. "enterprise_id": data.enterprise_id,
  188. "out_biz_no": model.out_biz_no,
  189. "account_book_id": data.account_book_id,
  190. "amount": data.amount,
  191. "url": result.url,
  192. "status": DepositStatusEnum.DEALING.value,
  193. "remark": data.remark,
  194. }
  195. await deposit_crud.create(deposit_data)
  196. return AccountDepositOutSchema(
  197. url=result.url,
  198. )
  199. @classmethod
  200. async def transfer_service(
  201. cls,
  202. auth: AuthSchema,
  203. data: AccountTransferSchema
  204. ) -> AccountTransferOutSchema:
  205. """
  206. 资金专户转账(✅)
  207. 调用: alipay.commerce.ec.trans.account.transfer
  208. """
  209. from alipay.aop.api.request.AlipayCommerceEcTransAccountTransferRequest import (
  210. AlipayCommerceEcTransAccountTransferRequest,
  211. )
  212. from alipay.aop.api.domain.AlipayCommerceEcTransAccountTransferModel import (
  213. AlipayCommerceEcTransAccountTransferModel,
  214. )
  215. from alipay.aop.api.response.AlipayCommerceEcTransAccountTransferResponse import (
  216. AlipayCommerceEcTransAccountTransferResponse,
  217. )
  218. from alipay.aop.api.domain.TransParticipant import (
  219. TransParticipant,
  220. )
  221. from alipay.aop.api.domain.BankCardExtInfoDTO import (
  222. BankCardExtInfoDTO,
  223. )
  224. # 检查资金专户是否存在
  225. account = await AccountCRUD(auth).get_by_account_book_id(data.account_book_id)
  226. if not account:
  227. raise CustomException(msg="资金账户不存在")
  228. if account.tenant_id != auth.tenant_id:
  229. raise CustomException(msg="无权限操作")
  230. if data.enterprise_id and account.enterprise_id != data.enterprise_id:
  231. raise CustomException(msg="参数错误")
  232. if not data.order_title and account.enterprise_id:
  233. enterprise = await EnterpriseCRUD(auth).get_by_enterprise_id(account.enterprise_id)
  234. if not enterprise:
  235. raise CustomException(msg="资金账户所属企业不存在")
  236. data.order_title = f"来自{enterprise.name}转账"
  237. model = AlipayCommerceEcTransAccountTransferModel()
  238. model.enterprise_id = account.enterprise_id
  239. model.account_book_id = account.account_book_id
  240. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  241. # 转账总金额,单位为元,精确到小数点后两位
  242. model.amount = str(data.amount)
  243. model.order_title = data.order_title
  244. payee_info = TransParticipant()
  245. payee_info.identity_type = data.payee_info.identity_type
  246. payee_info.name = data.payee_info.name
  247. payee_info.identity = data.payee_info.identity
  248. if data.payee_info.bankcard_ext_info:
  249. payee_info.bankcard_ext_info = BankCardExtInfoDTO.from_alipay_dict(
  250. data.payee_info.bankcard_ext_info.model_dump(exclude_none=True)
  251. )
  252. model.payee_info = payee_info
  253. request = AlipayCommerceEcTransAccountTransferRequest()
  254. request.biz_model = model
  255. client = AlipayClient.get_client()
  256. response = client.execute(request)
  257. if not response:
  258. raise CustomException(msg="转账失败: 无响应")
  259. result = AlipayCommerceEcTransAccountTransferResponse()
  260. result.parse_response_content(response)
  261. if not result.is_success():
  262. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  263. raise CustomException(msg=f"转账失败: {result.sub_msg or result.msg or result.code}")
  264. transfer_crud = TransferCRUD(auth)
  265. transfer_data = {
  266. "enterprise_id": model.enterprise_id,
  267. "out_biz_no": model.out_biz_no,
  268. "account_book_id": model.account_book_id,
  269. "amount": model.amount,
  270. "order_title": model.order_title,
  271. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  272. "status": result.status,
  273. "order_no": result.order_no,
  274. "fund_order_id": result.fund_order_id,
  275. }
  276. await transfer_crud.create(transfer_data)
  277. return AccountTransferOutSchema(
  278. status=result.status,
  279. order_no=result.order_no,
  280. fund_order_id=result.fund_order_id,
  281. out_biz_no=model.out_biz_no,
  282. )
  283. @classmethod
  284. async def tenant_transfer_service(
  285. cls,
  286. auth: AuthSchema,
  287. tenant_id: int,
  288. data: TenantTransferCreate,
  289. request_ip: str,
  290. api_key_id: int | None = None,
  291. ) -> TenantTransferResponse:
  292. """
  293. 租户API转账(通过API Key认证)
  294. 调用: alipay.commerce.ec.trans.account.transfer
  295. """
  296. from alipay.aop.api.request.AlipayCommerceEcTransAccountTransferRequest import (
  297. AlipayCommerceEcTransAccountTransferRequest,
  298. )
  299. from alipay.aop.api.domain.AlipayCommerceEcTransAccountTransferModel import (
  300. AlipayCommerceEcTransAccountTransferModel,
  301. )
  302. from alipay.aop.api.response.AlipayCommerceEcTransAccountTransferResponse import (
  303. AlipayCommerceEcTransAccountTransferResponse,
  304. )
  305. from alipay.aop.api.domain.TransParticipant import (
  306. TransParticipant,
  307. )
  308. from alipay.aop.api.domain.BankCardExtInfoDTO import (
  309. BankCardExtInfoDTO,
  310. )
  311. # 检查资金专户是否存在
  312. account = await AccountCRUD(auth).get_by_account_book_id(data.account_book_id)
  313. if not account:
  314. raise CustomException(msg="资金账户不存在")
  315. if account.tenant_id != tenant_id:
  316. raise CustomException(msg="无权限操作")
  317. if data.enterprise_id and account.enterprise_id != data.enterprise_id:
  318. raise CustomException(msg="参数错误")
  319. if not data.order_title and account.enterprise_id:
  320. enterprise = await EnterpriseCRUD(auth).get_by_enterprise_id(account.enterprise_id)
  321. if not enterprise:
  322. raise CustomException(msg="资金账户所属企业不存在")
  323. data.order_title = f"来自{enterprise.name}转账"
  324. model = AlipayCommerceEcTransAccountTransferModel()
  325. model.enterprise_id = account.enterprise_id
  326. model.account_book_id = account.account_book_id
  327. model.out_biz_no = get_snowflake_id_str(tenant_id)
  328. # 转账总金额,单位为元,精确到小数点后两位
  329. model.amount = str(data.amount)
  330. model.order_title = data.order_title
  331. payee_info = TransParticipant()
  332. payee_info.identity_type = data.payee_info.identity_type
  333. payee_info.name = data.payee_info.name
  334. payee_info.identity = data.payee_info.identity
  335. if data.payee_info.bankcard_ext_info:
  336. payee_info.bankcard_ext_info = BankCardExtInfoDTO.from_alipay_dict(
  337. data.payee_info.bankcard_ext_info.model_dump(exclude_none=True)
  338. )
  339. model.payee_info = payee_info
  340. request = AlipayCommerceEcTransAccountTransferRequest()
  341. request.biz_model = model
  342. client = AlipayClient.get_client()
  343. response = client.execute(request)
  344. if not response:
  345. raise CustomException(msg="转账失败: 无响应")
  346. result = AlipayCommerceEcTransAccountTransferResponse()
  347. result.parse_response_content(response)
  348. if not result.is_success():
  349. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  350. raise CustomException(msg=f"转账失败: {result.sub_msg or result.msg or result.code}")
  351. transfer_crud = TransferCRUD(auth)
  352. transfer_data = {
  353. "enterprise_id": model.enterprise_id,
  354. "out_biz_no": model.out_biz_no,
  355. "account_book_id": model.account_book_id,
  356. "amount": model.amount,
  357. "order_title": model.order_title,
  358. "payee_info": data.payee_info.model_dump() if data.payee_info else None,
  359. "status": result.status,
  360. "order_no": result.order_no,
  361. "fund_order_id": result.fund_order_id,
  362. }
  363. await transfer_crud.create(transfer_data)
  364. return TenantTransferResponse(
  365. status=result.status,
  366. order_no=result.order_no,
  367. fund_order_id=result.fund_order_id,
  368. )
  369. @classmethod
  370. async def withdraw_service(
  371. cls,
  372. auth: AuthSchema,
  373. data: AccountWithdrawSchema
  374. ) -> AccountOperationOutSchema:
  375. """
  376. 资金专户提现
  377. 调用: alipay.commerce.ec.trans.account.withdraw
  378. 接口文档: https://opendocs.alipay.com/pre-open/d651859b_alipay.commerce.ec.trans.account.withdraw
  379. 参数说明:
  380. - enterprise_id: 企业ID
  381. - account_book_id: 资金专户号
  382. - amount: 提现金额
  383. - out_biz_no: 商家侧订单号(唯一)
  384. """
  385. from alipay.aop.api.request.AlipayCommerceEcTransAccountWithdrawRequest import (
  386. AlipayCommerceEcTransAccountWithdrawRequest,
  387. )
  388. from alipay.aop.api.domain.AlipayCommerceEcTransAccountWithdrawModel import (
  389. AlipayCommerceEcTransAccountWithdrawModel,
  390. )
  391. from alipay.aop.api.response.AlipayCommerceEcTransAccountWithdrawResponse import (
  392. AlipayCommerceEcTransAccountWithdrawResponse,
  393. )
  394. crud = AccountCRUD(auth)
  395. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  396. if not enterprise:
  397. raise CustomException(msg="企业不存在")
  398. model = AlipayCommerceEcTransAccountWithdrawModel()
  399. model.enterprise_id = enterprise.enterprise_id
  400. model.account_book_id = data.account_book_id
  401. model.amount = str(data.amount)
  402. model.out_biz_no = get_snowflake_id_str(auth.tenant_id)
  403. request = AlipayCommerceEcTransAccountWithdrawRequest()
  404. request.biz_model = model
  405. client = AlipayClient.get_client()
  406. response = client.execute(request)
  407. if not response:
  408. raise CustomException(msg="提现失败: 无响应")
  409. result = AlipayCommerceEcTransAccountWithdrawResponse()
  410. result.parse_response_content(response)
  411. if not result.is_success():
  412. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  413. raise CustomException(msg=f"提现失败: {result.msg}")
  414. withdraw_crud = WithdrawCRUD(auth)
  415. withdraw_data = {
  416. "enterprise_id": data.enterprise_id,
  417. "out_biz_no": model.out_biz_no,
  418. "account_book_id": data.account_book_id,
  419. "amount": data.amount,
  420. # 专户提现到余额户是同步操作,要么执行成功,要么执行异常,
  421. # 出参status设计多余,遵循规范使用业务码区分成功与失败
  422. "status": WithdrawStatusEnum.SUCCESS.value,
  423. "order_no": result.order_no,
  424. }
  425. await withdraw_crud.create(withdraw_data)
  426. log.info(f"资金专户提现发起成功: 企业: {data.enterprise_id}, 金额: {data.amount}")
  427. return AccountOperationOutSchema(
  428. enterprise_id=data.enterprise_id,
  429. account_book_id=data.account_book_id,
  430. )
  431. @classmethod
  432. async def query_account_service(
  433. cls,
  434. auth: AuthSchema,
  435. data: AccountQuerySchema
  436. ) -> list[Any]:
  437. """
  438. 查询资金专户(调用支付宝接口)
  439. 调用: alipay.commerce.ec.trans.account.query
  440. """
  441. from alipay.aop.api.request.AlipayCommerceEcTransAccountQueryRequest import (
  442. AlipayCommerceEcTransAccountQueryRequest,
  443. )
  444. from alipay.aop.api.domain.AlipayCommerceEcTransAccountQueryModel import (
  445. AlipayCommerceEcTransAccountQueryModel,
  446. )
  447. from alipay.aop.api.response.AlipayCommerceEcTransAccountQueryResponse import (
  448. AlipayCommerceEcTransAccountQueryResponse,
  449. )
  450. from alipay.aop.api.domain.FundAccountApiDTO import (
  451. FundAccountApiDTO,
  452. )
  453. model = AlipayCommerceEcTransAccountQueryModel()
  454. model.enterprise_id = data.enterprise_id
  455. request = AlipayCommerceEcTransAccountQueryRequest()
  456. request.biz_model = model
  457. client = AlipayClient.get_client()
  458. response = client.execute(request)
  459. if not response:
  460. raise CustomException(msg="查询资金专户失败: 无响应")
  461. result = AlipayCommerceEcTransAccountQueryResponse()
  462. result.parse_response_content(response)
  463. if not result.is_success():
  464. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  465. raise CustomException(msg=f"查询资金专户失败: {result.msg}")
  466. collect = []
  467. for v in list(result.account_list or []):
  468. if not hasattr(v, "account_book_id"):
  469. continue
  470. if not hasattr(v, "scene") or v.scene != "B2B_TRANS":
  471. continue
  472. account = FundAccountApiDTO.to_alipay_dict(v)
  473. collect.append(account)
  474. return collect
  475. @classmethod
  476. async def transfer_detail_service(
  477. cls,
  478. auth: AuthSchema,
  479. out_biz_no: str
  480. ) -> TransferOutSchema:
  481. """
  482. 查询转账记录详情
  483. """
  484. crud = TransferCRUD(auth)
  485. transfer = await crud.get_by_out_biz_no(out_biz_no)
  486. if not transfer:
  487. raise CustomException(msg="转账记录不存在")
  488. transfer_result = TransferOutSchema.model_validate(transfer)
  489. # 查询三方订单号
  490. open_transfer_crud = OpenTransferCRUD(auth)
  491. open_transfer_data = await open_transfer_crud.get(out_biz_no=transfer.out_biz_no)
  492. if open_transfer_data:
  493. transfer_result.third_biz_no = open_transfer_data.third_biz_no
  494. return transfer_result
  495. @classmethod
  496. async def transfer_list_service(
  497. cls,
  498. auth: AuthSchema,
  499. page_no: int = 1,
  500. page_size: int = 20,
  501. search: dict | None = None,
  502. ) -> dict:
  503. """
  504. 查询转账记录列表
  505. """
  506. log.info(f"查询转账记录列表: {page_no}, {page_size}, {search}")
  507. crud = TransferCRUD(auth)
  508. offset = (page_no - 1) * page_size
  509. return await crud.page(
  510. offset=offset,
  511. limit=page_size,
  512. order_by=[{"id": "desc"}],
  513. search=search or {},
  514. out_schema=TransferListOutSchema,
  515. )
  516. @classmethod
  517. async def transfer_export_service(
  518. cls,
  519. auth: AuthSchema,
  520. start_time: str,
  521. end_time: str,
  522. enterprise_id: Optional[str] = None,
  523. ) -> bytes:
  524. """
  525. 导出转账记录报表为Excel文件
  526. """
  527. log.info(f"导出转账记录报表: {start_time} -> {end_time}")
  528. crud = TransferCRUD(auth)
  529. search = {
  530. "created_time__gte": start_time,
  531. "created_time__lte": end_time,
  532. }
  533. if enterprise_id:
  534. search["enterprise_id"] = enterprise_id
  535. records = await crud.list(
  536. search=search,
  537. order_by=[{"id": "desc"}],
  538. )
  539. from app.utils.excel_util import ExcelUtil
  540. status_map = {
  541. "DEALING": "处理中",
  542. "SUCCESS": "成功",
  543. "FAIL": "失败",
  544. "REFUND": "退票",
  545. }
  546. payee_type_map = {
  547. "ALIPAY_ACCOUNT": "支付宝账户",
  548. "BANK_CARD": "银行卡",
  549. }
  550. list_data = []
  551. for i, record in enumerate(records, start=1):
  552. payee_info = record.payee_info or {}
  553. list_data.append({
  554. "序号": i,
  555. "订单号": record.out_biz_no or "",
  556. "商户订单号": record.order_no or "",
  557. "金额(元)": str(record.amount or 0),
  558. "收款方姓名": payee_info.get("name", ""),
  559. "收款方类型": payee_type_map.get(payee_info.get("identity_type", ""), ""),
  560. "状态": status_map.get(record.status, record.status),
  561. "转账标题": record.order_title or "",
  562. "创建时间": record.created_time.strftime("%Y-%m-%d %H:%M:%S") if record.created_time else "",
  563. })
  564. mapping_dict = {
  565. "序号": "序号",
  566. "订单号": "订单号",
  567. "商户订单号": "商户订单号",
  568. "金额(元)": "金额(元)",
  569. "收款方姓名": "收款方姓名",
  570. "收款方类型": "收款方类型",
  571. "状态": "状态",
  572. "转账标题": "转账标题",
  573. "创建时间": "创建时间",
  574. }
  575. return ExcelUtil.export_list2excel(list_data, mapping_dict)
  576. @classmethod
  577. async def apply_receipt_service(
  578. cls,
  579. auth: AuthSchema,
  580. redis: Redis,
  581. data: ReceiptApplySchema,
  582. ) -> str:
  583. """
  584. 申请转账业务回单
  585. 调用: alipay.commerce.ec.trans.receipt.apply
  586. 参数:
  587. - enterprise_id: 企业ID
  588. - order_no: 支付宝转账单号
  589. 返回: file_id
  590. """
  591. from app.core.redis_crud import RedisCURD
  592. redis_crud = RedisCURD(redis)
  593. cache_key = f"receipt:{data.enterprise_id}:{data.order_no}"
  594. cached_file_id = await redis_crud.get(cache_key)
  595. if cached_file_id:
  596. log.info(f"使用缓存的 file_id: {cached_file_id}")
  597. return cached_file_id
  598. crud = EnterpriseCRUD(auth)
  599. enterprise = await crud.get_by_enterprise_id(data.enterprise_id)
  600. if not enterprise:
  601. raise CustomException(msg="企业不存在")
  602. from alipay.aop.api.request.AlipayCommerceEcTransReceiptApplyRequest import (
  603. AlipayCommerceEcTransReceiptApplyRequest,
  604. )
  605. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptApplyModel import (
  606. AlipayCommerceEcTransReceiptApplyModel,
  607. )
  608. from alipay.aop.api.response.AlipayCommerceEcTransReceiptApplyResponse import (
  609. AlipayCommerceEcTransReceiptApplyResponse,
  610. )
  611. model = AlipayCommerceEcTransReceiptApplyModel()
  612. model.enterprise_id = data.enterprise_id
  613. model.order_no = data.order_no
  614. request = AlipayCommerceEcTransReceiptApplyRequest()
  615. request.biz_model = model
  616. client = AlipayClient.get_client()
  617. response = client.execute(request)
  618. if not response:
  619. raise CustomException(msg="申请回单失败: 无响应")
  620. result = AlipayCommerceEcTransReceiptApplyResponse()
  621. result.parse_response_content(response)
  622. if not result.is_success():
  623. # 清除缓存
  624. await redis_crud.delete(cache_key)
  625. raise CustomException(msg=f"申请回单失败: {result.msg}")
  626. file_id = str(result.file_id)
  627. await redis_crud.set(cache_key, file_id, expire=172800)
  628. log.info(f"申请回单成功: order_no={data.order_no}, file_id={file_id}")
  629. return file_id
  630. @classmethod
  631. async def query_receipt_service(cls, enterprise_id: str, file_id: str) -> dict:
  632. """
  633. 查询回单状态
  634. 调用: alipay.commerce.ec.trans.receipt.query
  635. 参数:
  636. - file_id: 文件申请号
  637. 返回: {file_id, status, download_url, error_message}
  638. """
  639. from alipay.aop.api.request.AlipayCommerceEcTransReceiptQueryRequest import (
  640. AlipayCommerceEcTransReceiptQueryRequest,
  641. )
  642. from alipay.aop.api.response.AlipayCommerceEcTransReceiptQueryResponse import (
  643. AlipayCommerceEcTransReceiptQueryResponse,
  644. )
  645. from alipay.aop.api.domain.AlipayCommerceEcTransReceiptQueryModel import (
  646. AlipayCommerceEcTransReceiptQueryModel,
  647. )
  648. model = AlipayCommerceEcTransReceiptQueryModel()
  649. model.enterprise_id = enterprise_id
  650. model.file_id = file_id
  651. request = AlipayCommerceEcTransReceiptQueryRequest()
  652. request.biz_model = model
  653. client = AlipayClient.get_client()
  654. response = client.execute(request)
  655. if not response:
  656. raise CustomException(msg="查询回单失败: 无响应")
  657. result = AlipayCommerceEcTransReceiptQueryResponse()
  658. result.parse_response_content(response)
  659. if not result.is_success():
  660. raise CustomException(msg=f"查询回单失败: {result.msg}")
  661. data = {
  662. "file_id": file_id,
  663. "status": result.status,
  664. "download_url": result.download_url,
  665. "error_message": result.error_message,
  666. }
  667. return data
  668. @classmethod
  669. async def transfer_sync_status_service(
  670. cls,
  671. auth: AuthSchema,
  672. data: "TransferSyncStatusSchema",
  673. ) -> dict:
  674. """
  675. 手动同步转账状态(管理员补录)
  676. 用于修复因通知丢失而卡在 DEALING 的转账记录
  677. """
  678. from app.plugin.module_payment.account.crud import TransferCRUD
  679. from app.plugin.module_payment.account.schema import TransferSyncStatusSchema
  680. crud = TransferCRUD(auth)
  681. transfer = await crud.get_by_out_biz_no(data.out_biz_no)
  682. if not transfer:
  683. raise CustomException(msg=f"转账记录不存在: {data.out_biz_no}")
  684. if transfer.status != "DEALING" and data.status == "SUCCESS":
  685. raise CustomException(msg=f"转账记录当前状态为 {transfer.status},无需同步")
  686. update_data = {"status": data.status}
  687. if data.error_code:
  688. update_data["error_code"] = data.error_code
  689. if data.error_msg:
  690. update_data["error_msg"] = data.error_msg
  691. for key, value in update_data.items():
  692. if hasattr(transfer, key):
  693. setattr(transfer, key, value)
  694. await auth.db.flush()
  695. await auth.db.refresh(transfer)
  696. log.info(f"手动同步转账状态成功: out_biz_no={data.out_biz_no}, {transfer.status}")
  697. return {
  698. "out_biz_no": transfer.out_biz_no,
  699. "status": transfer.status,
  700. "error_code": transfer.error_code,
  701. "error_msg": transfer.error_msg,
  702. }
  703. @classmethod
  704. async def transfer_sync_all_service(
  705. cls,
  706. auth: AuthSchema,
  707. ) -> dict:
  708. """
  709. 全量同步转账状态
  710. 尝试调 fund.trans.common.query,如无权限则降级为列出 DEALING 记录供手动同步
  711. """
  712. from sqlalchemy import select
  713. from app.plugin.module_payment.account.model import TransferModel
  714. from app.plugin.module_payment.account.enums import TransferStatusEnum
  715. stmt = select(TransferModel).where(
  716. TransferModel.out_biz_no.isnot(None),
  717. ).order_by(TransferModel.id.asc())
  718. result = await auth.db.execute(stmt)
  719. all_transfers = result.scalars().all()
  720. synced = 0
  721. errors = 0
  722. details = []
  723. _has_permission = True
  724. for transfer in all_transfers:
  725. out_biz_no = transfer.out_biz_no
  726. eid = transfer.enterprise_id
  727. if not out_biz_no or not eid:
  728. continue
  729. try:
  730. result = await cls._sync_transfer_detail(auth, out_biz_no, eid)
  731. if result is False:
  732. # 两个方案都失败了(无权限),停止全量同步
  733. _has_permission = False
  734. break
  735. if isinstance(result, str):
  736. synced += 1
  737. details.append({"out_biz_no": out_biz_no, "old_status": transfer.status, "new_status": result})
  738. else:
  739. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "action": "no_change"})
  740. except Exception as e:
  741. errors += 1
  742. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "error": str(e)})
  743. log.warning(f"全量同步 - 查询失败: out_biz_no={out_biz_no}, err={e}")
  744. if not _has_permission:
  745. dealing = [t for t in all_transfers if t.status == TransferStatusEnum.DEALING.value]
  746. return {
  747. "total": len(all_transfers),
  748. "synced": synced,
  749. "no_permission": True,
  750. "dealing_count": len(dealing),
  751. "details": [{"out_biz_no": t.out_biz_no, "status": t.status} for t in dealing],
  752. "note": "无法通过支付宝 API 查询转账状态,请在开放平台开通 alipay.fund.trans.common.query 权限,或逐个使用 sync-status 手动补录",
  753. }
  754. if synced > 0:
  755. await auth.db.flush()
  756. return {
  757. "total": len(all_transfers),
  758. "synced": synced,
  759. "errors": errors,
  760. "details": details,
  761. }
  762. @classmethod
  763. async def _sync_transfer_detail(
  764. cls,
  765. auth: AuthSchema,
  766. out_biz_no: str,
  767. enterprise_id: str,
  768. ) -> str | bool | None:
  769. """查询单笔转账详情并更新本地记录
  770. 优先调 fund.trans.common.query,无权限时改用 consume.detail.query(用 order_no 当 pay_no 查)
  771. 返回: 新状态str / False(无权限) / None(失败/无变化)
  772. """
  773. from sqlalchemy import select, update as sa_update
  774. from app.plugin.module_payment.account.model import TransferModel
  775. from app.core.alipay import AlipayClient
  776. # 先查本地记录
  777. tf_stmt = select(TransferModel).where(TransferModel.out_biz_no == out_biz_no)
  778. tf_result = await auth.db.execute(tf_stmt)
  779. local_transfer = tf_result.scalar_one_or_none()
  780. # — 方案A: fund.trans.common.query —
  781. try:
  782. from alipay.aop.api.request.AlipayFundTransCommonQueryRequest import (
  783. AlipayFundTransCommonQueryRequest,
  784. )
  785. from alipay.aop.api.domain.AlipayFundTransCommonQueryModel import (
  786. AlipayFundTransCommonQueryModel,
  787. )
  788. from alipay.aop.api.response.AlipayFundTransCommonQueryResponse import (
  789. AlipayFundTransCommonQueryResponse,
  790. )
  791. model = AlipayFundTransCommonQueryModel()
  792. model.out_biz_no = out_biz_no
  793. model.product_code = "TRANS_ACCOUNT_NO_PWD"
  794. model.biz_scene = "DIRECT_TRANSFER"
  795. request = AlipayFundTransCommonQueryRequest()
  796. request.biz_model = model
  797. client = AlipayClient.get_client()
  798. response = client.execute(request)
  799. if response:
  800. result = AlipayFundTransCommonQueryResponse()
  801. result.parse_response_content(response)
  802. if result.is_success():
  803. alipay_status = getattr(result, 'status', None)
  804. if alipay_status and alipay_status != "DEALING":
  805. return await cls._apply_transfer_update(auth, out_biz_no, result, alipay_status)
  806. return None
  807. sub_msg = getattr(result, 'sub_msg', '') or ''
  808. if '权限' not in sub_msg and 'NO_PERMISSION' not in sub_msg:
  809. return None
  810. # 权限不足,继续方案B
  811. except ImportError:
  812. pass
  813. # — 方案B: consume.detail.query(用 order_no 当 pay_no 查) —
  814. order_no = local_transfer.order_no if local_transfer else None
  815. if not order_no:
  816. log.warning(f"无 order_no 可用于查询: out_biz_no={out_biz_no}")
  817. return False
  818. try:
  819. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  820. AlipayCommerceEcConsumeDetailQueryRequest,
  821. )
  822. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  823. AlipayCommerceEcConsumeDetailQueryModel,
  824. )
  825. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  826. AlipayCommerceEcConsumeDetailQueryResponse,
  827. )
  828. model = AlipayCommerceEcConsumeDetailQueryModel()
  829. model.pay_no = order_no
  830. model.enterprise_id = enterprise_id
  831. request = AlipayCommerceEcConsumeDetailQueryRequest()
  832. request.biz_model = model
  833. client = AlipayClient.get_client()
  834. response = client.execute(request)
  835. if not response:
  836. return False
  837. result = AlipayCommerceEcConsumeDetailQueryResponse()
  838. result.parse_response_content(response)
  839. if not result.is_success():
  840. sub_code = getattr(result, 'sub_code', '') or ''
  841. sub_msg = getattr(result, 'sub_msg', '') or ''
  842. # 权限不足
  843. if '权限' in sub_msg or 'NO_PERMISSION' in sub_code:
  844. return False
  845. log.warning(f"consume.detail.query 查无记录: out_biz_no={out_biz_no}, err={sub_msg}")
  846. return None
  847. consume_info = getattr(result, 'consume_info', None)
  848. if not consume_info:
  849. return None
  850. consume_type = getattr(consume_info, 'consume_type', '')
  851. if consume_type != "TRANSFER":
  852. return None
  853. notify_reason = getattr(consume_info, 'notify_reason', '') or ''
  854. if 'SUCCESS' in notify_reason.upper():
  855. new_status = "SUCCESS"
  856. elif 'FAIL' in notify_reason.upper():
  857. new_status = "FAIL"
  858. else:
  859. return None
  860. update_data = {"status": new_status}
  861. pay_no = getattr(consume_info, 'pay_no', None)
  862. if pay_no and pay_no != order_no:
  863. update_data["order_no"] = pay_no
  864. upd = sa_update(TransferModel).where(
  865. TransferModel.out_biz_no == out_biz_no
  866. ).values(**update_data)
  867. await auth.db.execute(upd)
  868. log.info(f"转账同步(consume详情) - out_biz_no={out_biz_no}, status={new_status}")
  869. return new_status
  870. except ImportError:
  871. log.warning("consume.detail.query SDK 不可用")
  872. return False
  873. except Exception as e:
  874. log.warning(f"consume.detail.query 异常: out_biz_no={out_biz_no}, err={e}")
  875. return False
  876. @classmethod
  877. async def _apply_transfer_update(
  878. cls,
  879. auth: AuthSchema,
  880. out_biz_no: str,
  881. result: object,
  882. alipay_status: str,
  883. ) -> str | None:
  884. """根据 fund.trans.common.query 结果更新本地记录"""
  885. from sqlalchemy import update as sa_update
  886. from app.plugin.module_payment.account.model import TransferModel
  887. update_data = {"status": alipay_status}
  888. order_no = getattr(result, 'order_id', None)
  889. pay_fund_order_id = getattr(result, 'pay_fund_order_id', None)
  890. trans_amount = getattr(result, 'trans_amount', None)
  891. error_code = getattr(result, 'error_code', None)
  892. fail_reason = getattr(result, 'fail_reason', None)
  893. if order_no:
  894. update_data["order_no"] = order_no
  895. if pay_fund_order_id:
  896. update_data["fund_order_id"] = pay_fund_order_id
  897. if trans_amount:
  898. update_data["amount"] = Decimal(str(trans_amount))
  899. if error_code:
  900. update_data["error_code"] = error_code
  901. if fail_reason:
  902. update_data["error_msg"] = fail_reason
  903. if update_data.get("status") != "DEALING":
  904. upd = sa_update(TransferModel).where(
  905. TransferModel.out_biz_no == out_biz_no
  906. ).values(**update_data)
  907. await auth.db.execute(upd)
  908. log.info(f"转账详情同步 - out_biz_no={out_biz_no}, status={alipay_status}")
  909. return alipay_status
  910. return None
  911. @classmethod
  912. async def update_transfer_status_service(
  913. cls,
  914. auth: AuthSchema,
  915. order_no: str,
  916. status: str,
  917. ext_info: dict = {}
  918. ) -> None:
  919. """
  920. 更新转账状态(由通知处理器调用)
  921. """
  922. crud = TransferCRUD(auth)
  923. transfer = await crud.get_by_order_no(order_no)
  924. if not transfer:
  925. log.warning(f"转账记录不存在: {order_no}")
  926. return
  927. update_data = {}
  928. update_data["status"] = status
  929. if ext_info:
  930. update_data["ext_info"] = ext_info
  931. await crud.update_by_order_no(order_no, update_data)
  932. @classmethod
  933. async def update_deposit_status_service(
  934. cls,
  935. auth: AuthSchema,
  936. out_biz_no: str,
  937. status: str,
  938. ) -> None:
  939. """
  940. 更新充值状态(由通知处理器调用)
  941. """
  942. crud = DepositCRUD(auth)
  943. deposit = await crud.get_by_out_biz_no(out_biz_no)
  944. if not deposit:
  945. log.warning(f"充值记录不存在: {out_biz_no}")
  946. return
  947. update_data = {"status": status}
  948. await crud.update_by_out_biz_no(out_biz_no, update_data)
  949. @classmethod
  950. async def update_withdraw_status_service(
  951. cls,
  952. auth: AuthSchema,
  953. out_biz_no: str,
  954. status: str,
  955. error_code: str | None = None,
  956. error_msg: str | None = None,
  957. ) -> None:
  958. """
  959. 更新提现状态(由通知处理器调用)
  960. """
  961. crud = WithdrawCRUD(auth)
  962. withdraw = await crud.get_by_out_biz_no(out_biz_no)
  963. if not withdraw:
  964. log.warning(f"提现记录不存在: {out_biz_no}")
  965. return
  966. update_data = {"status": status}
  967. if error_code:
  968. update_data["error_code"] = error_code
  969. if error_msg:
  970. update_data["error_msg"] = error_msg
  971. await crud.update_by_out_biz_no(out_biz_no, update_data)
  972. @classmethod
  973. async def consume_detail_query_service(
  974. cls,
  975. auth: AuthSchema,
  976. pay_no: str,
  977. enterprise_id: str | None = None,
  978. ant_shop_id: str | None = None,
  979. query_options: list[str] | None = None,
  980. ) -> dict:
  981. """
  982. 账单详情查询(✅)
  983. 调用: alipay.commerce.ec.consume.detail.query
  984. 用于查询企业码账单详情,支持查询关联退款、订单、票据等信息。
  985. """
  986. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  987. AlipayCommerceEcConsumeDetailQueryRequest,
  988. )
  989. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  990. AlipayCommerceEcConsumeDetailQueryModel,
  991. )
  992. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  993. AlipayCommerceEcConsumeDetailQueryResponse,
  994. )
  995. model = AlipayCommerceEcConsumeDetailQueryModel()
  996. model.pay_no = pay_no
  997. if enterprise_id:
  998. model.enterprise_id = enterprise_id
  999. if ant_shop_id:
  1000. model.ant_shop_id = ant_shop_id
  1001. if query_options:
  1002. model.query_options = query_options
  1003. request = AlipayCommerceEcConsumeDetailQueryRequest()
  1004. request.biz_model = model
  1005. client = AlipayClient.get_client()
  1006. response = client.execute(request)
  1007. if not response:
  1008. raise CustomException(msg="账单详情查询失败: 无响应")
  1009. result = AlipayCommerceEcConsumeDetailQueryResponse()
  1010. result.parse_response_content(response)
  1011. if not result.is_success():
  1012. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  1013. raise CustomException(msg=f"账单详情查询失败: {result.msg}")
  1014. consume_info = result.consume_info
  1015. if not consume_info:
  1016. raise CustomException(msg="账单详情查询失败: 无账单信息")
  1017. return {
  1018. "account_id": consume_info.account_id,
  1019. "pay_no": consume_info.pay_no,
  1020. "consume_type": consume_info.consume_type,
  1021. "gmt_biz_create": consume_info.gmt_biz_create,
  1022. "consume_biz_type": consume_info.consume_biz_type,
  1023. "consume_amount": consume_info.consume_amount,
  1024. "order_complete_label": consume_info.order_complete_label,
  1025. "refund_status": consume_info.refund_status,
  1026. "refund_amount": consume_info.refund_amount,
  1027. "peer_payer_card_name": consume_info.peer_payer_card_name,
  1028. "user_id": getattr(consume_info, 'user_id', None),
  1029. "open_id": getattr(consume_info, 'open_id', None),
  1030. "enterprise_id": consume_info.enterprise_id,
  1031. "employee_id": consume_info.employee_id,
  1032. "enterprise_name": getattr(consume_info, 'enterprise_name', None),
  1033. "employee_name": getattr(consume_info, 'employee_name', None),
  1034. "consume_scene_code": getattr(consume_info, 'consume_scene_code', None),
  1035. "consume_type_sub_category": getattr(consume_info, 'consume_type_sub_category', None),
  1036. "consume_title": getattr(consume_info, 'consume_title', None),
  1037. "gmt_pay": getattr(consume_info, 'gmt_pay', None),
  1038. "gmt_refund": getattr(consume_info, 'gmt_refund', None),
  1039. "pay_amount": getattr(consume_info, 'pay_amount', None),
  1040. "invoice_amount": getattr(consume_info, 'invoice_amount', None),
  1041. "peer_pay_amount": getattr(consume_info, 'peer_pay_amount', None),
  1042. "subsidy_amount": getattr(consume_info, 'subsidy_amount', None),
  1043. "ext_infos": getattr(consume_info, 'ext_infos', None),
  1044. }