__init__.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends,Query, HTTPException, status
  4. from common.security import valid_access_token
  5. from fastapi.responses import JSONResponse
  6. from sqlalchemy.orm import Session
  7. from sqlalchemy import and_, or_
  8. from pydantic import BaseModel
  9. from datetime import datetime
  10. from database import get_db
  11. from typing import List
  12. from models import *
  13. from utils import *
  14. import json
  15. import traceback
  16. router = APIRouter()
  17. ####巡查人员####
  18. @router.get('/inspection/user/list')
  19. async def get_inspection_user_list(
  20. nickName: str = Query(None, description='姓名'),
  21. deptId :str = Query(None, description='部门id'),
  22. page: int = Query(1, gt=0, description='页码'),
  23. pageSize: int = Query(5, gt=0, description='每页条目数量'),
  24. db: Session = Depends(get_db),
  25. user_id = Depends(valid_access_token)
  26. ):
  27. try:
  28. # 构建查询
  29. query = db.query(RiskManagementInspectionUser)
  30. query = query.filter(RiskManagementInspectionUser.del_flag != '2')
  31. # 应用查询条件
  32. if nickName:
  33. query = query.filter(RiskManagementInspectionUser.nick_name.like(f'%{nickName}%'))
  34. if deptId:
  35. query = query.filter(RiskManagementInspectionUser.dept_id == deptId)
  36. # 计算总条目数
  37. total_items = query.count()
  38. # 排序
  39. query = query.order_by(RiskManagementInspectionUser.create_time.desc())
  40. # 执行分页查询
  41. InspectionUsers = query.offset((page - 1) * pageSize).limit(pageSize).all()
  42. # 将查询结果转换为列表形式的字典
  43. InspectionUsers_list = [
  44. {
  45. "id": user.id,
  46. "user_id": user.user_id,
  47. "dept_id": user.dept_id,
  48. "dept_name": user.dept_name,
  49. "ancestors_names": user.ancestors_names,
  50. "user_name": user.user_name,
  51. "create_time": user.create_time.strftime('%Y-%m-%d'),
  52. "phonenumber": user.phonenumber,
  53. "nick_name": user.nick_name,
  54. "area_code": user.area_code,
  55. "area": user.area,
  56. "yzy_account":user.yzy_account
  57. }
  58. for user in InspectionUsers
  59. ]
  60. # 返回结果
  61. return {
  62. "code": 200,
  63. "msg": "成功",
  64. "data": InspectionUsers_list,
  65. "total": total_items,
  66. "page": page,
  67. "pageSize": pageSize,
  68. "totalPages": (total_items + pageSize - 1) // pageSize
  69. }
  70. except Exception as e:
  71. # 处理异常
  72. raise HTTPException(status_code=500, detail=str(e))
  73. @router.get('/inspection/user/{id}')
  74. async def get_inspection_user(
  75. id: str ,
  76. db: Session = Depends(get_db),
  77. user_id = Depends(valid_access_token)
  78. ):
  79. try:
  80. # 构建查询
  81. query = db.query(RiskManagementInspectionUser)
  82. query = query.filter(RiskManagementInspectionUser.del_flag != '2')
  83. # 应用查询条件
  84. if id:
  85. query = query.filter(RiskManagementInspectionUser.id == id)
  86. # 执行查询
  87. user = query.first()
  88. if not user:
  89. detail = "用户不存在"
  90. raise HTTPException(status_code=404, detail="用户不存在")
  91. # 将查询结果转换为列表形式的字典
  92. inspection_user_result = {
  93. "id": user.id,
  94. "user_id": user.user_id,
  95. "dept_id": user.dept_id,
  96. "dept_name": user.dept_name,
  97. "ancestors_names": user.ancestors_names,
  98. "user_name": user.user_name,
  99. "create_time": user.create_time.strftime('%Y-%m-%d'),
  100. "phonenumber": user.phonenumber,
  101. "nick_name": user.nick_name,
  102. "area_code": user.area_code,
  103. "area": user.area,
  104. "yzy_account":user.yzy_account
  105. }
  106. # 返回结果
  107. return {
  108. "code": 200,
  109. "msg": "成功",
  110. "data": inspection_user_result
  111. }
  112. except Exception as e:
  113. # 处理异常
  114. if str(e)=='':
  115. e = detail
  116. raise HTTPException(status_code=500, detail=str(e))
  117. @router.post('/inspection/user/create')
  118. async def create_inspection_user(
  119. db: Session = Depends(get_db),
  120. body = Depends(remove_xss_json),
  121. user_id = Depends(valid_access_token)
  122. ):
  123. try:
  124. # 创建新的预案记录
  125. new_user = RiskManagementInspectionUser(
  126. user_id=body['user_id'],
  127. dept_id = body['dept_id'],
  128. dept_name = body['dept_name'],
  129. ancestors_names = body['ancestors_names'],
  130. user_name = body['user_name'],
  131. nick_name = body['nick_name'],
  132. phonenumber = body['phonenumber'],
  133. area_code = body['area_code'],
  134. area = body['area'],
  135. yzy_account = body['yzy_account'],
  136. create_by = user_id
  137. )
  138. # 添加到数据库会话并提交
  139. db.add(new_user)
  140. db.commit()
  141. db.refresh(new_user) # 可选,如果需要刷新实例状态
  142. # 返回创建成功的响应
  143. return {
  144. "code": 200,
  145. "msg": "成功",
  146. "data": None
  147. }
  148. except Exception as e:
  149. # 处理异常
  150. raise HTTPException(status_code=500, detail=str(e))
  151. @router.put('/inspection/user/update')
  152. async def update_inspection_user(
  153. db: Session = Depends(get_db),
  154. body = Depends(remove_xss_json),
  155. user_id = Depends(valid_access_token)
  156. ):
  157. try:
  158. # 提取请求数据
  159. query = db.query(RiskManagementInspectionUser)
  160. query = query.filter(RiskManagementInspectionUser.id == body['id'])
  161. query = query.filter(RiskManagementInspectionUser.del_flag != '2')
  162. user = query.first()
  163. if not user:
  164. detail = "用户不存在"
  165. raise HTTPException(status_code=404, detail="用户不存在")
  166. if 'user_id' in body:
  167. user.user_id = body['user_id']
  168. if 'dept_id' in body:
  169. user.dept_id = body['dept_id']
  170. if 'dept_name' in body:
  171. user.dept_name = body['dept_name']
  172. if 'ancestors_names' in body:
  173. user.ancestors_names = body['ancestors_names']
  174. if 'user_name' in body:
  175. user.user_name = body['user_name']
  176. if 'nick_name' in body:
  177. user.nick_name = body['nick_name']
  178. if 'phonenumber' in body:
  179. user.phonenumber = body['phonenumber']
  180. if 'area_code' in body:
  181. user.area_code = body['area_code']
  182. if 'area' in body:
  183. user.area = body['area']
  184. if user_id:
  185. user.update_by = user_id
  186. # 更新到数据库会话并提交
  187. db.commit()
  188. db.refresh(user) # 可选,如果需要刷新实例状态
  189. # 返回创建成功的响应
  190. return {
  191. "code": 200,
  192. "msg": "成功",
  193. "data": None
  194. }
  195. except Exception as e:
  196. # 处理异常
  197. if str(e)=='':
  198. e = detail
  199. raise HTTPException(status_code=500, detail=str(e))
  200. @router.delete('/inspection/user/delete')
  201. async def delete_inspection_users(
  202. userIds: list,
  203. db: Session = Depends(get_db),
  204. body = Depends(remove_xss_json),
  205. user_id = Depends(valid_access_token)
  206. ):
  207. try:
  208. # 提取请求数据
  209. query = db.query(RiskManagementInspectionUser)
  210. query = query.filter(RiskManagementInspectionUser.del_flag != '2')
  211. query = query.filter(RiskManagementInspectionUser.id.in_(userIds))
  212. users = query.all()
  213. if not users:
  214. detail = "用户不存在"
  215. raise HTTPException(status_code=404, detail="用户不存在")
  216. for user in users:
  217. user.del_flag = '2'
  218. user.update_by=user_id
  219. # 更新到数据库会话并提交
  220. db.commit()
  221. # 返回创建成功的响应
  222. return {
  223. "code": 200,
  224. "msg": "删除成功",
  225. "data": None
  226. }
  227. except Exception as e:
  228. # 处理异常
  229. if str(e) == '':
  230. e = detail
  231. raise HTTPException(status_code=500, detail=str(e))
  232. @router.delete('/inspection/user/delete/{userId}')
  233. async def delete_inspection_user(
  234. userId: str,
  235. db: Session = Depends(get_db),
  236. body = Depends(remove_xss_json),
  237. user_id = Depends(valid_access_token)
  238. ):
  239. try:
  240. # 提取请求数据
  241. query = db.query(RiskManagementInspectionUser)
  242. query = query.filter(RiskManagementInspectionUser.del_flag != '2')
  243. query = query.filter(RiskManagementInspectionUser.id==userId)
  244. user = query.first()
  245. if not user:
  246. detail = "用户不存在"
  247. raise HTTPException(status_code=404, detail="用户不存在")
  248. user.del_flag = '2'
  249. user.update_by = user_id
  250. # 更新到数据库会话并提交
  251. db.commit()
  252. db.refresh(user) # 可选,如果需要刷新实例状态
  253. # 返回创建成功的响应
  254. return {
  255. "code": 200,
  256. "msg": "删除成功",
  257. "data": None
  258. }
  259. except Exception as e:
  260. # 处理异常
  261. if str(e) == '':
  262. e = detail
  263. raise HTTPException(status_code=500, detail=str(e))
  264. @router.get("/allAreas")
  265. def read_all_areas(db: Session = Depends(get_db)):
  266. def parent_id_get_area_info(parent_id):
  267. query = db.query(GovdataArea)
  268. query = query.filter(GovdataArea.parent_id == parent_id)
  269. return query.all()
  270. def build_area_tree(areas, parent_area):
  271. # 收集祖先部门名称
  272. area_tree = []
  273. for area_info in areas:
  274. # current_area = db.query(GovdataArea).filter(GovdataArea.id == area_info.id).first()
  275. # ancestors_names = []
  276. # while current_area:
  277. # ancestors_names.append(current_area.area_name)
  278. # current_area = db.query(GovdataArea).filter(GovdataArea.id == current_area.parent_id).first()
  279. # ancestors_names.reverse()
  280. area = {
  281. "id": area_info.id,
  282. "code": area_info.area_code,
  283. "label": area_info.area_name,
  284. "parentId": area_info.parent_id,
  285. # "ancestors": '/'.join(ancestors_names)
  286. }
  287. # print(dept_info.dept_id)
  288. children = parent_id_get_area_info(area_info.id)
  289. if len(children) > 0:
  290. children_areas = build_area_tree(children, area)
  291. area["children"] = children_areas
  292. area_tree.append(area)
  293. return area_tree
  294. # data = build_area_tree(parent_id_get_area_info(0),None)
  295. filename = '/home/python3/xh_twapi01/routers/api/riskManagement/area_tree.json'
  296. # 打开文件并读取内容
  297. with open(filename, 'r', encoding='utf-8') as file:
  298. # 加载JSON内容到一个字典
  299. data = json.load(file)
  300. return {
  301. "code": 200,
  302. "msg": "成功",
  303. "data": data
  304. }
  305. ####巡查任务####
  306. @router.get('/inspection/task/list')
  307. async def get_inspection_task_list(
  308. business: str = Query(None, description='巡查业务'),
  309. cycle :str = Query(None, description='巡查周期'),
  310. page: int = Query(1, gt=0, description='页码'),
  311. pageSize: int = Query(10, gt=0, description='每页条目数量'),
  312. db: Session = Depends(get_db),
  313. user_id = Depends(valid_access_token)
  314. ):
  315. try:
  316. # 构建查询
  317. query = db.query(RiskManagementInspectionTask)
  318. query = query.filter(RiskManagementInspectionTask.del_flag != '2')
  319. # 应用查询条件
  320. if business:
  321. query = query.filter(RiskManagementInspectionTask.inspection_business == business)
  322. if cycle:
  323. query = query.filter(RiskManagementInspectionTask.inspection_cycle == cycle)
  324. # 计算总条目数
  325. total_items = query.count()
  326. # 排序
  327. query = query.order_by(RiskManagementInspectionTask.create_time.desc())
  328. # 执行分页查询
  329. InspectionTasks = query.offset((page - 1) * pageSize).limit(pageSize).all()
  330. # 将查询结果转换为列表形式的字典
  331. InspectionTasks_list = []
  332. for task in InspectionTasks:
  333. if task.task_status=='3':
  334. task_status = '3' #'已完结'
  335. else:
  336. if datetime.now()<task.start_time:
  337. task_status = '0' #'未开始'
  338. elif task.start_time<=datetime.now()<=task.end_time:
  339. task_status = '1' #'进行中'
  340. else:
  341. task_status = '2' #'未完成'
  342. task_info = {
  343. "id": task.id,
  344. "task_number": task.task_number,
  345. "business": task.inspection_business,
  346. "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
  347. "cycle": task.inspection_cycle,
  348. "inspection_range": task.inspection_range,
  349. "task_status": task_status,
  350. "create_time": task.create_time.strftime('%Y-%m-%d')
  351. }
  352. InspectionTasks_list.append(task_info)
  353. # 返回结果
  354. return {
  355. "code": 200,
  356. "msg": "成功",
  357. "data": InspectionTasks_list,
  358. "total": total_items,
  359. "page": page,
  360. "pageSize": pageSize,
  361. "totalPages": (total_items + pageSize - 1) // pageSize
  362. }
  363. except Exception as e:
  364. # 处理异常
  365. raise HTTPException(status_code=500, detail=str(e))
  366. @router.get('/inspection/task/{id}')
  367. async def get_inspection_task(
  368. id: str ,
  369. db: Session = Depends(get_db),
  370. user_id = Depends(valid_access_token)
  371. ):
  372. try:
  373. # 构建查询
  374. query = db.query(RiskManagementInspectionTask)
  375. query = query.filter(RiskManagementInspectionTask.del_flag != '2')
  376. # 应用查询条件
  377. if id:
  378. query = query.filter(RiskManagementInspectionTask.id == id)
  379. # 执行查询
  380. task = query.first()
  381. if not task:
  382. detail = "巡查任务不存在"
  383. raise HTTPException(status_code=404, detail="用户不存在")
  384. # 将查询结果转换为列表形式的字典
  385. if task.task_status == '3':
  386. task_status = '3' # '已完结'
  387. else:
  388. if datetime.now() < task.start_time:
  389. task_status = '0' # '未开始'
  390. elif task.start_time <= datetime.now() <= task.end_time:
  391. task_status = '1' # '进行中'
  392. else:
  393. task_status = '2' # '未完成'
  394. inspection_task_result = {
  395. "id": task.id,
  396. "task_number": task.task_number,
  397. "business": task.inspection_business,
  398. "task_time": '%s-%s'%(task.start_time.strftime('%Y/%m/%d'),task.end_time.strftime('%Y/%m/%d')),
  399. "cycle": task.inspection_cycle,
  400. "inspection_range": task.inspection_range,
  401. "task_status": task_status,
  402. "create_time": task.create_time.strftime('%Y-%m-%d')
  403. }
  404. # 返回结果
  405. return {
  406. "code": 200,
  407. "msg": "成功",
  408. "data": inspection_task_result
  409. }
  410. except Exception as e:
  411. # 处理异常
  412. if str(e)=='':
  413. e = detail
  414. raise HTTPException(status_code=500, detail=str(e))
  415. @router.post('/inspection/task/create')
  416. async def create_inspection_task(
  417. db: Session = Depends(get_db),
  418. body = Depends(remove_xss_json),
  419. user_id = Depends(valid_access_token)
  420. ):
  421. try:
  422. cycle = body['cycle']
  423. # 0每年、1每月、2每周、3每日、4一次
  424. corn_query = body['corn_query']
  425. if cycle=='0':
  426. corn=f'0 0 {corn_query} *'
  427. elif cycle=='1':
  428. corn=f'0 0 {corn_query} * *'
  429. elif cycle == '2':
  430. corn = f'0 0 * * {corn_query}'
  431. elif cycle == '3':
  432. corn = f'0 0 * * *'
  433. else:
  434. corn=''
  435. # 创建新的预案记录
  436. new_task = RiskManagementInspectionTask(
  437. inspection_business=body['business'],
  438. start_time = body['start_time'],
  439. end_time = body['end_time'],
  440. inspection_cycle = cycle,
  441. corn_expression = corn,
  442. inspection_range = body['inspection_range'],
  443. task_status = '-1',
  444. create_by = user_id
  445. )
  446. # 添加到数据库会话并提交
  447. db.add(new_task)
  448. db.commit()
  449. db.refresh(new_task) # 可选,如果需要刷新实例状态
  450. new_task.task_number = f'YJXC{str(new_task.id).zfill(10)}'
  451. db.commit()
  452. # 返回创建成功的响应
  453. return {
  454. "code": 200,
  455. "msg": "成功",
  456. "data": None
  457. }
  458. except Exception as e:
  459. # 处理异常
  460. raise HTTPException(status_code=500, detail=str(e))
  461. @router.put('/inspection/task/update')
  462. async def update_inspection_task(
  463. db: Session = Depends(get_db),
  464. body = Depends(remove_xss_json),
  465. user_id = Depends(valid_access_token)
  466. ):
  467. try:
  468. # 提取请求数据
  469. query = db.query(RiskManagementInspectionTask)
  470. query = query.filter(RiskManagementInspectionTask.id == body['id'])
  471. query = query.filter(RiskManagementInspectionTask.del_flag != '2')
  472. task = query.first()
  473. if not task:
  474. detail = "任务不存在"
  475. raise HTTPException(status_code=404, detail="任务不存在")
  476. if 'cycle' in body:
  477. cycle = body['cycle']
  478. # 0每年、1每月、2每周、3每日、4一次
  479. corn_query = body['corn_query']
  480. if cycle == '0':
  481. corn = f'0 0 {corn_query} *'
  482. elif cycle == '1':
  483. corn = f'0 0 {corn_query} * *'
  484. elif cycle == '2':
  485. corn = f'0 0 * * {corn_query}'
  486. elif cycle == '3':
  487. corn = f'0 0 * * *'
  488. else:
  489. corn = ''
  490. task.inspection_cycle = cycle
  491. task.corn_expression = corn
  492. if 'business' in body:
  493. task.inspection_business = body['business']
  494. if 'start_time' in body:
  495. task.start_time = body['start_time']
  496. if 'end_time' in body:
  497. task.end_time = body['end_time']
  498. if 'inspection_range' in body:
  499. task.inspection_range = body['inspection_range']
  500. if 'task_status' in body:
  501. task.task_status = body['task_status']
  502. if user_id:
  503. task.update_by = user_id
  504. # 更新到数据库会话并提交
  505. db.commit()
  506. db.refresh(task) # 可选,如果需要刷新实例状态
  507. # 返回创建成功的响应
  508. return {
  509. "code": 200,
  510. "msg": "成功",
  511. "data": None
  512. }
  513. except Exception as e:
  514. # 处理异常
  515. if str(e)=='':
  516. e = detail
  517. raise HTTPException(status_code=500, detail=str(e))
  518. @router.delete('/inspection/task/delete')
  519. async def delete_inspection_tasks(
  520. taskIds: list,
  521. db: Session = Depends(get_db),
  522. body = Depends(remove_xss_json),
  523. user_id = Depends(valid_access_token)
  524. ):
  525. try:
  526. # 提取请求数据
  527. query = db.query(RiskManagementInspectionTask)
  528. query = query.filter(RiskManagementInspectionTask.del_flag != '2')
  529. query = query.filter(RiskManagementInspectionTask.id.in_(taskIds))
  530. tasks = query.all()
  531. if not tasks:
  532. detail = "任务不存在"
  533. raise HTTPException(status_code=404, detail="任务不存在")
  534. for task in tasks:
  535. task.del_flag = '2'
  536. task.update_by=user_id
  537. # 更新到数据库会话并提交
  538. db.commit()
  539. # 返回创建成功的响应
  540. return {
  541. "code": 200,
  542. "msg": "删除成功",
  543. "data": None
  544. }
  545. except Exception as e:
  546. # 处理异常
  547. if str(e) == '':
  548. e = detail
  549. raise HTTPException(status_code=500, detail=str(e))
  550. @router.delete('/inspection/task/delete/{userId}')
  551. async def delete_inspection_task(
  552. userId: str,
  553. db: Session = Depends(get_db),
  554. body = Depends(remove_xss_json),
  555. user_id = Depends(valid_access_token)
  556. ):
  557. try:
  558. # 提取请求数据
  559. query = db.query(RiskManagementInspectionTask)
  560. query = query.filter(RiskManagementInspectionTask.del_flag != '2')
  561. query = query.filter(RiskManagementInspectionTask.id==userId)
  562. task = query.first()
  563. if not task:
  564. detail = "用户不存在"
  565. raise HTTPException(status_code=404, detail="用户不存在")
  566. task.del_flag = '2'
  567. task.update_by = user_id
  568. # 更新到数据库会话并提交
  569. db.commit()
  570. db.refresh(task) # 可选,如果需要刷新实例状态
  571. # 返回创建成功的响应
  572. return {
  573. "code": 200,
  574. "msg": "删除成功",
  575. "data": None
  576. }
  577. except Exception as e:
  578. # 处理异常
  579. if str(e) == '':
  580. e = detail
  581. raise HTTPException(status_code=500, detail=str(e))