person.py 42 KB

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