person_new.py 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  1. from fastapi import APIRouter, Request, Depends, HTTPException, Query, BackgroundTasks
  2. from sqlalchemy.exc import IntegrityError
  3. from fastapi.responses import HTMLResponse, FileResponse
  4. from fastapi.responses import JSONResponse,StreamingResponse
  5. from database import get_db
  6. from sqlalchemy import text, exists, and_, or_, not_
  7. from sqlalchemy.orm import Session
  8. from models import *
  9. import json
  10. import random
  11. import os
  12. from sqlalchemy import create_engine, select
  13. from typing import Optional
  14. from utils.StripTagsHTMLParser import *
  15. from utils.three_proofing_responsible_util import *
  16. from utils.ry_system_util import *
  17. from common.db import db_event_management, db_user, db_area, db_emergency_plan
  18. from common.security import valid_access_token
  19. import traceback
  20. from utils import *
  21. from datetime import datetime, timedelta
  22. import pandas as pd
  23. import xlrd
  24. from common.db import db_dept
  25. from exceptions import AppException, HmacException
  26. from common.enc import mpfun, three_proofing_responsible_person_data
  27. from common.db import db_czrz
  28. from common.auth_user import *
  29. router = APIRouter()
  30. @router.post('/{zrlx}/create')
  31. async def create_contact(
  32. zrlx:str,
  33. request: Request,
  34. auth_user: AuthUser = Depends(find_auth_user),
  35. db: Session = Depends(get_db),
  36. body=Depends(remove_xss_json),
  37. user_id=Depends(valid_access_token)
  38. ):
  39. try:
  40. lx = '三防'
  41. if zrlx=='sf':
  42. lx = '三防'
  43. if zrlx=='sf1':
  44. lx = '森防'
  45. if zrlx=='wh':
  46. lx = '危化'
  47. if zrlx=='sf':
  48. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  49. # 提取请求数据
  50. unit_name = body['unit_name']
  51. name = body['name']
  52. area_code = body['area_code']
  53. area_info = id_get_area_info(db, body['area_code'])
  54. area_code2 = '440900000000'
  55. if area_info:
  56. area_code2 = area_info.area_code
  57. position = body['position']
  58. phone = body['phone']
  59. telephone= ''
  60. if 'telephone' in body:
  61. telephone=body['telephone']
  62. order_num = -1
  63. if 'order_num'in body:
  64. order_num=body['order_num']
  65. unit_id = db_dept.get_dept_id_by_name(db, unit_name)
  66. user_id_1 = db_user.get_user_id_by_phonenumber(db,phone)
  67. # 创建新的记录
  68. new_person = ThreeProofingResponsiblePerson(
  69. unit_id=unit_id,
  70. unit_name=unit_name,
  71. name=name,
  72. area_code2=area_code2,
  73. area_code=area_code,
  74. position=position,
  75. phone=phone,
  76. responsible_type= lx,
  77. telephone=telephone,
  78. user_id = user_id_1,
  79. order_num=order_num,
  80. create_by=user_id
  81. )
  82. # 添加到数据库会话并提交
  83. type_list = body['type_list']
  84. if isinstance(type_list,list) and len(type_list)>0:
  85. db.add(new_person)
  86. db.commit()
  87. three_proofing_responsible_person_data.sign_table()
  88. else:
  89. return JSONResponse(status_code=404,content={
  90. 'code': 404,
  91. 'msg': '责任类型不能为空'
  92. })
  93. try:
  94. for type_info in type_list:
  95. type_parent_id = type_info['type_parent_id']#get_type_parent_id_by_type_id(db,type_id)
  96. for type_id in type_info['children']:
  97. new_person_type = ThreeProofingResponsiblePersonType(
  98. type_parent_id = type_parent_id,
  99. type_id = type_id,
  100. person_id = new_person.id,
  101. create_by=user_id
  102. )
  103. db.add(new_person_type)
  104. if type_parent_id in ('5','7','9'):
  105. if 'children2' in type_info:
  106. for other_type_id in type_info['children2']:
  107. new_person_other_type = ThreeProofingResponsiblePersonOtherType(
  108. type_parent_id=type_parent_id,
  109. other_type_id=other_type_id,
  110. person_id=new_person.id,
  111. create_by=user_id
  112. )
  113. db.add(new_person_other_type)
  114. if type_parent_id in ('4','5','7','10','11'):
  115. dept_name = None
  116. if 'dept_name' in type_info:
  117. dept_name = type_info['dept_name']
  118. other_type_2_name = None
  119. if 'other_type_2_name' in type_info:
  120. other_type_2_name = type_info['other_type_2_name']
  121. denger_point_name = None
  122. if 'denger_point_name' in type_info:
  123. denger_point_name = type_info['denger_point_name']
  124. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  125. type_parent_id = type_parent_id,
  126. dept_name = dept_name,
  127. other_type_2_name = other_type_2_name,
  128. denger_point_name = denger_point_name,
  129. person_id = new_person.id,
  130. create_by=user_id
  131. )
  132. db.add(new_person_other_info)
  133. except:
  134. db.rollback()
  135. traceback.print_exc()
  136. new_person.del_flag='2'
  137. db.commit()
  138. db_czrz.log(db, auth_user, "系统管理", f"后台管理新建三防责任人管理人员信息成功", request.client.host)
  139. # 返回创建成功的响应
  140. return {
  141. "code": 200,
  142. "msg": "创建成功",
  143. "data": None
  144. }
  145. except Exception as e:
  146. # 处理异常
  147. db.rollback()
  148. traceback.print_exc()
  149. raise HTTPException(status_code=500, detail=str(e))
  150. @router.put('/location_update')
  151. async def update_contact(
  152. request: Request,
  153. auth_user: AuthUser = Depends(find_auth_user),
  154. db: Session = Depends(get_db),
  155. body=Depends(remove_xss_json),
  156. user_id=Depends(valid_access_token)
  157. ):
  158. try:
  159. query = db.query(ThreeProofingResponsiblePerson)
  160. query = query.filter(ThreeProofingResponsiblePerson.del_flag == '0')
  161. query = query.filter(ThreeProofingResponsiblePerson.user_id == user_id)
  162. for info in query.all():
  163. info.longitude = body['longitude']
  164. info.latitude = body['latitude']
  165. info.location_time = datetime.now
  166. db.commit()
  167. except Exception as e:
  168. # 处理异常
  169. db.rollback()
  170. traceback.print_exc()
  171. raise HTTPException(status_code=500, detail=str(e))
  172. @router.put('/{zrlx}/update')
  173. async def update_contact(
  174. zrlx:str,
  175. request: Request,
  176. auth_user: AuthUser = Depends(find_auth_user),
  177. db: Session = Depends(get_db),
  178. body=Depends(remove_xss_json),
  179. user_id=Depends(valid_access_token)
  180. ):
  181. try:
  182. lx = '三防'
  183. if zrlx=='sf':
  184. lx = '三防'
  185. if zrlx=='sf1':
  186. lx = '森防'
  187. if zrlx=='wh':
  188. lx = '危化'
  189. if zrlx=='sf':
  190. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  191. # 提取请求数据
  192. id = body['id']
  193. person = get_person_info_by_id(db,id)
  194. if not person:
  195. return JSONResponse(status_code=404, content={
  196. 'errcode': 404,
  197. 'errmsg': '责任人不存在'
  198. })
  199. person.unit_name = body['unit_name']
  200. person.name = body['name']
  201. person.area_code = body['area_code']
  202. area_info = id_get_area_info(db, body['area_code'])
  203. if area_info:
  204. person.area_code2 = area_info.area_code
  205. person.position = body['position']
  206. person.phone = mpfun.enc_data(body['phone'])
  207. if 'telephone' in body:
  208. person.telephone = mpfun.enc_data(body['telephone'])
  209. person.order_num = body['order_num']
  210. if body['order_num']=='':
  211. person.order_num = -1
  212. person.unit_id = db_dept.get_dept_id_by_name(db, body['unit_name'])
  213. person.update_by = user_id
  214. person.update_time = datetime.now()
  215. person.sign = three_proofing_responsible_person_data.get_sign_hmac(person)
  216. type_list = body['type_list']
  217. old_person_type_list=get_person_type_by_person_id(db,person.id)
  218. for old_person_type in old_person_type_list:
  219. old_person_type.del_flag='2'
  220. old_person_other_info_list = get_person_other_info_by_person_id(db,person.id)
  221. for old_person_other_info in old_person_other_info_list:
  222. old_person_other_info.del_flag = '2'
  223. old_person_other_type_list = get_person_other_type_by_person_id(db,person.id)
  224. for old_person_other_type in old_person_other_type_list:
  225. old_person_other_type.del_flag = '2'
  226. for type_info in type_list:
  227. type_parent_id = type_info['type_parent_id'] # get_type_parent_id_by_type_id(db,type_id)
  228. for type_id in type_info['children']:
  229. new_person_type = ThreeProofingResponsiblePersonType(
  230. type_parent_id=type_parent_id,
  231. type_id=type_id,
  232. person_id=id,
  233. create_by=user_id
  234. )
  235. db.add(new_person_type)
  236. if type_parent_id in ('5', '7', '9'):
  237. if 'children2' in type_info:
  238. for other_type_id in type_info['children2']:
  239. new_person_other_type = ThreeProofingResponsiblePersonOtherType(
  240. type_parent_id=type_parent_id,
  241. other_type_id=other_type_id,
  242. person_id=person.id,
  243. create_by=user_id
  244. )
  245. db.add(new_person_other_type)
  246. if type_parent_id in ('4', '5', '7', '10', '11'):
  247. dept_name = None
  248. if 'dept_name' in type_info:
  249. dept_name = type_info['dept_name']
  250. other_type_2_name = None
  251. if 'other_type_2_name' in type_info:
  252. other_type_2_name = type_info['other_type_2_name']
  253. denger_point_name = None
  254. if 'denger_point_name' in type_info:
  255. denger_point_name = type_info['denger_point_name']
  256. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  257. type_parent_id=type_parent_id,
  258. dept_name=dept_name,
  259. other_type_2_name=other_type_2_name,
  260. denger_point_name=denger_point_name,
  261. person_id=person.id,
  262. create_by=user_id
  263. )
  264. db.add(new_person_other_info)
  265. # 更新到数据库会话并提交
  266. db.commit()
  267. db_czrz.log(db, auth_user, "系统管理", f"后台管理更新三防责任人管理人员信息成功", request.client.host)
  268. # 返回创建成功的响应
  269. return {
  270. "code": 200,
  271. "msg": "更新成功",
  272. "data": None
  273. }
  274. except Exception as e:
  275. # 处理异常
  276. db.rollback()
  277. traceback.print_exc()
  278. raise HTTPException(status_code=500, detail=str(e))
  279. @router.get('/{zrlx}/list')
  280. async def get_emergency_contact_list(
  281. zrlx:str,
  282. type_parent_id: str = Query(None, description='单位名称'),
  283. area_code:str = Query(None, description='单位名称'),
  284. Name: str = Query(None, description='联系人'),
  285. page: int = Query(1, gt=0, description='页码'),
  286. pageSize: int = Query(10, gt=0, description='每页条目数量'),
  287. db: Session = Depends(get_db),
  288. user_id=Depends(valid_access_token)
  289. ):
  290. try:
  291. lx = '三防'
  292. if zrlx=='sf':
  293. lx = '三防'
  294. if zrlx=='sf1':
  295. lx = '森防'
  296. if zrlx=='wh':
  297. lx = '危化'
  298. if zrlx=='sf':
  299. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  300. # 构建查询
  301. query = db.query(ThreeProofingResponsiblePerson)
  302. query = query.filter(ThreeProofingResponsiblePerson.del_flag == '0')
  303. query = query.filter(ThreeProofingResponsiblePerson.responsible_type.like(f'%{lx}%'))
  304. # 应用查询条件
  305. if type_parent_id:
  306. person_list = get_person_list_by_type_parent_id(db,type_parent_id)
  307. query = query.filter(ThreeProofingResponsiblePerson.id.in_(person_list))
  308. if Name:
  309. query = query.filter(ThreeProofingResponsiblePerson.name.like(f'%{Name}%'))
  310. def get_area_chli(area_list : list,parent_id : int):
  311. areas = parent_id_get_area_info(db,parent_id)
  312. if areas:
  313. for area in areas:
  314. area_list.append(area.id)
  315. get_area_chli(area_list, area.id)
  316. return area_list
  317. # if area_code:
  318. # query = query.filter(ThreeProofingResponsiblePerson.area_code.in_(get_area_chli([area_code],area_code)))
  319. # '''440900000000'''
  320. if area_code:
  321. area_info = id_get_area_info(db,area_code)
  322. if area_info:
  323. area_code = area_info.area_code
  324. area_code=area_code.replace('0000000000','').replace('00000000','').replace('000000','').replace('000','')
  325. query = query.filter(ThreeProofingResponsiblePerson.area_code2.like(f'%{area_code}%') )
  326. # if area_code:
  327. # query = query.filter(ThreeProofingResponsiblePerson.area_code==area_code)
  328. # 计算总条目数
  329. total_items = query.count()
  330. # 排序
  331. query = query.order_by(ThreeProofingResponsiblePerson.order_num.asc())
  332. query = query.order_by(ThreeProofingResponsiblePerson.create_time.desc())
  333. # 执行分页查询
  334. contact_infos = query.offset((page - 1) * pageSize).limit(pageSize).all()
  335. for info in contact_infos:
  336. if three_proofing_responsible_person_data.sign_valid_row(info) == False:
  337. raise HmacException(500, "三防责任人管理人员信息表验证异常,已被非法篡改")
  338. # 将查询结果转换为列表形式的字典
  339. contact_infos_list = []
  340. for info in contact_infos:
  341. type_parent_id_list = get_type_parent_id_by_person_id(db,info.id)
  342. type_parent_list = []
  343. type_parent_list2 = []
  344. for type_parent in type_parent_id_list:
  345. if type_parent not in type_parent_list2:
  346. dict_data = get_dict_data_info(db,'three_proofing',type_parent)
  347. type_parent_list2.append(type_parent)
  348. type_parent_list.append({"type_parent_id":type_parent,"type_parent":dict_data.dict_label})
  349. area_info = id_get_area_info(db,info.area_code)
  350. user_info = user_id_get_user_info(db,info.create_by)
  351. nick_name = ''
  352. if user_info:
  353. nick_name = user_info.nick_name
  354. area_list = db_area.id_get_area_parent_list(db,info.area_code,[])
  355. if info.order_num ==-1:
  356. order_num = ''
  357. else:
  358. order_num = str(info.order_num)
  359. contact_infos_list.append({
  360. "id": info.id,
  361. "unit_id": info.unit_id,
  362. "unit_name": info.unit_name,
  363. "name": info.name,
  364. "area_list":area_list,
  365. "area_code": info.area_code,
  366. "area_name": area_info.area_name,
  367. "position": info.position,
  368. "phone": mpfun.dec_data(info.phone),
  369. "telephone": mpfun.dec_data(info.telephone),
  370. "order_num": order_num,
  371. "online_status":'0',
  372. "create_time": info.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  373. "create_by":info.create_by,
  374. "create_user":nick_name,
  375. "type_parent_list":type_parent_list
  376. })
  377. # 返回结果+
  378. return {
  379. "code": 200,
  380. "msg": "成功",
  381. "data": contact_infos_list,
  382. "total": total_items
  383. }
  384. except HmacException as e:
  385. return {
  386. "code": e.code,
  387. "msg": e.msg
  388. }
  389. except Exception as e:
  390. # 处理异常
  391. traceback.print_exc()
  392. raise HTTPException(status_code=500, detail=str(e))
  393. @router.get('/{zrlx}/export')
  394. async def get_emergency_contact_list(
  395. zrlx:str,
  396. request: Request,
  397. type_parent_id: str = Query(None, description='单位名称'),
  398. area_code: str = Query(None, description='单位名称'),
  399. Name: str = Query(None, description='联系人'),
  400. page: int = Query(1, gt=0, description='页码'),
  401. pageSize: int = Query(10, gt=0, description='每页条目数量'),
  402. db: Session = Depends(get_db),
  403. auth_user: AuthUser = Depends(find_auth_user),
  404. user_id=Depends(valid_access_token)
  405. ):
  406. try:
  407. lx = '三防'
  408. if zrlx=='sf':
  409. lx = '三防'
  410. if zrlx=='sf1':
  411. lx = '森防'
  412. if zrlx=='wh':
  413. lx = '危化'
  414. if zrlx=='sf':
  415. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  416. # 构建查询
  417. query = db.query(ThreeProofingResponsiblePerson)
  418. query = query.filter(ThreeProofingResponsiblePerson.del_flag == '0')
  419. query = query.filter(ThreeProofingResponsiblePerson.responsible_type.like(f'%{lx}%'))
  420. # 应用查询条件
  421. if type_parent_id:
  422. person_list = get_person_list_by_type_parent_id(db, type_parent_id)
  423. query = query.filter(ThreeProofingResponsiblePerson.id.in_(person_list))
  424. if Name:
  425. query = query.filter(ThreeProofingResponsiblePerson.name.like(f'%{Name}%'))
  426. def get_area_chli(area_list: list, parent_id: int):
  427. areas = parent_id_get_area_info(db, parent_id)
  428. if areas:
  429. for area in areas:
  430. area_list.append(area.id)
  431. get_area_chli(area_list, area.id)
  432. return area_list
  433. # if area_code:
  434. # query = query.filter(ThreeProofingResponsiblePerson.area_code.in_(get_area_chli([area_code],area_code)))
  435. # '''440900000000'''
  436. if area_code:
  437. area_info = id_get_area_info(db, area_code)
  438. if area_info:
  439. area_code = area_info.area_code
  440. area_code = area_code.replace('0000000000', '').replace('00000000', '').replace('000000', '').replace(
  441. '000', '')
  442. query = query.filter(ThreeProofingResponsiblePerson.area_code2.like(f'%{area_code}%'))
  443. # if area_code:
  444. # query = query.filter(ThreeProofingResponsiblePerson.area_code==area_code)
  445. # 计算总条目数
  446. total_items = query.count()
  447. # 排序
  448. query = query.order_by(ThreeProofingResponsiblePerson.order_num.asc())
  449. query = query.order_by(ThreeProofingResponsiblePerson.create_time.desc())
  450. # 执行分页查询
  451. contact_infos = query.all()
  452. for info in contact_infos:
  453. if three_proofing_responsible_person_data.sign_valid_row(info) == False:
  454. raise HmacException(500, "三防责任人管理人员信息表验证异常,已被非法篡改")
  455. # 将查询结果转换为列表形式的字典
  456. contact_infos_list = []
  457. for info in contact_infos:
  458. type_parent_id_list = get_type_parent_id_by_person_id(db, info.id)
  459. type_parent_list = []
  460. type_parent_list2 = []
  461. for type_parent in type_parent_id_list:
  462. if type_parent not in type_parent_list2:
  463. dict_data = get_dict_data_info(db, 'three_proofing', type_parent)
  464. type_parent_list2.append(type_parent)
  465. type_parent_list.append(dict_data.dict_label)
  466. area_info = id_get_area_info(db, info.area_code)
  467. user_info = user_id_get_user_info(db, info.create_by)
  468. area_list = db_area.id_get_area_parent_list(db, info.area_code, [])
  469. area_list = '/'.join([i['label'] for i in area_list])
  470. if info.order_num == -1:
  471. order_num = ''
  472. else:
  473. order_num = str(info.order_num)
  474. contact_infos_list.append({
  475. "id": info.id,
  476. "单位ID": info.unit_id,
  477. "单位名称": info.unit_name,
  478. "姓名": info.name,
  479. "区划列表": area_list,
  480. "区划编码": info.area_code,
  481. "区划": area_info.area_name,
  482. "职务": info.position,
  483. "手机号码": mpfun.dec_data(info.phone),
  484. "办公电话": mpfun.dec_data(info.telephone),
  485. "排序顺序": order_num,
  486. "创建时间": info.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  487. "责任类型": '、'.join(type_parent_list)
  488. })
  489. # 返回结果+
  490. import pandas as pd
  491. from io import BytesIO
  492. # 将查询结果转换为 DataFrame
  493. df = pd.DataFrame(contact_infos_list)
  494. # 将 DataFrame 导出为 Excel 文件
  495. output = BytesIO()
  496. with pd.ExcelWriter(output, engine='openpyxl') as writer:
  497. df.to_excel(writer, index=False)
  498. # 设置响应头
  499. output.seek(0)
  500. from urllib.parse import quote
  501. encoded_filename = f'三防责任人清单{datetime.now().strftime("%Y%m%d%H%mi%s")}.xlsx'
  502. encoded_filename = quote(encoded_filename, encoding='utf-8')
  503. headers = {
  504. 'Content-Disposition': f'attachment; filename*=UTF-8\'\'{encoded_filename}',
  505. 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  506. }
  507. db_czrz.log(db, auth_user, "三防责任人管理", f"三防责任人清单导出数据成功", request.client.host)
  508. # 返回文件流
  509. return StreamingResponse(output, headers=headers)
  510. #
  511. # return {
  512. # "code": 200,
  513. # "msg": "成功",
  514. # "data": contact_infos_list,
  515. # "total": total_items
  516. # }
  517. except HmacException as e:
  518. return JSONResponse(status_code=e.code, content={
  519. "code": e.code,
  520. "msg": e.msg
  521. })
  522. # return {
  523. # "code": e.code,
  524. # "msg": e.msg
  525. # }
  526. except Exception as e:
  527. # 处理异常
  528. traceback.print_exc()
  529. return JSONResponse(status_code=500, content={"code": 500, "msg": f"Internal server error: {str(e)}"})
  530. @router.get('/{zrlx}/info/{id}')
  531. async def get_emergency_contact_id_info(
  532. zrlx:str,
  533. id: str,
  534. db: Session = Depends(get_db),
  535. user_id=Depends(valid_access_token)
  536. ):
  537. try:
  538. lx = '三防'
  539. if zrlx=='sf':
  540. lx = '三防'
  541. if zrlx=='sf1':
  542. lx = '森防'
  543. if zrlx=='wh':
  544. lx = '危化'
  545. if zrlx=='sf':
  546. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  547. contact = get_person_info_by_id(db,id)
  548. if not contact:
  549. return JSONResponse(status_code=404, content={
  550. 'errcode': 404,
  551. 'errmsg': '联系人不存在'
  552. })
  553. # 将查询结果转换为列表形式的字典
  554. area_info = id_get_area_info(db,contact.area_code)
  555. user_info = user_id_get_user_info(db,contact.create_by)
  556. nick_name = ''
  557. if user_info:
  558. nick_name = user_info.nick_name
  559. area_list = db_area.id_get_area_parent_list(db, contact.area_code, [])
  560. if contact.order_num == -1:
  561. order_num = ''
  562. else:
  563. order_num = str(contact.order_num)
  564. contact_result = {
  565. "id": contact.id,
  566. "unit_id": contact.unit_id,
  567. "unit_name": contact.unit_name,
  568. "name": contact.name,
  569. "area_list":area_list,
  570. "area_code":contact.area_code,
  571. "area_name": area_info.area_name,
  572. "position": contact.position,
  573. "phone": mpfun.dec_data(contact.phone),
  574. "telephone":mpfun.dec_data(contact.telephone),
  575. "order_num":order_num,
  576. "online_status":'0',
  577. "create_time": contact.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  578. "create_by":contact.create_by,
  579. "create_user":nick_name,
  580. "type_list":[]
  581. }
  582. type_parent_id_list = []
  583. type_list = get_person_type_by_person_id(db,contact.id)
  584. for type_info in type_list:
  585. if type_info.type_parent_id not in type_parent_id_list:
  586. type_parent_id_list.append(type_info.type_parent_id)
  587. for type_parent_id in type_parent_id_list:
  588. dict_data = get_dict_data_info(db, 'three_proofing', type_parent_id)
  589. type_data = {"type_parent_id": type_parent_id, "type_parent": dict_data.dict_label,"children":[],"labelData":[]}
  590. for type_info in get_person_type_by_person_id_and_type_parent_id(db,contact.id,type_parent_id):
  591. type_data_info = get_type_info_by_id(db,type_info.type_id)
  592. # type_data['children'].append({"id": type_info.type_id, "label": type_data_info.type_name})
  593. type_data['children'].append(type_info.type_id)
  594. type_data['labelData'].append( type_data_info.type_name)
  595. other_info = get_person_other_info_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  596. if other_info:
  597. type_data['dept_name'] = other_info.dept_name
  598. type_data['denger_point_name'] = other_info.denger_point_name
  599. type_data['other_type_2_name'] = other_info.other_type_2_name
  600. other_type_list = get_person_other_type_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  601. if other_type_list:
  602. type_data['children2'] = []
  603. type_data['other_type_label'] = []
  604. for other_type in other_type_list:
  605. other_type_info = get_other_type_info_by_id(db, other_type.other_type_id)
  606. label= ''
  607. if other_type_info:
  608. label = other_type_info.type_name
  609. # type_data['children2'].append({"id": other_type.other_type_id, "label": label})
  610. type_data['children2'].append(other_type.other_type_id)
  611. type_data['other_type_label'].append(label)
  612. contact_result['type_list'].append(type_data)
  613. # 返回结果
  614. return {
  615. "code": 200,
  616. "msg": "成功",
  617. "data": contact_result
  618. }
  619. except Exception as e:
  620. # 处理异常
  621. traceback.print_exc()
  622. raise HTTPException(status_code=500, detail=str(e))
  623. @router.delete('/{zrlx}/delete')
  624. async def delete_emergency_plans(
  625. zrlx:str,
  626. request: Request,
  627. ids: list,
  628. db: Session = Depends(get_db),
  629. body=Depends(remove_xss_json),
  630. auth_user: AuthUser = Depends(find_auth_user),
  631. user_id=Depends(valid_access_token)
  632. ):
  633. try:
  634. lx = '三防'
  635. if zrlx=='sf':
  636. lx = '三防'
  637. if zrlx=='sf1':
  638. lx = '森防'
  639. if zrlx=='wh':
  640. lx = '危化'
  641. if zrlx=='sf':
  642. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  643. # 提取请求数据
  644. query = db.query(ThreeProofingResponsiblePerson)
  645. query = query.filter(ThreeProofingResponsiblePerson.del_flag != '2')
  646. query = query.filter(ThreeProofingResponsiblePerson.id.in_(ids))
  647. contacts = query.all()
  648. if not contacts:
  649. return JSONResponse(status_code=404, content={
  650. 'errcode': 404,
  651. 'errmsg': '联系人不存在'
  652. })
  653. for contact in contacts:
  654. contact.del_flag = '2'
  655. contact.update_by = user_id
  656. contact.update_time = datetime.now()
  657. contact.sign = three_proofing_responsible_person_data.get_sign_hmac(contact)
  658. # 更新到数据库会话并提交
  659. db.commit()
  660. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除三防责任人管理人员信息成功", request.client.host)
  661. # 返回创建成功的响应
  662. return {
  663. "code": 200,
  664. "msg": "删除成功",
  665. "data": None
  666. }
  667. except Exception as e:
  668. # 处理异常
  669. traceback.print_exc()
  670. raise HTTPException(status_code=500, detail=str(e))
  671. @router.delete('/{zrlx}/delete/{id}')
  672. async def delete_emergency_plans(
  673. zrlx:str,
  674. request: Request,
  675. id: int,
  676. db: Session = Depends(get_db),
  677. body=Depends(remove_xss_json),
  678. auth_user: AuthUser = Depends(find_auth_user),
  679. user_id=Depends(valid_access_token)
  680. ):
  681. try:
  682. lx = '三防'
  683. if zrlx=='sf':
  684. lx = '三防'
  685. if zrlx=='sf1':
  686. lx = '森防'
  687. if zrlx=='wh':
  688. lx = '危化'
  689. if zrlx=='sf':
  690. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  691. contact = get_person_info_by_id(db, id)
  692. if not contact:
  693. return JSONResponse(status_code=404, content={
  694. 'errcode': 404,
  695. 'errmsg': '联系人不存在'
  696. })
  697. contact.del_flag = '2'
  698. contact.update_by = user_id
  699. contact.update_time = datetime.now()
  700. contact.sign = three_proofing_responsible_person_data.get_sign_hmac(contact)
  701. # 更新到数据库会话并提交
  702. db.commit()
  703. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除三防责任人管理人员信息成功", request.client.host)
  704. # 返回创建成功的响应
  705. return {
  706. "code": 200,
  707. "msg": "删除成功",
  708. "data": None
  709. }
  710. except Exception as e:
  711. # 处理异常
  712. traceback.print_exc()
  713. raise HTTPException(status_code=500, detail=str(e))
  714. def string_type_parent_id_create_data(db,string,type_parent_id,file_info,new_person,user_id,row) :
  715. type_name_list = [i for i in string.split(',')]
  716. reslte = []
  717. for type_name in type_name_list:
  718. type_id = get_type_id_by_type_parent_id_and_type_name(db, type_parent_id, type_name)
  719. if type_id:
  720. new_person_type = ThreeProofingResponsiblePersonType(
  721. type_parent_id=type_parent_id,
  722. type_id=type_id,
  723. person_id=new_person.id,
  724. create_by=user_id
  725. )
  726. reslte.append(new_person_type)
  727. else:
  728. file_info.remark= file_info.remark+f'\n行<{row+1}>责任类别未找到<{type_name}>'
  729. return reslte ,False
  730. return reslte ,True
  731. def other_type_string_type_parent_id_create_data(db,string,type_parent_id,file_info,new_person,user_id,row) :
  732. type_name_list = [i for i in string.split(',')]
  733. reslte = []
  734. for other_type_name in type_name_list:
  735. other_type_id = get_other_type_id_by_type_parent_id_and_other_type_name(db, type_parent_id, other_type_name)
  736. if other_type_id:
  737. new_person_type = ThreeProofingResponsiblePersonOtherType(
  738. type_parent_id=type_parent_id,
  739. other_type_id=other_type_id,
  740. person_id=new_person.id,
  741. create_by=user_id
  742. )
  743. reslte.append(new_person_type)
  744. else:
  745. file_info.remark= file_info.remark+f'\n行<{row+1}>责任类别未找到<{other_type_name}>'
  746. file_info.error_num +=1
  747. return reslte ,False
  748. return reslte ,True
  749. def import_data(db,file_path,user_id,file_info):
  750. import_status = True
  751. try:
  752. book = xlrd.open_workbook(file_path)
  753. sheet = book.sheet_by_index(0)
  754. except :
  755. file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
  756. file_info.error_num +=1
  757. import_status = False
  758. data = []
  759. for row in range(4, sheet.nrows):
  760. # 姓名
  761. name = sheet.cell(row, 0).value
  762. if name == '':
  763. file_info.remark = file_info.remark+f'\n行<{row+1}>姓名不能为空<{name}>'
  764. file_info.error_num +=1
  765. import_status = False
  766. # 所属单位
  767. unit_name = sheet.cell(row, 1).value
  768. if unit_name == '':
  769. file_info.remark = file_info.remark+f'\n行<{row+1}>所属单位不能为空<{unit_name}>'
  770. file_info.error_num +=1
  771. import_status = False
  772. unit_id = db_dept.get_dept_id_by_name(db, unit_name)
  773. # 职务
  774. position = sheet.cell(row, 2).value
  775. if position =='':
  776. file_info.remark = file_info.remark+f'\n行<{row+1}>职务不能为空<{position}>'
  777. file_info.error_num +=1
  778. import_status = False
  779. # 电话号码(如有多个手机号请用“,”分隔)
  780. phone = str(sheet.cell(row, 3).value)
  781. if phone =='':
  782. file_info.remark = file_info.remark+f'\n行<{row+1}>电话号码不能为空<{phone}>'
  783. file_info.error_num +=1
  784. import_status = False
  785. phone_list = [i for i in phone.split(',')]
  786. user_id_1=-1
  787. for i in phone_list:
  788. user_id_1 = db_user.get_user_id_by_phonenumber(db, i)
  789. if user_id_1 != -1:
  790. break
  791. # 办公电话
  792. # (选填,格式:区号-电话号码)
  793. telephone = sheet.cell(row, 4).value
  794. # 排位顺序
  795. # (选填,请输入排序号1-9999,排序号数值越小越靠前,不填则默认排至最末)
  796. order_num = sheet.cell(row, 5).value
  797. if order_num == '':
  798. order_num=-1
  799. area_name = sheet.cell(row, 7).value
  800. if area_name=='':
  801. area_code=2
  802. area_code2='440900000000'
  803. else:
  804. area_code=get_area_info_by_area_name(db,area_name)
  805. if area_code is None:
  806. file_info.remark = file_info.remark+f'\n行<{row+1}>责任区域未找到'
  807. file_info.error_num +=1
  808. import_status = False
  809. area_code2 = area_code.area_code
  810. area_code = area_code.id
  811. new_person = ThreeProofingResponsiblePerson(
  812. unit_id=unit_id,
  813. unit_name=unit_name,
  814. name=name,
  815. area_code2=area_code2,
  816. area_code=area_code,
  817. position=position,
  818. phone=phone.replace,
  819. telephone=telephone,
  820. user_id=user_id_1,
  821. order_num=order_num,
  822. create_by=user_id,
  823. sign = ''
  824. )
  825. data.append(new_person)
  826. db.add(new_person)
  827. db.commit()
  828. # 党委政府
  829. a1 = sheet.cell(row, 6).value
  830. if a1 != '':
  831. new_type_list,status = string_type_parent_id_create_data(db,a1,'1',file_info,new_person,user_id,row)
  832. if status:
  833. db.add_all(new_type_list)
  834. data +=new_type_list
  835. else:
  836. import_status = status
  837. # type_name_list = [i for i in a1.split(',')]
  838. # for type_name in type_name_list:
  839. # type_id = get_type_id_by_type_parent_id_and_type_name(db, '1', type_name)
  840. # if type_id:
  841. # pass
  842. # 三防指挥部
  843. b1 = sheet.cell(row, 8).value
  844. if b1 != '':
  845. new_type_list,status = string_type_parent_id_create_data(db,b1,'2',file_info,new_person,user_id,row)
  846. if status:
  847. db.add_all(new_type_list)
  848. data +=new_type_list
  849. else:
  850. import_status = status
  851. b2 = sheet.cell(row, 9).value
  852. # 应急部门
  853. c1 = sheet.cell(row, 10).value
  854. if c1!='':
  855. new_type_list, status = string_type_parent_id_create_data(db, c1, '3', file_info, new_person, user_id,row)
  856. if status:
  857. db.add_all(new_type_list)
  858. data += new_type_list
  859. else:
  860. import_status = status
  861. # 成员单位
  862. d1 = sheet.cell(row, 11).value
  863. if d1!='':
  864. new_type_list, status = string_type_parent_id_create_data(db, d1, '4', file_info, new_person, user_id,row)
  865. if status:
  866. db.add_all(new_type_list)
  867. data += new_type_list
  868. else:
  869. import_status = status
  870. d2 = sheet.cell(row, 12).value
  871. if d2!='':
  872. dept_name = d2
  873. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  874. type_parent_id='4',
  875. dept_name=dept_name,
  876. person_id=new_person.id,
  877. create_by=user_id
  878. )
  879. db.add(new_person_other_info)
  880. data.append(new_person_other_info)
  881. # 重点部门
  882. e1 = sheet.cell(row, 13).value
  883. if e1!='':
  884. new_type_list, status = string_type_parent_id_create_data(db, e1, '5', file_info, new_person, user_id,row)
  885. if status:
  886. db.add_all(new_type_list)
  887. data += new_type_list
  888. else:
  889. import_status = status
  890. e2 = sheet.cell(row, 14).value
  891. if e2!='':
  892. dept_name = e2
  893. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  894. type_parent_id='5',
  895. dept_name=dept_name,
  896. person_id=new_person.id,
  897. create_by=user_id
  898. )
  899. db.add(new_person_other_info)
  900. data.append(new_person_other_info)
  901. e3 = sheet.cell(row, 15).value
  902. if e3!='':
  903. new_type_list,status = other_type_string_type_parent_id_create_data(db,e3,'5',file_info,new_person,user_id,row)
  904. if status:
  905. db.add_all(new_type_list)
  906. data +=new_type_list
  907. else:
  908. import_status = status
  909. # 行政村
  910. f1 = sheet.cell(row, 16).value
  911. if f1!='':
  912. new_type_list, status = string_type_parent_id_create_data(db, f1, '6', file_info, new_person, user_id,row)
  913. if status:
  914. db.add_all(new_type_list)
  915. data += new_type_list
  916. else:
  917. import_status = status
  918. # 水利工程
  919. g1 = sheet.cell(row, 17).value
  920. if g1!='':
  921. new_type_list, status = string_type_parent_id_create_data(db, g1, '7', file_info, new_person, user_id,row)
  922. if status:
  923. db.add_all(new_type_list)
  924. data += new_type_list
  925. else:
  926. import_status = status
  927. g2 = sheet.cell(row, 18).value
  928. if g2!='':
  929. dept_name = g2
  930. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  931. type_parent_id='7',
  932. dept_name=dept_name,
  933. person_id=new_person.id,
  934. create_by=user_id
  935. )
  936. db.add(new_person_other_info)
  937. data.append(new_person_other_info)
  938. g3 = sheet.cell(row, 19).value
  939. if g3!='':
  940. new_type_list, status = other_type_string_type_parent_id_create_data(db, g3, '11', file_info, new_person, user_id,
  941. row)
  942. if status:
  943. db.add_all(new_type_list)
  944. data += new_type_list
  945. else:
  946. import_status = status
  947. # 受威胁转移
  948. h1 = sheet.cell(row, 20).value
  949. if h1!='':
  950. new_type_list, status = string_type_parent_id_create_data(db, h1, '8', file_info, new_person, user_id,row)
  951. if status:
  952. db.add_all(new_type_list)
  953. data += new_type_list
  954. else:
  955. import_status = status
  956. # 抢险队伍
  957. j1 = sheet.cell(row, 21).value
  958. if j1!='':
  959. new_type_list, status = string_type_parent_id_create_data(db, j1, '9', file_info, new_person, user_id,row)
  960. if status:
  961. db.add_all(new_type_list)
  962. data += new_type_list
  963. else:
  964. import_status = status
  965. j2 = sheet.cell(row, 22).value
  966. if j2!='':
  967. new_type_list, status = other_type_string_type_parent_id_create_data(db, j2, '9', file_info, new_person, user_id,
  968. row)
  969. if status:
  970. db.add_all(new_type_list)
  971. data += new_type_list
  972. else:
  973. import_status = status
  974. # 地质灾害
  975. k1 = sheet.cell(row, 23).value
  976. if k1!='':
  977. new_type_list, status = string_type_parent_id_create_data(db, k1, '10', file_info, new_person, user_id,row)
  978. if status:
  979. db.add_all(new_type_list)
  980. data += new_type_list
  981. else:
  982. import_status = status
  983. k2 = sheet.cell(row, 24).value
  984. if k2!='':
  985. denger_point_name = k2
  986. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  987. type_parent_id='10',
  988. denger_point_name=denger_point_name,
  989. person_id=new_person.id,
  990. create_by=user_id
  991. )
  992. db.add(new_person_other_info)
  993. data.append(new_person_other_info)
  994. # 其他
  995. l1 = sheet.cell(row, 25).value
  996. if l1!='':
  997. new_type_list, status = string_type_parent_id_create_data(db, l1, '11', file_info, new_person, user_id,row)
  998. if status:
  999. db.add_all(new_type_list)
  1000. data += new_type_list
  1001. else:
  1002. import_status = status
  1003. l2 = sheet.cell(row, 26).value
  1004. if l2!='':
  1005. other_type_2_name = l2
  1006. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  1007. type_parent_id='11',
  1008. other_type_2_name=other_type_2_name,
  1009. person_id=new_person.id,
  1010. create_by=user_id
  1011. )
  1012. db.add(new_person_other_info)
  1013. data.append(new_person_other_info)
  1014. db.commit()
  1015. if import_status == False:
  1016. # print(1111111)
  1017. for info in data:
  1018. db.delete(info)
  1019. file_info.status = 2
  1020. db.commit()
  1021. three_proofing_responsible_person_data.sign_table()
  1022. @router.post('/{zrlx}/createImport')
  1023. async def create_contact(
  1024. zrlx:str,
  1025. request: Request,
  1026. background_tasks: BackgroundTasks,
  1027. db: Session = Depends(get_db),
  1028. body=Depends(remove_xss_json),
  1029. auth_user: AuthUser = Depends(find_auth_user),
  1030. user_id=Depends(valid_access_token)
  1031. ):
  1032. try:
  1033. lx = '三防'
  1034. if zrlx=='sf':
  1035. lx = '三防'
  1036. if zrlx=='sf1':
  1037. lx = '森防'
  1038. if zrlx=='wh':
  1039. lx = '危化'
  1040. if zrlx=='sf':
  1041. return JSONResponse(status_code=404,content={"code":404,"msg":"责任人类型未查询到"})
  1042. # 提取请求数据
  1043. filename = body['filename']
  1044. file_name_desc = body['file_name_desc']
  1045. if len(filename) == 0:
  1046. raise Exception()
  1047. file_path = f'/data/upload/mergefile/uploads/{filename}'
  1048. # 检查文件是否存在
  1049. if not os.path.isfile(file_path):
  1050. return JSONResponse(status_code=404, content={
  1051. 'errcode': 404,
  1052. 'errmsg': f'{filename}不存在'
  1053. })
  1054. new_file = ThreeProofingResponsiblePersonImportFileStatus(
  1055. file_uuid=filename,
  1056. file_name = file_name_desc,
  1057. status = '1',
  1058. remark = '',
  1059. user_id=user_id
  1060. )
  1061. db.add(new_file)
  1062. db.commit()
  1063. background_tasks.add_task(import_data,db,file_path, user_id,new_file)
  1064. db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
  1065. # 返回创建成功的响应
  1066. return {
  1067. "code": 200,
  1068. "msg": "成功",
  1069. "data": None
  1070. }
  1071. except AppException as e:
  1072. return {
  1073. "code": 500,
  1074. "msg": e.msg
  1075. }
  1076. except Exception as e:
  1077. traceback.print_exc()
  1078. # 处理异常
  1079. db.rollback()
  1080. raise HTTPException(status_code=500, detail=str(e))