person.py 42 KB

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