controller.py 14 KB

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