service.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151
  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. 查出本地所有 pay_transfer.out_biz_no,逐个调用 fund.trans.common.query 查询支付宝状态并更新
  711. """
  712. from sqlalchemy import select, update as sa_update
  713. from app.plugin.module_payment.account.model import TransferModel
  714. from app.plugin.module_payment.account.enums import TransferStatusEnum
  715. # 直接查所有有 out_biz_no 的转账记录(绕过权限过滤)
  716. stmt = select(TransferModel).where(
  717. TransferModel.out_biz_no.isnot(None),
  718. ).order_by(TransferModel.id.asc())
  719. result = await auth.db.execute(stmt)
  720. all_transfers = result.scalars().all()
  721. synced = 0
  722. errors = 0
  723. details = []
  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:
  732. synced += 1
  733. details.append({"out_biz_no": out_biz_no, "old_status": transfer.status, "new_status": result})
  734. else:
  735. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "action": "no_change"})
  736. except Exception as e:
  737. errors += 1
  738. details.append({"out_biz_no": out_biz_no, "status": transfer.status, "error": str(e)})
  739. log.warning(f"全量同步 - 查询失败: out_biz_no={out_biz_no}, err={e}")
  740. if synced > 0:
  741. await auth.db.flush()
  742. return {
  743. "total": len(all_transfers),
  744. "synced": synced,
  745. "errors": errors,
  746. "details": details,
  747. }
  748. @classmethod
  749. async def _sync_transfer_detail(
  750. cls,
  751. auth: AuthSchema,
  752. out_biz_no: str,
  753. enterprise_id: str,
  754. ) -> str | None:
  755. """调用 fund.trans.common.query 查询单笔转账详情并更新本地记录,返回新状态"""
  756. from sqlalchemy import update as sa_update
  757. from app.plugin.module_payment.account.model import TransferModel
  758. from app.core.alipay import AlipayClient
  759. try:
  760. from alipay.aop.api.request.AlipayFundTransCommonQueryRequest import (
  761. AlipayFundTransCommonQueryRequest,
  762. )
  763. from alipay.aop.api.domain.AlipayFundTransCommonQueryModel import (
  764. AlipayFundTransCommonQueryModel,
  765. )
  766. from alipay.aop.api.response.AlipayFundTransCommonQueryResponse import (
  767. AlipayFundTransCommonQueryResponse,
  768. )
  769. except ImportError:
  770. return None
  771. model = AlipayFundTransCommonQueryModel()
  772. model.out_biz_no = out_biz_no
  773. model.product_code = "TRANS_ACCOUNT_NO_PWD"
  774. model.biz_scene = "DIRECT_TRANSFER"
  775. request = AlipayFundTransCommonQueryRequest()
  776. request.biz_model = model
  777. client = AlipayClient.get_client()
  778. response = client.execute(request)
  779. if not response:
  780. return None
  781. result = AlipayFundTransCommonQueryResponse()
  782. result.parse_response_content(response)
  783. if not result.is_success():
  784. return None
  785. alipay_status = getattr(result, 'status', None)
  786. if not alipay_status:
  787. return None
  788. update_data = {"status": alipay_status}
  789. order_no = getattr(result, 'order_id', None)
  790. pay_fund_order_id = getattr(result, 'pay_fund_order_id', None)
  791. trans_amount = getattr(result, 'trans_amount', None)
  792. error_code = getattr(result, 'error_code', None)
  793. fail_reason = getattr(result, 'fail_reason', None)
  794. pay_date = getattr(result, 'pay_date', None)
  795. if order_no:
  796. update_data["order_no"] = order_no
  797. if pay_fund_order_id:
  798. update_data["fund_order_id"] = pay_fund_order_id
  799. if trans_amount:
  800. update_data["amount"] = Decimal(str(trans_amount))
  801. if error_code:
  802. update_data["error_code"] = error_code
  803. if fail_reason:
  804. update_data["error_msg"] = fail_reason
  805. if pay_date:
  806. try:
  807. update_data["ext_info"] = {"pay_date": pay_date}
  808. except Exception:
  809. pass
  810. if update_data.get("status") != "DEALING":
  811. upd = sa_update(TransferModel).where(
  812. TransferModel.out_biz_no == out_biz_no
  813. ).values(**update_data)
  814. await auth.db.execute(upd)
  815. log.info(f"转账详情同步 - out_biz_no={out_biz_no}, status={alipay_status}")
  816. return alipay_status
  817. return None
  818. @classmethod
  819. async def update_transfer_status_service(
  820. cls,
  821. auth: AuthSchema,
  822. order_no: str,
  823. status: str,
  824. ext_info: dict = {}
  825. ) -> None:
  826. """
  827. 更新转账状态(由通知处理器调用)
  828. """
  829. crud = TransferCRUD(auth)
  830. transfer = await crud.get_by_order_no(order_no)
  831. if not transfer:
  832. log.warning(f"转账记录不存在: {order_no}")
  833. return
  834. update_data = {}
  835. update_data["status"] = status
  836. if ext_info:
  837. update_data["ext_info"] = ext_info
  838. await crud.update_by_order_no(order_no, update_data)
  839. @classmethod
  840. async def update_deposit_status_service(
  841. cls,
  842. auth: AuthSchema,
  843. out_biz_no: str,
  844. status: str,
  845. ) -> None:
  846. """
  847. 更新充值状态(由通知处理器调用)
  848. """
  849. crud = DepositCRUD(auth)
  850. deposit = await crud.get_by_out_biz_no(out_biz_no)
  851. if not deposit:
  852. log.warning(f"充值记录不存在: {out_biz_no}")
  853. return
  854. update_data = {"status": status}
  855. await crud.update_by_out_biz_no(out_biz_no, update_data)
  856. @classmethod
  857. async def update_withdraw_status_service(
  858. cls,
  859. auth: AuthSchema,
  860. out_biz_no: str,
  861. status: str,
  862. error_code: str | None = None,
  863. error_msg: str | None = None,
  864. ) -> None:
  865. """
  866. 更新提现状态(由通知处理器调用)
  867. """
  868. crud = WithdrawCRUD(auth)
  869. withdraw = await crud.get_by_out_biz_no(out_biz_no)
  870. if not withdraw:
  871. log.warning(f"提现记录不存在: {out_biz_no}")
  872. return
  873. update_data = {"status": status}
  874. if error_code:
  875. update_data["error_code"] = error_code
  876. if error_msg:
  877. update_data["error_msg"] = error_msg
  878. await crud.update_by_out_biz_no(out_biz_no, update_data)
  879. @classmethod
  880. async def consume_detail_query_service(
  881. cls,
  882. auth: AuthSchema,
  883. pay_no: str,
  884. enterprise_id: str | None = None,
  885. ant_shop_id: str | None = None,
  886. query_options: list[str] | None = None,
  887. ) -> dict:
  888. """
  889. 账单详情查询(✅)
  890. 调用: alipay.commerce.ec.consume.detail.query
  891. 用于查询企业码账单详情,支持查询关联退款、订单、票据等信息。
  892. """
  893. from alipay.aop.api.request.AlipayCommerceEcConsumeDetailQueryRequest import (
  894. AlipayCommerceEcConsumeDetailQueryRequest,
  895. )
  896. from alipay.aop.api.domain.AlipayCommerceEcConsumeDetailQueryModel import (
  897. AlipayCommerceEcConsumeDetailQueryModel,
  898. )
  899. from alipay.aop.api.response.AlipayCommerceEcConsumeDetailQueryResponse import (
  900. AlipayCommerceEcConsumeDetailQueryResponse,
  901. )
  902. model = AlipayCommerceEcConsumeDetailQueryModel()
  903. model.pay_no = pay_no
  904. if enterprise_id:
  905. model.enterprise_id = enterprise_id
  906. if ant_shop_id:
  907. model.ant_shop_id = ant_shop_id
  908. if query_options:
  909. model.query_options = query_options
  910. request = AlipayCommerceEcConsumeDetailQueryRequest()
  911. request.biz_model = model
  912. client = AlipayClient.get_client()
  913. response = client.execute(request)
  914. if not response:
  915. raise CustomException(msg="账单详情查询失败: 无响应")
  916. result = AlipayCommerceEcConsumeDetailQueryResponse()
  917. result.parse_response_content(response)
  918. if not result.is_success():
  919. log.error(f"支付宝接口调用失败: {result.code} - {result.msg}")
  920. raise CustomException(msg=f"账单详情查询失败: {result.msg}")
  921. consume_info = result.consume_info
  922. if not consume_info:
  923. raise CustomException(msg="账单详情查询失败: 无账单信息")
  924. return {
  925. "account_id": consume_info.account_id,
  926. "pay_no": consume_info.pay_no,
  927. "consume_type": consume_info.consume_type,
  928. "gmt_biz_create": consume_info.gmt_biz_create,
  929. "consume_biz_type": consume_info.consume_biz_type,
  930. "consume_amount": consume_info.consume_amount,
  931. "order_complete_label": consume_info.order_complete_label,
  932. "refund_status": consume_info.refund_status,
  933. "refund_amount": consume_info.refund_amount,
  934. "peer_payer_card_name": consume_info.peer_payer_card_name,
  935. "user_id": getattr(consume_info, 'user_id', None),
  936. "open_id": getattr(consume_info, 'open_id', None),
  937. "enterprise_id": consume_info.enterprise_id,
  938. "employee_id": consume_info.employee_id,
  939. "enterprise_name": getattr(consume_info, 'enterprise_name', None),
  940. "employee_name": getattr(consume_info, 'employee_name', None),
  941. "consume_scene_code": getattr(consume_info, 'consume_scene_code', None),
  942. "consume_type_sub_category": getattr(consume_info, 'consume_type_sub_category', None),
  943. "consume_title": getattr(consume_info, 'consume_title', None),
  944. "gmt_pay": getattr(consume_info, 'gmt_pay', None),
  945. "gmt_refund": getattr(consume_info, 'gmt_refund', None),
  946. "pay_amount": getattr(consume_info, 'pay_amount', None),
  947. "invoice_amount": getattr(consume_info, 'invoice_amount', None),
  948. "peer_pay_amount": getattr(consume_info, 'peer_pay_amount', None),
  949. "subsidy_amount": getattr(consume_info, 'subsidy_amount', None),
  950. "ext_infos": getattr(consume_info, 'ext_infos', None),
  951. }