controller.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # -*- coding: utf-8 -*-
  2. import httpx
  3. from fastapi import APIRouter, Depends, UploadFile, Body, Path, Query
  4. from fastapi.responses import StreamingResponse, JSONResponse
  5. from redis.asyncio.client import Redis
  6. from app.common.response import SuccessResponse, StreamResponse
  7. from app.config.setting import settings
  8. from app.core.dependencies import AuthPermission, redis_getter
  9. from app.api.v1.module_system.auth.schema import AuthSchema
  10. from app.core.base_params import PaginationQueryParam
  11. from app.utils.common_util import bytes2file_response
  12. from app.core.logger import log
  13. from app.core.base_schema import BatchSetAvailable
  14. from .service import BizVarDictService
  15. from .schema import BizVarDictCreateSchema, BizVarDictUpdateSchema, BizVarDictQueryParam
  16. BizVarDictRouter = APIRouter(prefix='/vardict', tags=["变量信息模块"])
  17. @BizVarDictRouter.get("/detail/{id}", summary="获取变量信息详情", description="获取变量信息详情")
  18. async def get_vardict_detail_controller(
  19. id: int = Path(..., description="ID"),
  20. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:query"]))
  21. ) -> JSONResponse:
  22. """获取变量信息详情接口"""
  23. result_dict = await BizVarDictService.detail_vardict_service(auth=auth, id=id)
  24. log.info(f"获取变量信息详情成功 {id}")
  25. return SuccessResponse(data=result_dict, msg="获取变量信息详情成功")
  26. @BizVarDictRouter.get("/list", summary="查询变量信息列表", description="查询变量信息列表")
  27. async def get_vardict_list_controller(
  28. page: PaginationQueryParam = Depends(),
  29. search: BizVarDictQueryParam = Depends(),
  30. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:query"]))
  31. ) -> JSONResponse:
  32. """查询变量信息列表接口(数据库分页)"""
  33. result_dict = await BizVarDictService.page_vardict_service(
  34. auth=auth,
  35. page_no=page.page_no if page.page_no is not None else 1,
  36. page_size=page.page_size if page.page_size is not None else 10,
  37. search=search,
  38. order_by=page.order_by
  39. )
  40. log.info("查询变量信息列表成功")
  41. return SuccessResponse(data=result_dict, msg="查询变量信息列表成功")
  42. @BizVarDictRouter.post("/create", summary="创建变量信息", description="创建变量信息")
  43. async def create_vardict_controller(
  44. data: BizVarDictCreateSchema,
  45. redis: Redis = Depends(redis_getter),
  46. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:create"]))
  47. ) -> JSONResponse:
  48. """创建变量信息接口"""
  49. result_dict = await BizVarDictService.create_vardict_service(auth=auth, data=data,redis=redis)
  50. log.info("创建变量信息成功")
  51. return SuccessResponse(data=result_dict, msg="创建变量信息成功")
  52. @BizVarDictRouter.put("/update/{id}", summary="修改变量信息", description="修改变量信息")
  53. async def update_vardict_controller(
  54. data: BizVarDictUpdateSchema,
  55. id: int = Path(..., description="ID"),
  56. redis: Redis = Depends(redis_getter),
  57. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:update"]))
  58. ) -> JSONResponse:
  59. """修改变量信息接口"""
  60. result_dict = await BizVarDictService.update_vardict_service(auth=auth, id=id, data=data,redis=redis)
  61. log.info("修改变量信息成功")
  62. return SuccessResponse(data=result_dict, msg="修改变量信息成功")
  63. @BizVarDictRouter.delete("/delete", summary="删除变量信息", description="删除变量信息")
  64. async def delete_vardict_controller(
  65. ids: list[int] = Body(..., description="ID列表"),
  66. redis: Redis = Depends(redis_getter),
  67. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:delete"]))
  68. ) -> JSONResponse:
  69. """删除变量信息接口"""
  70. await BizVarDictService.delete_vardict_service(auth=auth, ids=ids,redis=redis)
  71. log.info(f"删除变量信息成功: {ids}")
  72. return SuccessResponse(msg="删除变量信息成功")
  73. @BizVarDictRouter.patch("/available/setting", summary="批量修改变量信息状态", description="批量修改变量信息状态")
  74. async def batch_set_available_vardict_controller(
  75. data: BatchSetAvailable,
  76. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:patch"]))
  77. ) -> JSONResponse:
  78. """批量修改变量信息状态接口"""
  79. await BizVarDictService.set_available_vardict_service(auth=auth, data=data)
  80. log.info(f"批量修改变量信息状态成功: {data.ids}")
  81. return SuccessResponse(msg="批量修改变量信息状态成功")
  82. @BizVarDictRouter.post('/export', summary="导出变量信息", description="导出变量信息")
  83. async def export_vardict_list_controller(
  84. search: BizVarDictQueryParam = Depends(),
  85. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:export"]))
  86. ) -> StreamingResponse:
  87. """导出变量信息接口"""
  88. result_dict_list = await BizVarDictService.list_vardict_service(search=search, auth=auth)
  89. export_result = await BizVarDictService.batch_export_vardict_service(obj_list=result_dict_list)
  90. log.info('导出变量信息成功')
  91. return StreamResponse(
  92. data=bytes2file_response(export_result),
  93. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  94. headers={
  95. 'Content-Disposition': 'attachment; filename=biz_var_dict.xlsx'
  96. }
  97. )
  98. @BizVarDictRouter.post('/import', summary="导入变量信息", description="导入变量信息")
  99. async def import_vardict_list_controller(
  100. file: UploadFile,
  101. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:import"]))
  102. ) -> JSONResponse:
  103. """导入变量信息接口"""
  104. batch_import_result = await BizVarDictService.batch_import_vardict_service(file=file, auth=auth, update_support=True)
  105. log.info("导入变量信息成功")
  106. return SuccessResponse(data=batch_import_result, msg="导入变量信息成功")
  107. @BizVarDictRouter.post('/download/template', summary="获取变量信息导入模板", description="获取变量信息导入模板", dependencies=[Depends(AuthPermission(["module_business:vardict:download"]))])
  108. async def export_vardict_template_controller() -> StreamingResponse:
  109. """获取变量信息导入模板接口"""
  110. import_template_result = await BizVarDictService.import_template_download_vardict_service()
  111. log.info('获取变量信息导入模板成功')
  112. return StreamResponse(
  113. data=bytes2file_response(import_template_result),
  114. media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  115. headers={'Content-Disposition': 'attachment; filename=biz_var_dict_template.xlsx'}
  116. )
  117. @BizVarDictRouter.get("/list_alarms", summary="查询变量信息列表", description="查询变量信息列表")
  118. async def get_vardict_list_alarms_controller(
  119. search: BizVarDictQueryParam = Depends(),
  120. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:query"]))
  121. ) -> JSONResponse:
  122. """查询变量信息列表接口(数据库分页)"""
  123. result_dict = await BizVarDictService.vardict_alarms_list(auth=auth,crane_no=search.crane_no)
  124. #请求采集接口获取状态信息
  125. async with httpx.AsyncClient() as client:
  126. response = await client.get(
  127. url=settings.COLLECT_DATA_FULL,
  128. params={},
  129. timeout=2
  130. )
  131. if response.status_code == 200:
  132. json_data = response.json()
  133. if json_data['code'] == 200 and json_data['data']:
  134. for item in result_dict:
  135. item['value'] = False
  136. crane_no = item['crane_no']
  137. alarm = json_data.get('data').get(crane_no).get('data').get('alarm').get(item['var_code'])
  138. if alarm:
  139. item['value'] = alarm.get('value')
  140. log.info("查询变量信息列表成功")
  141. return SuccessResponse(data=result_dict, msg="查询变量信息列表成功")
  142. @BizVarDictRouter.get("/list_analog", summary="查询变量信息列表", description="查询变量信息列表")
  143. async def get_vardict_list_analog_controller(
  144. search: BizVarDictQueryParam = Depends(),
  145. auth: AuthSchema = Depends(AuthPermission(["module_business:vardict:query"]))
  146. ) -> JSONResponse:
  147. """查询变量信息列表接口(数据库分页)"""
  148. result_dict = await BizVarDictService.vardict_analog_list(auth=auth,crane_no=search.crane_no)
  149. #请求采集接口获取状态信息
  150. async with httpx.AsyncClient() as client:
  151. response = await client.get(
  152. url=settings.COLLECT_DATA_FULL,
  153. params={},
  154. timeout=2
  155. )
  156. if response.status_code == 200:
  157. json_data = response.json()
  158. if json_data['code'] == 200 and json_data['data']:
  159. for item in result_dict:
  160. item['value'] = False
  161. crane_no = item['crane_no']
  162. analog = json_data.get('data').get(crane_no).get('data').get('analog').get(item['var_code'])
  163. if analog:
  164. item['value'] = analog.get('value')
  165. log.info("查询变量信息列表成功")
  166. return SuccessResponse(data=result_dict, msg="查询变量信息列表成功")
  167. @BizVarDictRouter.get("/varDictMecGroup/{crane_no}", summary="获取变量信息分组数据", description="获取变量信息分组数据")
  168. async def get_vardict_mec_group_controller(
  169. crane_no: str = Path(..., description="crane_no"),
  170. redis: Redis = Depends(redis_getter),
  171. auth: AuthSchema = Depends(AuthPermission(["module_business:crane:query"]))
  172. ) -> JSONResponse:
  173. result_dict = await BizVarDictService.get_vardict_group_service(
  174. redis=redis, crane_no=crane_no,auth=auth
  175. )
  176. if not result_dict:
  177. log.info(f"获取变量信息分组数据成功:{result_dict}")
  178. return SuccessResponse(data=result_dict, msg="获取变量分组数据成功")
  179. #请求采集接口获取状态信息
  180. async with httpx.AsyncClient() as client:
  181. response = await client.get(
  182. url=settings.COLLECT_DATA_FULL,
  183. params={},
  184. timeout=2
  185. )
  186. if response.status_code == 200:
  187. json_data = response.json()
  188. if json_data['code'] == 200 and json_data['data']:
  189. json_analog = json_data.get('data').get(crane_no).get('data').get('analog')
  190. json_digital = json_data.get('data').get(crane_no).get('data').get('digital')
  191. for var_dict in result_dict:
  192. for key,inner_dict in var_dict.items():
  193. if key != 'mec_type' and key != 'alarm_varList' and key != 'mecVarList_simple':
  194. for item in inner_dict:
  195. if key == 'digital_varList':
  196. item['value'] = json_digital.get(item.get('var_code')).get('value')
  197. else:
  198. item['value'] = json_analog.get(item.get('var_code')).get('value')
  199. log.info(f"获取变量信息分组数据成功:{result_dict}")
  200. return SuccessResponse(data=result_dict, msg="获取变量分组数据成功")