person.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. from fastapi import APIRouter, Request, Depends, HTTPException, Query
  2. from sqlalchemy.exc import IntegrityError
  3. from fastapi.responses import HTMLResponse, FileResponse
  4. from fastapi.responses import JSONResponse
  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. from common.db import db_dept
  24. from exceptions import AppException
  25. router = APIRouter()
  26. @router.post('/create')
  27. async def create_contact(
  28. db: Session = Depends(get_db),
  29. body=Depends(remove_xss_json),
  30. user_id=Depends(valid_access_token)
  31. ):
  32. try:
  33. # 提取请求数据
  34. unit_name = body['unit_name']
  35. name = body['name']
  36. area_code = body['area_code']
  37. position = body['position']
  38. phone = body['phone']
  39. telephone= ''
  40. if 'telephone' in body:
  41. telephone=body['telephone']
  42. order_num = -1
  43. if 'order_num'in body:
  44. order_num=body['order_num']
  45. unit_id = db_dept.get_dept_id_by_name(db, unit_name)
  46. user_id_1 = db_user.get_user_id_by_phonenumber(db,phone)
  47. # 创建新的预案记录
  48. new_person = ThreeProofingResponsiblePerson(
  49. unit_id=unit_id,
  50. unit_name=unit_name,
  51. name=name,
  52. area_code=area_code,
  53. position=position,
  54. phone=phone,
  55. telephone=telephone,
  56. user_id = user_id_1,
  57. order_num=order_num,
  58. create_by=user_id
  59. )
  60. # 添加到数据库会话并提交
  61. type_list = body['type_list']
  62. if isinstance(type_list,list) and len(type_list)>0:
  63. db.add(new_person)
  64. db.commit()
  65. else:
  66. return JSONResponse(status_code=404,content={
  67. 'code': 404,
  68. 'msg': '责任类型不能为空'
  69. })
  70. try:
  71. for type_info in type_list:
  72. type_parent_id = type_info['type_parent_id']#get_type_parent_id_by_type_id(db,type_id)
  73. for type_id in type_info['children']:
  74. new_person_type = ThreeProofingResponsiblePersonType(
  75. type_parent_id = type_parent_id,
  76. type_id = type_id,
  77. person_id = new_person.id,
  78. create_by=user_id
  79. )
  80. db.add(new_person_type)
  81. if type_parent_id in ('5','7','9'):
  82. if 'children2' in type_info:
  83. for other_type_id in type_info['children2']:
  84. new_person_other_type = ThreeProofingResponsiblePersonOtherType(
  85. type_parent_id=type_parent_id,
  86. other_type_id=other_type_id,
  87. person_id=new_person.id,
  88. create_by=user_id
  89. )
  90. db.add(new_person_other_type)
  91. if type_parent_id in ('4','5','7','10','11'):
  92. dept_name = None
  93. if 'dept_name' in type_info:
  94. dept_name = type_info['dept_name']
  95. other_type_2_name = None
  96. if 'other_type_2_name' in type_info:
  97. other_type_2_name = type_info['other_type_2_name']
  98. denger_point_name = None
  99. if 'denger_point_name' in type_info:
  100. denger_point_name = type_info['denger_point_name']
  101. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  102. type_parent_id = type_parent_id,
  103. dept_name = dept_name,
  104. other_type_2_name = other_type_2_name,
  105. denger_point_name = denger_point_name,
  106. person_id = new_person.id,
  107. create_by=user_id
  108. )
  109. db.add(new_person_other_info)
  110. except:
  111. db.rollback()
  112. traceback.print_exc()
  113. new_person.del_flag='2'
  114. db.commit()
  115. # 返回创建成功的响应
  116. return {
  117. "code": 200,
  118. "msg": "创建成功",
  119. "data": None
  120. }
  121. except Exception as e:
  122. # 处理异常
  123. db.rollback()
  124. traceback.print_exc()
  125. raise HTTPException(status_code=500, detail=str(e))
  126. @router.put('/update')
  127. async def update_contact(
  128. db: Session = Depends(get_db),
  129. body=Depends(remove_xss_json),
  130. user_id=Depends(valid_access_token)
  131. ):
  132. try:
  133. # 提取请求数据
  134. id = body['id']
  135. person = get_person_info_by_id(db,id)
  136. if not person:
  137. return JSONResponse(status_code=404, content={
  138. 'errcode': 404,
  139. 'errmsg': '责任人不存在'
  140. })
  141. person.unit_name = body['unit_name']
  142. person.name = body['name']
  143. person.area_code = body['area_code']
  144. person.position = body['position']
  145. person.phone = body['phone']
  146. if 'telephone' in body:
  147. person.telephone=body['telephone']
  148. person.order_num = body['order_num']
  149. person.unit_id = db_dept.get_dept_id_by_name(db, body['unit_name'])
  150. type_list = body['type_list']
  151. old_person_type_list=get_person_type_by_person_id(db,person.id)
  152. for old_person_type in old_person_type_list:
  153. old_person_type.del_flag='2'
  154. old_person_other_type_list = get_person_other_info_by_person_id(db,person.id)
  155. for old_person_other_type in old_person_other_type_list:
  156. old_person_other_type.del_flag = '2'
  157. for type_info in type_list:
  158. type_parent_id = type_info['type_parent_id'] # get_type_parent_id_by_type_id(db,type_id)
  159. for type_id in type_info['children']:
  160. new_person_type = ThreeProofingResponsiblePersonType(
  161. type_parent_id=type_parent_id,
  162. type_id=type_id,
  163. person_id=id,
  164. create_by=user_id
  165. )
  166. db.add(new_person_type)
  167. if type_parent_id in ('5', '7', '9'):
  168. if 'children2' in type_info:
  169. for other_type_id in type_info['children2']:
  170. new_person_other_type = ThreeProofingResponsiblePersonOtherType(
  171. type_parent_id=type_parent_id,
  172. other_type_id=other_type_id,
  173. person_id=person.id,
  174. create_by=user_id
  175. )
  176. db.add(new_person_other_type)
  177. if type_parent_id in ('4', '5', '7', '10', '11'):
  178. dept_name = None
  179. if 'dept_name' in type_info:
  180. dept_name = type_info['dept_name']
  181. other_type_2_name = None
  182. if 'other_type_2_name' in type_info:
  183. other_type_2_name = type_info['other_type_2_name']
  184. denger_point_name = None
  185. if 'denger_point_name' in type_info:
  186. denger_point_name = type_info['denger_point_name']
  187. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  188. type_parent_id=type_parent_id,
  189. dept_name=dept_name,
  190. other_type_2_name=other_type_2_name,
  191. denger_point_name=denger_point_name,
  192. person_id=person.id,
  193. create_by=user_id
  194. )
  195. db.add(new_person_other_info)
  196. # 更新到数据库会话并提交
  197. db.commit()
  198. # 返回创建成功的响应
  199. return {
  200. "code": 200,
  201. "msg": "更新成功",
  202. "data": None
  203. }
  204. except Exception as e:
  205. # 处理异常
  206. db.rollback()
  207. traceback.print_exc()
  208. raise HTTPException(status_code=500, detail=str(e))
  209. @router.get('/list')
  210. async def get_emergency_contact_list(
  211. type_parent_id: str = Query(None, description='单位名称'),
  212. area_code:str = Query(None, description='单位名称'),
  213. Name: str = Query(None, description='联系人'),
  214. page: int = Query(1, gt=0, description='页码'),
  215. pageSize: int = Query(10, gt=0, description='每页条目数量'),
  216. db: Session = Depends(get_db),
  217. user_id=Depends(valid_access_token)
  218. ):
  219. try:
  220. # 构建查询
  221. query = db.query(ThreeProofingResponsiblePerson)
  222. query = query.filter(ThreeProofingResponsiblePerson.del_flag == '0')
  223. # 应用查询条件
  224. if type_parent_id:
  225. person_list = get_person_list_by_type_parent_id(db,type_parent_id)
  226. query = query.filter(ThreeProofingResponsiblePerson.id.in_(person_list))
  227. if Name:
  228. query = query.filter(ThreeProofingResponsiblePerson.name.like(f'%{Name}%'))
  229. if area_code:
  230. query = query.filter(ThreeProofingResponsiblePerson.area_code==area_code)
  231. # 计算总条目数
  232. total_items = query.count()
  233. # 排序
  234. query = query.order_by(ThreeProofingResponsiblePerson.order_num.asc())
  235. query = query.order_by(ThreeProofingResponsiblePerson.create_time.desc())
  236. # 执行分页查询
  237. contact_infos = query.offset((page - 1) * pageSize).limit(pageSize).all()
  238. # 将查询结果转换为列表形式的字典
  239. contact_infos_list = []
  240. for info in contact_infos:
  241. type_parent_id_list = get_type_parent_id_by_person_id(db,info.id)
  242. type_parent_list = []
  243. type_parent_list2 = []
  244. for type_parent in type_parent_id_list:
  245. if type_parent not in type_parent_list2:
  246. dict_data = get_dict_data_info(db,'three_proofing',type_parent)
  247. type_parent_list2.append(type_parent)
  248. type_parent_list.append({"type_parent_id":type_parent,"type_parent":dict_data.dict_label})
  249. area_info = id_get_area_info(db,info.area_code)
  250. user_info = user_id_get_user_info(db,info.create_by)
  251. area_list = db_area.id_get_area_parent_list(db,info.area_code,[])
  252. contact_infos_list.append({
  253. "id": info.id,
  254. "unit_id": info.unit_id,
  255. "unit_name": info.unit_name,
  256. "name": info.name,
  257. "area_list":area_list,
  258. "area_code": info.area_code,
  259. "area_name": area_info.area_name,
  260. "position": info.position,
  261. "phone": info.phone,
  262. "telephone":info.telephone,
  263. "order_num":info.order_num,
  264. "online_status":'0',
  265. "create_time": info.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  266. "create_by":info.create_by,
  267. "create_user":user_info.nick_name,
  268. "type_parent_list":type_parent_list
  269. })
  270. # 返回结果+
  271. return {
  272. "code": 200,
  273. "msg": "成功",
  274. "data": contact_infos_list,
  275. "total": total_items
  276. }
  277. except Exception as e:
  278. # 处理异常
  279. traceback.print_exc()
  280. raise HTTPException(status_code=500, detail=str(e))
  281. @router.get('/info/{id}')
  282. async def get_emergency_contact_id_info(
  283. id: str,
  284. db: Session = Depends(get_db),
  285. user_id=Depends(valid_access_token)
  286. ):
  287. try:
  288. contact = get_person_info_by_id(db,id)
  289. if not contact:
  290. return JSONResponse(status_code=404, content={
  291. 'errcode': 404,
  292. 'errmsg': '联系人不存在'
  293. })
  294. # 将查询结果转换为列表形式的字典
  295. area_info = id_get_area_info(db,contact.area_code)
  296. user_info = user_id_get_user_info(db,contact.create_by)
  297. area_list = db_area.id_get_area_parent_list(db, contact.area_code, [])
  298. contact_result = {
  299. "id": contact.id,
  300. "unit_id": contact.unit_id,
  301. "unit_name": contact.unit_name,
  302. "name": contact.name,
  303. "area_list":area_list,
  304. "area_code":contact.area_code,
  305. "area_name": area_info.area_name,
  306. "position": contact.position,
  307. "phone": contact.phone,
  308. "telephone":contact.telephone,
  309. "order_num":contact.order_num,
  310. "online_status":'0',
  311. "create_time": contact.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  312. "create_by":contact.create_by,
  313. "create_user":user_info.nick_name,
  314. "type_list":[]
  315. }
  316. type_parent_id_list = []
  317. type_list = get_person_type_by_person_id(db,contact.id)
  318. for type_info in type_list:
  319. if type_info.type_parent_id not in type_parent_id_list:
  320. type_parent_id_list.append(type_info.type_parent_id)
  321. for type_parent_id in type_parent_id_list:
  322. dict_data = get_dict_data_info(db, 'three_proofing', type_parent_id)
  323. type_data = {"type_parent_id": type_parent_id, "type_parent": dict_data.dict_label,"children":[]}
  324. for type_info in get_person_type_by_person_id_and_type_parent_id(db,contact.id,type_parent_id):
  325. type_data_info = get_type_info_by_id(db,type_info.type_id)
  326. type_data['children'].append({"id": type_info.type_id, "label": type_data_info.type_name})
  327. other_info = get_person_other_info_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  328. if other_info:
  329. type_data['dept_name'] = other_info.dept_name
  330. type_data['denger_point_name'] = other_info.denger_point_name
  331. type_data['other_type_2_name'] = other_info.other_type_2_name
  332. other_type_list = get_person_other_type_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  333. if other_type_list:
  334. type_data['children2'] = []
  335. for other_type in other_type_list:
  336. other_type_info = get_other_type_info_by_id(db, other_type.other_type_id)
  337. label= ''
  338. if other_type_info:
  339. label = other_type_info.type_name
  340. type_data['children2'].append({"id": other_type.other_type_id, "label": label})
  341. contact_result['type_list'].append(type_data)
  342. # 返回结果
  343. return {
  344. "code": 200,
  345. "msg": "成功",
  346. "data": contact_result
  347. }
  348. except Exception as e:
  349. # 处理异常
  350. traceback.print_exc()
  351. raise HTTPException(status_code=500, detail=str(e))
  352. @router.delete('/delete')
  353. async def delete_emergency_plans(
  354. ids: list,
  355. db: Session = Depends(get_db),
  356. body=Depends(remove_xss_json),
  357. user_id=Depends(valid_access_token)
  358. ):
  359. try:
  360. # 提取请求数据
  361. query = db.query(ThreeProofingResponsiblePerson)
  362. query = query.filter(ThreeProofingResponsiblePerson.del_flag != '2')
  363. query = query.filter(ThreeProofingResponsiblePerson.id.in_(ids))
  364. contacts = query.all()
  365. if not contacts:
  366. return JSONResponse(status_code=404, content={
  367. 'errcode': 404,
  368. 'errmsg': '联系人不存在'
  369. })
  370. for contact in contacts:
  371. contact.del_flag = '2'
  372. contact.create_by = user_id
  373. # 更新到数据库会话并提交
  374. db.commit()
  375. # 返回创建成功的响应
  376. return {
  377. "code": 200,
  378. "msg": "删除成功",
  379. "data": None
  380. }
  381. except Exception as e:
  382. # 处理异常
  383. traceback.print_exc()
  384. raise HTTPException(status_code=500, detail=str(e))
  385. @router.delete('/delete/{id}')
  386. async def delete_emergency_plans(
  387. id: int,
  388. db: Session = Depends(get_db),
  389. body=Depends(remove_xss_json),
  390. user_id=Depends(valid_access_token)
  391. ):
  392. try:
  393. contact = get_person_info_by_id(db, id)
  394. if not contact:
  395. return JSONResponse(status_code=404, content={
  396. 'errcode': 404,
  397. 'errmsg': '联系人不存在'
  398. })
  399. contact.del_flag = '2'
  400. contact.create_by = user_id
  401. # 更新到数据库会话并提交
  402. db.commit()
  403. # 返回创建成功的响应
  404. return {
  405. "code": 200,
  406. "msg": "删除成功",
  407. "data": None
  408. }
  409. except Exception as e:
  410. # 处理异常
  411. traceback.print_exc()
  412. raise HTTPException(status_code=500, detail=str(e))
  413. #
  414. # @router.post('/createImport')
  415. # async def create_contact(
  416. # db: Session = Depends(get_db),
  417. # body=Depends(remove_xss_json),
  418. # user_id=Depends(valid_access_token)
  419. # ):
  420. # try:
  421. # # 提取请求数据
  422. # filename = body['filename']
  423. # if len(filename) == 0:
  424. # raise Exception()
  425. #
  426. # file_name = filename[0]['url']
  427. # file_path = f'/data/upload/mergefile/uploads/{file_name}'
  428. #
  429. # # 检查文件是否存在
  430. # if not os.path.isfile(file_path):
  431. # return JSONResponse(status_code=404, content={
  432. # 'errcode': 404,
  433. # 'errmsg': f'{file_name}不存在'
  434. # })
  435. #
  436. # # 定义预期的列名和对应的最大长度
  437. # expected_columns = {
  438. # '单位名称': 255,
  439. # '联系人': 255,
  440. # '职务': 255,
  441. # '粤政易手机号码': 20
  442. # }
  443. # try:
  444. # df = pd.read_excel(file_path, engine='openpyxl', header=0)
  445. # except Exception as e:
  446. # raise AppException(500, "请按模板上传!")
  447. #
  448. # # 读取Excel文件
  449. # # try:
  450. # # df = pd.read_excel(file_path, engine='openpyxl', header=0)
  451. # # except Exception as e:
  452. # # return f"读取Excel文件时出错: {e}"
  453. #
  454. # # 获取前两行的数据
  455. # first_two_rows = df
  456. # # print(first_two_rows)
  457. # # 检查列名是否匹配
  458. # actual_columns = first_two_rows.columns.tolist()
  459. # # print('actual_columns', actual_columns)
  460. # missing_columns = [col for col in expected_columns.keys() if col not in actual_columns]
  461. #
  462. # if len(missing_columns) > 0:
  463. # raise AppException(500, "请按模板上传")
  464. #
  465. # head1 = df.head(1)
  466. # head1data = head1.to_dict(orient='records')[0]
  467. # print(head1data)
  468. # if head1data['单位名称'] == '填写单位名称' and head1data['联系人'] == '填写单位联系人' and head1data['职务'] == '填写联系人职务' and \
  469. # head1data['粤政易手机号码'] == '填写联系人的粤政易注册手机号码':
  470. # df = df.drop(index=0)
  471. # else:
  472. # raise AppException(500, "请按模板上传。")
  473. #
  474. # # 检查前两行的字段长度
  475. # for index, row in first_two_rows.iterrows():
  476. # for col, max_length in expected_columns.items():
  477. # # if pd.isna(row[col]):
  478. # # return f"第{index + 1}行的'{col}'字段不能为空。"
  479. # if pd.notna(row[col]) and len(str(row[col])) > max_length:
  480. # raise AppException(500, f"第{index + 1}行的'{col}'字段长度超过{max_length}字符。")
  481. #
  482. # data = df.to_dict(orient='records')
  483. # # print(data)
  484. # infos = []
  485. # for info in data:
  486. # if pd.isna(info['单位名称']) and pd.isna(info['联系人']) and pd.isna(info['粤政易手机号码']):
  487. # continue
  488. # if pd.isna(info['单位名称']) or pd.isna(info['联系人']) or pd.isna(info['粤政易手机号码']):
  489. # return "单位名称、联系人、粤政易手机号码为必填"
  490. # if pd.isna(info['职务']):
  491. # info['职务'] = None
  492. # infos.append(info)
  493. #
  494. # # 创建新的预案记录
  495. # for contact in infos:
  496. # unit_id = db_dept.get_dept_id_by_name(db, contact['单位名称'])
  497. # if unit_id == '':
  498. # raise AppException(500, "单位名称不正确")
  499. #
  500. # # 删除之前同一个部门的人员
  501. # db.query(EmergencyContactInfo).filter(
  502. # and_(EmergencyContactInfo.del_flag == "0", EmergencyContactInfo.unit_id == unit_id, )).update(
  503. # {"del_flag": "2"})
  504. #
  505. # new_contact = EmergencyContactInfo(
  506. # unit_id=unit_id,
  507. # unit_name=contact['单位名称'],
  508. # contact_name=contact['联系人'],
  509. # position=contact['职务'],
  510. # yue_gov_ease_phone=contact['粤政易手机号码'],
  511. # create_by=user_id
  512. # )
  513. #
  514. # # 添加到数据库会话
  515. # db.add(new_contact)
  516. # # 提交
  517. # db.commit()
  518. #
  519. # # 返回创建成功的响应
  520. # return {
  521. # "code": 200,
  522. # "msg": "创建成功",
  523. # "data": None
  524. # }
  525. #
  526. # except AppException as e:
  527. # return {
  528. # "code": 500,
  529. # "msg": e.msg
  530. # }
  531. #
  532. # except Exception as e:
  533. # traceback.print_exc()
  534. # # 处理异常
  535. # raise HTTPException(status_code=500, detail=str(e))