controller.py 14 KB

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