__init__.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends,Query, HTTPException, status
  4. from pydantic import BaseModel
  5. from typing import List
  6. from fastapi.responses import JSONResponse
  7. from database import get_db
  8. from sqlalchemy.orm import Session
  9. from sqlalchemy import and_, or_
  10. from datetime import datetime
  11. from models import *
  12. from utils import *
  13. import json
  14. router = APIRouter()
  15. class File(BaseModel):
  16. status :str
  17. name : str
  18. url : str
  19. class PlanCreateForm(BaseModel):
  20. planName : str
  21. planType : int
  22. # planTypeDesc : str
  23. publishDate: str
  24. organizingUnit : str
  25. document : str
  26. fileList : List[File] = []
  27. class DrillCreateForm(BaseModel):
  28. planId : str
  29. drillName : str
  30. drillUnit : str
  31. year : int
  32. drillTime: str
  33. drillAddress : str
  34. lon : float
  35. lat : float
  36. drillProject : List[File] = []
  37. drillVideo : List[File] = []
  38. drillPicture : List[File] = []
  39. def get_file_query_fun(from_scenario,foreign_key):
  40. file_query = db.query(EmergencyFile)
  41. file_query = file_query.filter(EmergencyFile.del_flag != '2')
  42. file_query = file_query.filter(EmergencyFile.from_scenario == from_scenario)
  43. file_query = file_query.filter(EmergencyFile.foreign_key == foreign_key)
  44. files = file_query.all()
  45. result = [{
  46. "uid": file.file_id,
  47. "status": file.status,
  48. "name": file.file_name_desc,
  49. "url": "/api/file/download/%s" % file.file_name
  50. } for file in files]
  51. return result
  52. @router.get('/plan/list')
  53. async def get_emergency_plan_list(
  54. planType: str = Query(None, description='预案类型'),
  55. # publishDate: datetime = Query(None, description='发布日期'),
  56. beginTime :str = Query(None, description='发布日期起始'),
  57. endTime :str = Query(None, description='发布日期结束'),
  58. # planName: str = Query(None, description='预案名称'),
  59. keywords : str = Query(None, description='预案名称/编制单位'),
  60. page: int = Query(1, gt=0, description='页码'),
  61. pageSize: int = Query(5, gt=0, description='每页条目数量'),
  62. db: Session = Depends(get_db)
  63. ):
  64. try:
  65. # 构建查询
  66. query = db.query(EmergencyPlan)
  67. query = query.filter(EmergencyPlan.del_flag != '2')
  68. # 应用查询条件
  69. if planType:
  70. query = query.filter(EmergencyPlan.plan_type == planType)
  71. # if publishDate:
  72. # query = query.filter(EmergencyPlan.publish_date == publishDate)
  73. if beginTime:
  74. query = query.filter(EmergencyPlan.publish_date >= beginTime)
  75. if endTime:
  76. query = query.filter(EmergencyPlan.publish_date <= endTime)
  77. if keywords:
  78. query = query.filter(
  79. or_(
  80. EmergencyPlan.plan_name.like(f'%{keywords}%'),
  81. EmergencyPlan.organizing_unit.like(f'%{keywords}%')
  82. )
  83. )
  84. # query = query.filter(EmergencyPlan.plan_name.like(f'%{planName}%'))
  85. # 计算总条目数
  86. total_items = query.count()
  87. # 执行分页查询
  88. emergency_plans = query.offset((page - 1) * pageSize).limit(pageSize).all()
  89. # 将查询结果转换为列表形式的字典
  90. emergency_plans_list = [
  91. {
  92. "planUid": plan.plan_id,
  93. "planId": plan.plan_number,
  94. "planName": plan.plan_name,
  95. "planType": plan.plan_type,
  96. "organizingUnit": plan.organizing_unit,
  97. "document": plan.document_number,
  98. "publishDate": plan.publish_date.strftime('%Y-%m-%d')
  99. }
  100. for plan in emergency_plans
  101. ]
  102. # 构建分页信息
  103. pagination_info = {
  104. }
  105. # 返回结果
  106. return {
  107. "code": 200,
  108. "msg": "成功获取预案列表",
  109. "data": emergency_plans_list,
  110. "total": total_items,
  111. "page": page,
  112. "pageSize": pageSize,
  113. "totalPages": (total_items + pageSize - 1) // pageSize
  114. }
  115. except Exception as e:
  116. # 处理异常
  117. raise HTTPException(status_code=500, detail=str(e))
  118. @router.get('/plan/{planId}')
  119. async def get_emergency_plan(
  120. planId: str ,
  121. db: Session = Depends(get_db)
  122. ):
  123. try:
  124. # 构建查询
  125. query = db.query(EmergencyPlan)
  126. query = query.filter(EmergencyPlan.del_flag != '2')
  127. # 应用查询条件
  128. if planId:
  129. query = query.filter(EmergencyPlan.plan_number == planId)
  130. # 执行查询
  131. emergency_plan = query.first()
  132. # 将查询结果转换为列表形式的字典
  133. emergency_plan_result = {
  134. "planUid": emergency_plan.plan_id,
  135. "planId": emergency_plan.plan_number,
  136. "planName": emergency_plan.plan_name,
  137. "planType": emergency_plan.plan_type,
  138. "organizingUnit": emergency_plan.organizing_unit,
  139. "document": emergency_plan.document_number,
  140. "publish_date": emergency_plan.publish_date.strftime('%Y-%m-%d'),
  141. "fileList": get_file_query_fun(from_scenario='emergencyPlans_plan',foreign_key=emergency_plan.plan_id)
  142. }
  143. # 返回结果
  144. return {
  145. "code": 200,
  146. "msg": "成功获取预案详情",
  147. "data": emergency_plan_result
  148. }
  149. except Exception as e:
  150. # 处理异常
  151. raise HTTPException(status_code=500, detail=str(e))
  152. @router.post('/plan/create')
  153. async def create_emergency_plan(
  154. form_data:PlanCreateForm,
  155. db: Session = Depends(get_db)
  156. ):
  157. try:
  158. # 提取请求数据
  159. plan_name = form_data.planName
  160. plan_type = form_data.planType
  161. # plan_type_desc = form_data.planTypeDesc
  162. publish_date = form_data.publishDate # 如果没有提供发布日期,则使用当前时间
  163. organizing_unit = form_data.organizingUnit # 使用用户位置作为编制单位
  164. document_number = form_data.document
  165. # 创建新的预案记录
  166. new_plan = EmergencyPlan(
  167. plan_id=new_guid(), # 假设使用 UUID 作为预案 UID
  168. plan_name=plan_name,
  169. plan_type=plan_type,
  170. # plan_type_desc=plan_type_desc,
  171. publish_date=publish_date,
  172. organizing_unit=organizing_unit,
  173. document_number=document_number
  174. )
  175. # 添加到数据库会话并提交
  176. db.add(new_plan)
  177. db.commit()
  178. db.refresh(new_plan) # 可选,如果需要刷新实例状态
  179. new_plan.plan_number= f'YJYA{str(new_plan.id).zfill(10)}'
  180. db.commit()
  181. for file in form_data.fileList:
  182. file_name = file.url
  183. file_name_desc = file.name
  184. status = file.status
  185. new_file = EmergencyFile(
  186. file_id = new_guid(),
  187. foreign_key = new_plan.plan_id,
  188. from_scenario = 'emergencyPlans_plan',
  189. file_name=file_name,
  190. file_name_desc = file_name_desc,
  191. status = status
  192. )
  193. db.add(new_file)
  194. db.commit()
  195. db.refresh(new_file)
  196. # 返回创建成功的响应
  197. return {
  198. "code": 200,
  199. "msg": "预案创建成功",
  200. "data": None
  201. }
  202. except Exception as e:
  203. # 处理异常
  204. raise HTTPException(status_code=500, detail=str(e))
  205. # @router.put('/plan/update')
  206. # async def update_emergency_plan(
  207. # plan_data: dict,
  208. # db: Session = Depends(get_db)
  209. # ):
  210. # try:
  211. # # 提取请求数据
  212. # query = db.query(EmergencyPlan)
  213. # query = query.filter(EmergencyPlan.plan_id == plan_data.get('plan_id'))
  214. # query = query.filter(EmergencyPlan.del_flag != '2')
  215. # plan = query.first()
  216. # if not plan:
  217. # detail = "预案不存在"
  218. # raise HTTPException(status_code=404, detail="预案不存在")
  219. #
  220. # plan.plan_name = plan_data.get('plan_name')
  221. # plan.plan_type = plan_data.get('plan_type')
  222. # plan.plan_type_desc = plan_data.get('plan_type_desc')
  223. # plan.publish_date = plan_data.get('publish_date') # 如果没有提供发布日期,则使用当前时间
  224. # plan.organizing_unit = plan_data.get('organizing_unit') # 使用用户位置作为编制单位
  225. # plan.document_number = plan_data.get('document_number')
  226. #
  227. #
  228. # # 更新到数据库会话并提交
  229. # db.commit()
  230. # db.refresh(new_plan) # 可选,如果需要刷新实例状态
  231. #
  232. # # 返回创建成功的响应
  233. # return {
  234. # "code": 200,
  235. # "msg": "预案更新成功",
  236. # "data": None
  237. # }
  238. # except Exception as e:
  239. # # 处理异常
  240. # if str(e)=='':
  241. # e = detail
  242. # raise HTTPException(status_code=500, detail=str(e))
  243. #
  244. #
  245. @router.delete('/plan/delete/{planUid}')
  246. async def delete_emergency_plan(
  247. planUid: str,
  248. db: Session = Depends(get_db)
  249. ):
  250. try:
  251. # 提取请求数据
  252. query = db.query(EmergencyPlan)
  253. query = query.filter(EmergencyPlan.del_flag != '2')
  254. query = query.filter(EmergencyPlan.plan_id == planUid)
  255. plan = query.first()
  256. if not plan:
  257. detail = "预案不存在"
  258. raise HTTPException(status_code=404, detail="预案不存在")
  259. plan.del_flag = '2'
  260. # 更新到数据库会话并提交
  261. db.commit()
  262. db.refresh(plan) # 可选,如果需要刷新实例状态
  263. # 返回创建成功的响应
  264. return {
  265. "code": 200,
  266. "msg": "预案删除成功",
  267. "data": None
  268. }
  269. except Exception as e:
  270. # 处理异常
  271. if str(e) == '':
  272. e = detail
  273. raise HTTPException(status_code=500, detail=str(e))
  274. @router.get('/drill/list')
  275. async def get_emergency_drill_list(
  276. planNum: str = Query(None, description='预案编号'),
  277. page: int = Query(1, gt=0, description='页码'),
  278. pageSize: int = Query(5, gt=0, description='每页条目数量'),
  279. db: Session = Depends(get_db)
  280. ):
  281. try:
  282. # 构建查询
  283. query = db.query(EmergencyDrill)
  284. query = query.filter(EmergencyDrill.del_flag != '2')
  285. # 应用查询条件
  286. if planNum:
  287. query = query.filter(EmergencyDrill.plan_number == planNum)
  288. else:
  289. detail = "planNum不存在"
  290. raise HTTPException(status_code=404, detail="planNum不存在")
  291. # 计算总条目数
  292. total_items = query.count()
  293. # 执行分页查询
  294. emergency_drill = query.offset((page - 1) * pageSize).limit(pageSize).all() #
  295. print(emergency_drill)
  296. # 将查询结果转换为列表形式的字典
  297. emergency_drill_list = []
  298. for drill in emergency_drill:
  299. emergency_drill = {
  300. "drillId": drill.drill_id,
  301. "drillName": drill.drill_name,
  302. "drillUnit": drill.organizing_unit,
  303. "year": "%s年" % drill.planned_annual,
  304. "drillTime": drill.planned_time.strftime('%Y-%m-%d %H:%M:%S'),
  305. "drillAddress": drill.drill_location,
  306. "drillProject": get_file_query_fun(from_scenario='emergencyPlans_drill_project', foreign_key=drill.drill_id),
  307. "drillVideo": get_file_query_fun(from_scenario='emergencyPlans_drill_video', foreign_key=drill.drill_id),
  308. "drillPicture": get_file_query_fun(from_scenario='emergencyPlans_drill_pic', foreign_key=drill.drill_id)
  309. }
  310. emergency_drill_list.append(emergency_drill)
  311. # 返回结果
  312. return {
  313. "code": 200,
  314. "msg": "成功",
  315. "data": emergency_drill_list,
  316. "total": total_items,
  317. "page": page,
  318. "pageSize": pageSize,
  319. "totalPages": (total_items + pageSize - 1) // pageSize
  320. }
  321. except Exception as e:
  322. # 处理异常
  323. if str(e) == '':
  324. e = detail
  325. raise HTTPException(status_code=500, detail=str(e))
  326. @router.get('/drill/{drillId}}')
  327. async def get_emergency_drill(
  328. drillId: str = Query(None, description='演练编号'),
  329. db: Session = Depends(get_db)
  330. ):
  331. try:
  332. # 构建查询
  333. query = db.query(EmergencyDrill)
  334. query = query.filter(EmergencyDrill.del_flag != '2')
  335. # 应用查询条件
  336. if drillId:
  337. query = query.filter(EmergencyDrill.plan_number == drillId)
  338. else:
  339. detail = "drillId不存在"
  340. raise HTTPException(status_code=404, detail="drillId不存在")
  341. # 执行查询
  342. drill = query.first()
  343. # 将查询结果转换为字典形式
  344. emergency_drill = {
  345. "drillId": drill.drill_id,
  346. "drillName": drill.drill_name,
  347. "drillUnit": drill.organizing_unit,
  348. "year": "%s年" % drill.planned_annual,
  349. "drillTime": drill.planned_time.strftime('%Y-%m-%d %H:%M:%S'),
  350. "drillAddress": drill.drill_location,
  351. "drillProject": get_file_query_fun(from_scenario='emergencyPlans_drill_project',foreign_key=drill.drill_id),
  352. "drillVideo": get_file_query_fun(from_scenario='emergencyPlans_drill_video', foreign_key=drill.drill_id),
  353. "drillPicture": get_file_query_fun(from_scenario='emergencyPlans_drill_pic', foreign_key=drill.drill_id)
  354. }
  355. # 返回结果
  356. return {
  357. "code": 200,
  358. "msg": "成功",
  359. "data": emergency_drill
  360. }
  361. except Exception as e:
  362. # 处理异常
  363. if str(e) == '':
  364. e = detail
  365. raise HTTPException(status_code=500, detail=str(e))
  366. @router.post('/drill/create')
  367. async def create_emergency_drill(
  368. form_data:DrillCreateForm,
  369. db: Session = Depends(get_db)
  370. ):
  371. try:
  372. # 提取请求数据
  373. plan_number = form_data.planId
  374. drill_name = form_data.drillName
  375. organizing_unit = form_data.drillUnit
  376. planned_annual = form_data.year
  377. planned_time = form_data.drillTime
  378. drill_location = form_data.drillAddress
  379. drill_lon = form_data.lon
  380. drill_lat = form_data.lat
  381. # 创建新的预案记录
  382. new_drill = EmergencyDrill(
  383. drill_id=new_guid(), # 假设使用 UUID 作为预案 UID
  384. plan_number = plan_number,
  385. drill_name=drill_name,
  386. organizing_unit = organizing_unit,
  387. planned_annual = planned_annual,
  388. planned_time = planned_time,
  389. drill_location = drill_location,
  390. drill_lon = drill_lon,
  391. drill_lat = drill_lat
  392. )
  393. # 添加到数据库会话并提交
  394. db.add(new_drill)
  395. db.commit()
  396. db.refresh(new_drill) # 可选,如果需要刷新实例状态
  397. for file in form_data.drillProject:
  398. file_name = file.url
  399. file_name_desc = file.name
  400. status = file.status
  401. new_file = EmergencyFile(
  402. file_id = new_guid(),
  403. foreign_key = new_drill.drill_id,
  404. from_scenario = 'emergencyPlans_drill_project',
  405. file_name=file_name,
  406. file_name_desc = file_name_desc,
  407. status = status
  408. )
  409. db.add(new_file)
  410. db.commit()
  411. db.refresh(new_file)
  412. for file in form_data.drillVideo:
  413. file_name = file.url
  414. file_name_desc = file.name
  415. status = file.status
  416. new_file = EmergencyFile(
  417. file_id = new_guid(),
  418. foreign_key = new_drill.drill_id,
  419. from_scenario = 'emergencyPlans_drill_video',
  420. file_name=file_name,
  421. file_name_desc=file_name_desc,
  422. status=status
  423. )
  424. db.add(new_file)
  425. db.commit()
  426. db.refresh(new_file)
  427. for file in form_data.drillPicture:
  428. file_name = file.url
  429. file_name_desc = file.name
  430. status = file.status
  431. new_file = EmergencyFile(
  432. file_id = new_guid(),
  433. foreign_key = new_drill.drill_id,
  434. from_scenario = 'emergencyPlans_drill_pic',
  435. file_name=file_name,
  436. file_name_desc = file_name_desc,
  437. status = status
  438. )
  439. db.add(new_file)
  440. db.commit()
  441. db.refresh(new_file)
  442. # 返回创建成功的响应
  443. return {
  444. "code": 200,
  445. "msg": "演练创建成功",
  446. "data": None
  447. }
  448. except Exception as e:
  449. # 处理异常
  450. raise HTTPException(status_code=500, detail=str(e))
  451. @router.delete('/drill/delete/{drillUid}')
  452. async def delete_emergency_drill(
  453. drillUid: str,
  454. db: Session = Depends(get_db)
  455. ):
  456. try:
  457. # 提取请求数据
  458. query = db.query(EmergencyDrill)
  459. query = query.filter(EmergencyDrill.del_flag != '2')
  460. query = query.filter(EmergencyDrill.drill_id == drillUid)
  461. drill = query.first()
  462. if not drill:
  463. detail = "演练不存在"
  464. raise HTTPException(status_code=404, detail="演练不存在")
  465. drill.del_flag = '2'
  466. # 更新到数据库会话并提交
  467. db.commit()
  468. db.refresh(drill) # 可选,如果需要刷新实例状态
  469. # 返回创建成功的响应
  470. return {
  471. "code": 200,
  472. "msg": "演练删除成功",
  473. "data": None
  474. }
  475. except Exception as e:
  476. # 处理异常
  477. if str(e) == '':
  478. e = detail
  479. raise HTTPException(status_code=500, detail=str(e))
  480. @router.get('/training/list')
  481. async def get_emergency_training_list(
  482. planNum: str = Query(None, description='预案编号'),
  483. page: int = Query(1, gt=0, description='页码'),
  484. pageSize: int = Query(5, gt=0, description='每页条目数量'),
  485. db: Session = Depends(get_db)
  486. ):
  487. try:
  488. # 构建查询
  489. query = db.query(EmergencyTrainingSession)
  490. query = query.filter(EmergencyTrainingSession.del_flag != '2')
  491. # 应用查询条件
  492. if planNum:
  493. query = query.filter(EmergencyTrainingSession.plan_number == planNum)
  494. else:
  495. return 'planNum不存在'
  496. # 计算总条目数
  497. total_items = query.count()
  498. # 执行分页查询
  499. emergency_training = query.offset((page - 1) * pageSize).limit(pageSize).all() #
  500. # print(emergency_drill)
  501. # 将查询结果转换为列表形式的字典
  502. emergency_training_list = [
  503. {
  504. "trainingId": training.training_id,
  505. "theme": training.training_theme,
  506. "unitName": training.training_unit,
  507. "peopleNum": "%s人"%training.participant_count,
  508. "trainingWay":training.training_method,
  509. "startTime":training.start_time.strftime('%Y-%m-%d %H:%M:%S'),
  510. "endTime": training.end_time.strftime('%Y-%m-%d %H:%M:%S'),
  511. "address": training.training_location,
  512. "Content":training.training_content
  513. }
  514. for training in emergency_training
  515. ]
  516. # 返回结果
  517. return {
  518. "code": 200,
  519. "msg": "成功",
  520. "data": emergency_training_list,
  521. "total": total_items,
  522. "page": page,
  523. "pageSize": pageSize,
  524. "totalPages": (total_items + pageSize - 1) // pageSize
  525. }
  526. except Exception as e:
  527. # 处理异常
  528. raise HTTPException(status_code=500, detail=str(e))
  529. class TrainingCreateForm(BaseModel):
  530. planId:str
  531. theme : str
  532. unitName : str
  533. trainingWay : str
  534. peopleNum: int
  535. startTime : str
  536. endTime : str
  537. Content :str
  538. address : str
  539. lon : float
  540. lat : float
  541. @router.post('/training/create')
  542. async def create_emergency_training(
  543. form_data:TrainingCreateForm,
  544. db: Session = Depends(get_db)
  545. ):
  546. try:
  547. # 创建新的预案记录
  548. new_training = EmergencyTrainingSession(
  549. training_id=new_guid(), # 假设使用 UUID 作为预案 UID
  550. training_theme=form_data.theme,
  551. training_unit=form_data.unitName,
  552. training_method=form_data.trainingWay,
  553. participant_count=form_data.peopleNum,
  554. start_time=form_data.startTime,
  555. end_time=form_data.endTime,
  556. training_content=form_data.Content,
  557. training_location=form_data.address,
  558. training_lon=form_data.lon,
  559. training_lat=form_data.lat,
  560. plan_number = form_data.planId
  561. )
  562. # 添加到数据库会话并提交
  563. db.add(new_training)
  564. db.commit()
  565. db.refresh(new_training) # 可选,如果需要刷新实例状态
  566. # 返回创建成功的响应
  567. return {
  568. "code": 200,
  569. "msg": "培训创建成功",
  570. "data": None
  571. }
  572. except Exception as e:
  573. # 处理异常
  574. raise HTTPException(status_code=500, detail=str(e))
  575. @router.delete('/training/delete/{trainingUid}')
  576. async def delete_emergency_training(
  577. trainingUid: str,
  578. db: Session = Depends(get_db)
  579. ):
  580. try:
  581. # 提取请求数据
  582. query = db.query(EmergencyTrainingSession)
  583. query = query.filter(EmergencyTrainingSession.del_flag != '2')
  584. query = query.filter(EmergencyTrainingSession.training_id == trainingUid)
  585. training = query.first()
  586. if not training:
  587. detail = "培训不存在"
  588. raise HTTPException(status_code=404, detail="培训不存在")
  589. training.del_flag = '2'
  590. # 更新到数据库会话并提交
  591. db.commit()
  592. db.refresh(training) # 可选,如果需要刷新实例状态
  593. # 返回创建成功的响应
  594. return {
  595. "code": 200,
  596. "msg": "培训删除成功",
  597. "data": None
  598. }
  599. except Exception as e:
  600. # 处理异常
  601. if str(e) == '':
  602. e = detail
  603. raise HTTPException(status_code=500, detail=str(e))