controller.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. from typing import Annotated
  2. import uuid
  3. from fastapi import APIRouter, Depends, Path, Query
  4. from fastapi.responses import JSONResponse
  5. from app.api.v1.module_system.auth.schema import AuthSchema
  6. from app.common.response import ResponseSchema, SuccessResponse
  7. from app.core.dependencies import AuthPermission
  8. from app.core.logger import log
  9. from app.core.router_class import OperationLogRoute
  10. from app.plugin.module_payment.expense.institution.schema import InstitutionListOutSchema
  11. from .service import InstitutionService, InstitutionScopeService, IssueruleService
  12. from alipay.aop.api.domain.AlipayEbppInvoiceInstitutionCreateModel import (
  13. AlipayEbppInvoiceInstitutionCreateModel,
  14. )
  15. from alipay.aop.api.response.AlipayEbppInvoiceInstitutionCreateResponse import (
  16. AlipayEbppInvoiceInstitutionCreateResponse,
  17. )
  18. from alipay.aop.api.domain.AlipayEbppInvoiceInstitutionDeleteModel import (
  19. AlipayEbppInvoiceInstitutionDeleteModel,
  20. )
  21. from alipay.aop.api.response.AlipayEbppInvoiceInstitutionDeleteResponse import (
  22. AlipayEbppInvoiceInstitutionDeleteResponse,
  23. )
  24. from alipay.aop.api.domain.AlipayEbppInvoiceInstitutionModifyModel import (
  25. AlipayEbppInvoiceInstitutionModifyModel,
  26. )
  27. from alipay.aop.api.response.AlipayEbppInvoiceInstitutionModifyResponse import (
  28. AlipayEbppInvoiceInstitutionModifyResponse,
  29. )
  30. InstitutionRouter = APIRouter(
  31. route_class=OperationLogRoute,
  32. prefix="/institution",
  33. tags=["费控制度"],
  34. )
  35. @InstitutionRouter.post(
  36. "",
  37. summary="创建费控制度",
  38. description="创建费控制度。支持串联调用:创建制度→设置成员→创建发放规则",
  39. )
  40. async def create_institution_controller(
  41. data: dict,
  42. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:create"]))],
  43. ) -> JSONResponse:
  44. """创建费控制度(含完整串联流程)"""
  45. institution_create_model = AlipayEbppInvoiceInstitutionCreateModel.from_alipay_dict(data)
  46. enterprise_id = data.get("enterprise_id", "")
  47. if not enterprise_id:
  48. from app.plugin.module_payment.enterprise.model import EnterpriseModel
  49. from sqlalchemy import select
  50. stmt = select(EnterpriseModel).where(EnterpriseModel.tenant_id == auth.tenant_id).limit(1)
  51. result = await auth.db.execute(stmt)
  52. enterprise = result.scalar_one_or_none()
  53. enterprise_id = enterprise.enterprise_id if enterprise else ""
  54. # 解析适用成员数据
  55. scope_data = None
  56. adapter_type = data.get("applicable_scope")
  57. if adapter_type and adapter_type != "NONE":
  58. scope_data = {
  59. "adapter_type": adapter_type,
  60. "owner_type": data.get("scope_owner_type", "EMPLOYEE"),
  61. "add_owner_id_list": data.get("scope_owner_id_list"),
  62. }
  63. # 解析发放规则数据
  64. issuerule_data = None
  65. if data.get("grant_mode") == "period":
  66. period_type_raw = data.get("period_type", "monthly")
  67. # 映射前端period_type到支付宝枚举
  68. ISSUE_TYPE_MAP = {
  69. "daily": "ISSUE_DAY",
  70. "weekly": "ISSUE_WEEK",
  71. "monthly": "ISSUE_MONTH",
  72. "quarterly": "ISSUE_QUARTER",
  73. "yearly": "ISSUE_YEAR",
  74. }
  75. issue_type = ISSUE_TYPE_MAP.get(period_type_raw, "ISSUE_MONTH")
  76. amount = data.get("amount", 0)
  77. # 有效时间配置
  78. effective_time_type = data.get("effective_time_type", "unlimited")
  79. if effective_time_type == "unlimited":
  80. effective_period = '{"all": true}'
  81. elif effective_time_type == "workday":
  82. workday_start = data.get("workday_start_time", "00:00")
  83. workday_end = data.get("workday_end_time", "23:59")
  84. effective_period = f'{{"regular":{{"workday":[["{workday_start}","{workday_end}"]]}}}}'
  85. else:
  86. effective_period = '{"all": true}'
  87. issuerule_data = {
  88. "quota_type": "CAP",
  89. "issue_type": issue_type,
  90. "issue_amount_value": str(amount),
  91. "issue_rule_name": data.get("name", "") + "-发放规则",
  92. "effective_period": effective_period,
  93. "invalid_mode": 1 if data.get("effective_time_type") == "unlimited" else 0,
  94. "share_mode": 0,
  95. "outer_source_id": data.get("outer_source_id") or str(uuid.uuid4()),
  96. }
  97. result = await InstitutionService.create_institution_full_flow(
  98. auth=auth,
  99. institution_model=institution_create_model,
  100. enterprise_id=enterprise_id,
  101. scope_data=scope_data,
  102. issuerule_data=issuerule_data,
  103. )
  104. log.info(f"创建费控制度成功: institution_id={result.get('institution_id')}")
  105. return SuccessResponse(data=result, msg="创建费控制度成功")
  106. @InstitutionRouter.get(
  107. "",
  108. summary="查询费控制度列表",
  109. description="分页查询费控制度列表",
  110. response_model=ResponseSchema[InstitutionListOutSchema],
  111. )
  112. async def list_institution_controller(
  113. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:list"]))],
  114. page_no: Annotated[int, Query(description="页码")] = 1,
  115. page_size: Annotated[int, Query(description="每页数量")] = 20,
  116. enterprise_id: Annotated[str | None, Query(description="企业ID")] = None,
  117. name: Annotated[str | None, Query(description="制度名称")] = None,
  118. expense_type: Annotated[str | None, Query(description="费用类型")] = None,
  119. status: Annotated[str | None, Query(description="状态")] = None,
  120. ) -> JSONResponse:
  121. """查询费控制度列表"""
  122. search = {}
  123. if enterprise_id:
  124. search["enterprise_id"] = enterprise_id
  125. if name:
  126. search["name"] = name
  127. if expense_type:
  128. search["expense_type"] = expense_type
  129. if status:
  130. search["status"] = status
  131. result = await InstitutionService.list_service(
  132. auth=auth, page_no=page_no, page_size=page_size, search=search
  133. )
  134. return SuccessResponse(data=result, msg="查询费控制度列表成功")
  135. @InstitutionRouter.get(
  136. "/{institution_id}",
  137. summary="查询费控制度详情",
  138. description="查询费控制度详情 (alipay.ebpp.invoice.institution.detailinfo.query),失败时降级到本地DB",
  139. )
  140. async def detail_institution_controller(
  141. institution_id: Annotated[str, Path(description="制度ID")],
  142. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:detail"]))],
  143. enterprise_id: Annotated[str | None, Query(description="企业ID")] = None,
  144. ) -> JSONResponse:
  145. """查询费控制度详情"""
  146. if not enterprise_id:
  147. return SuccessResponse(data=None, msg="企业ID不能为空")
  148. result = await InstitutionService.detailinfo_query_service(
  149. auth=auth,
  150. institution_id=institution_id,
  151. enterprise_id=enterprise_id,
  152. )
  153. if result is None:
  154. return SuccessResponse(data=None, msg="制度不存在")
  155. return SuccessResponse(data=result, msg="查询费控制度详情成功")
  156. @InstitutionRouter.delete(
  157. "",
  158. summary="删除费控制度",
  159. description="删除费控制度 (alipay.ebpp.invoice.institution.delete)",
  160. )
  161. async def delete_institution_controller(
  162. data: dict,
  163. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:delete"]))],
  164. ) -> JSONResponse:
  165. """删除费控制度"""
  166. institution_delete_model = AlipayEbppInvoiceInstitutionDeleteModel(**data)
  167. result = await InstitutionService.delete_institution_service(auth=auth, data=institution_delete_model)
  168. log.info(f"删除费控制度成功: institution_id={institution_delete_model.institution_id}, enterprise_id={institution_delete_model.enterprise_id}")
  169. return SuccessResponse(data=result, msg="删除费控制度成功")
  170. @InstitutionRouter.post(
  171. "/modify",
  172. summary="编辑费控制度",
  173. description="编辑费控制度 (alipay.ebpp.invoice.institution.modify)",
  174. )
  175. async def modify_institution_controller(
  176. data: dict,
  177. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:modify"]))],
  178. ) -> JSONResponse:
  179. """编辑费控制度"""
  180. institution_modify_model = AlipayEbppInvoiceInstitutionModifyModel(**data)
  181. result = await InstitutionService.modify_institution_service(auth=auth, data=institution_modify_model)
  182. log.info(f"编辑费控制度成功: institution_id={institution_modify_model.institution_id}")
  183. return SuccessResponse(data=result, msg="编辑费控制度成功")
  184. # ========== 制度成员范围管理 ==========
  185. @InstitutionRouter.get(
  186. "/{institution_id}/scope",
  187. summary="查询制度成员范围",
  188. description="查询制度下成员范围 (alipay.ebpp.invoice.institution.scopepageinfo.query)",
  189. )
  190. async def list_scope_controller(
  191. institution_id: Annotated[str, Path(description="制度ID")],
  192. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:scope:list"]))],
  193. enterprise_id: Annotated[str | None, Query(description="企业ID")] = None,
  194. owner_type: Annotated[str | None, Query(description="适配ID类型")] = None,
  195. page_num: Annotated[int, Query(description="页码")] = 1,
  196. page_size: Annotated[int, Query(description="每页条数")] = 20,
  197. ) -> JSONResponse:
  198. """查询制度成员"""
  199. result = await InstitutionScopeService.scopepageinfo_query_service(
  200. auth=auth,
  201. institution_id=institution_id,
  202. enterprise_id=enterprise_id,
  203. page_num=page_num,
  204. page_size=page_size,
  205. owner_type=owner_type,
  206. )
  207. return SuccessResponse(data=result, msg="查询成功")
  208. @InstitutionRouter.post(
  209. "/{institution_id}/scope",
  210. summary="设置制度成员范围",
  211. description="设置/修改制度成员范围 (alipay.ebpp.invoice.institution.scope.modify)",
  212. )
  213. async def modify_scope_controller(
  214. institution_id: Annotated[str, Path(description="制度ID")],
  215. data: dict,
  216. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:scope:modify"]))],
  217. ) -> JSONResponse:
  218. """设置制度成员"""
  219. result = await InstitutionScopeService.scope_modify_service(
  220. auth=auth,
  221. institution_id=institution_id,
  222. data=data,
  223. )
  224. log.info(f"设置制度成员成功: institution_id={institution_id}, adapter_type={data.get('adapter_type')}")
  225. return SuccessResponse(data=result, msg="设置成功")
  226. # ========== 自动额度发放规则管理 ==========
  227. @InstitutionRouter.post(
  228. "/{institution_id}/issuerule",
  229. summary="创建自动发放规则",
  230. description="创建自动额度发放规则 (alipay.ebpp.invoice.issuerule.create)",
  231. )
  232. async def create_issuerule_controller(
  233. institution_id: Annotated[str, Path(description="制度ID")],
  234. data: dict,
  235. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:issuerule:create"]))],
  236. ) -> JSONResponse:
  237. """创建自动发放规则"""
  238. result = await IssueruleService.create_issuerule_service(
  239. auth=auth,
  240. institution_id=institution_id,
  241. enterprise_id=data.get("enterprise_id", ""),
  242. quota_type=data.get("quota_type", "CAP"),
  243. issue_type=data.get("issue_type", "ISSUE_MONTH"),
  244. issue_amount_value=data.get("issue_amount_value", "0"),
  245. outer_source_id=data.get("outer_source_id"),
  246. issue_rule_name=data.get("issue_rule_name"),
  247. effective_period=data.get("effective_period"),
  248. invalid_mode=data.get("invalid_mode"),
  249. share_mode=data.get("share_mode"),
  250. )
  251. log.info(f"创建自动发放规则成功: institution_id={institution_id}")
  252. return SuccessResponse(data=result, msg="创建自动发放规则成功")
  253. @InstitutionRouter.put(
  254. "/{institution_id}/issuerule/{issue_rule_id}",
  255. summary="编辑自动发放规则",
  256. description="编辑自动额度发放规则 (alipay.ebpp.invoice.issuerule.modify)",
  257. )
  258. async def modify_issuerule_controller(
  259. institution_id: Annotated[str, Path(description="制度ID")],
  260. issue_rule_id: Annotated[str, Path(description="发放规则ID")],
  261. data: dict,
  262. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:issuerule:modify"]))],
  263. ) -> JSONResponse:
  264. result = await IssueruleService.modify_issuerule_service(
  265. auth=auth,
  266. institution_id=institution_id,
  267. issue_rule_id=issue_rule_id,
  268. enterprise_id=data.get("enterprise_id", ""),
  269. quota_type=data.get("quota_type"),
  270. issue_type=data.get("issue_type"),
  271. issue_amount_value=data.get("issue_amount_value"),
  272. issue_rule_name=data.get("issue_rule_name"),
  273. effective=data.get("effective"),
  274. effective_period=data.get("effective_period"),
  275. invalid_mode=data.get("invalid_mode"),
  276. share_mode=data.get("share_mode"),
  277. )
  278. log.info(f"编辑自动发放规则成功: issue_rule_id={issue_rule_id}")
  279. return SuccessResponse(data=result, msg="编辑自动发放规则成功")
  280. @InstitutionRouter.delete(
  281. "/{institution_id}/issuerule",
  282. summary="删除自动发放规则",
  283. description="删除自动额度发放规则 (alipay.ebpp.invoice.issuerule.delete)",
  284. )
  285. async def delete_issuerule_controller(
  286. institution_id: Annotated[str, Path(description="制度ID")],
  287. data: dict,
  288. auth: Annotated[AuthSchema, Depends(AuthPermission(["module_payment:expense:institution:issuerule:delete"]))],
  289. ) -> JSONResponse:
  290. result = await IssueruleService.delete_issuerule_service(
  291. auth=auth,
  292. institution_id=institution_id,
  293. issue_rule_id_list=data.get("issue_rule_id_list", []),
  294. enterprise_id=data.get("enterprise_id", ""),
  295. )
  296. log.info(f"删除自动发放规则成功: institution_id={institution_id}")
  297. return SuccessResponse(data=result, msg="删除自动发放规则成功")