person.py 42 KB

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