service.py 52 KB

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