contact.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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 common.db import db_event_management, db_user, db_area, db_emergency_plan
  16. from common.security import valid_access_token
  17. from common.enc import mpfun, emergency_contact_info_data
  18. import traceback
  19. from common.db import db_czrz
  20. from utils import *
  21. from datetime import datetime, timedelta
  22. import pandas as pd
  23. from common.auth_user import *
  24. from common.db import db_dept
  25. from exceptions import AppException, HmacException
  26. router = APIRouter()
  27. @router.get('/list')
  28. async def get_emergency_contact_list(
  29. unitId: str = Query(None, description='单位名称'),
  30. contactName: str = Query(None, description='联系人'),
  31. page: int = Query(1, gt=0, description='页码'),
  32. pageSize: int = Query(10, gt=0, description='每页条目数量'),
  33. db: Session = Depends(get_db),
  34. user_id = Depends(valid_access_token)
  35. ):
  36. try:
  37. # 构建查询
  38. query = db.query(EmergencyContactInfo)
  39. query = query.filter(EmergencyContactInfo.del_flag == '0')
  40. # 应用查询条件
  41. if unitId:
  42. query = query.filter(EmergencyContactInfo.unit_id == unitId)
  43. if contactName:
  44. query = query.filter(EmergencyContactInfo.contact_name.like(f'%{contactName}%'))
  45. # 计算总条目数
  46. total_items = query.count()
  47. # 排序
  48. query = query.order_by(EmergencyContactInfo.id.desc())
  49. # 执行分页查询
  50. contact_infos = query.offset((page - 1) * pageSize).limit(pageSize).all()
  51. for info in contact_infos:
  52. if emergency_contact_info_data.sign_valid_row(info) == False:
  53. raise HmacException(500, "应急预案人员信息表验证异常,已被非法篡改")
  54. # 将查询结果转换为列表形式的字典
  55. contact_infos_list = [
  56. {
  57. "id": info.id,
  58. "unitId": info.unit_id,
  59. "unitName": info.unit_name,
  60. "contactName": info.contact_name,
  61. "position": info.position,
  62. "phone": mpfun.dec_data(info.yue_gov_ease_phone),
  63. "create_time": info.create_time.strftime('%Y-%m-%d')
  64. }
  65. for info in contact_infos
  66. ]
  67. # 返回结果
  68. return {
  69. "code": 200,
  70. "msg": "成功",
  71. "data": contact_infos_list,
  72. "total": total_items
  73. }
  74. except HmacException as e:
  75. return {
  76. "code": e.code,
  77. "msg": e.msg
  78. }
  79. except Exception as e:
  80. # 处理异常
  81. raise HTTPException(status_code=500, detail=str(e))
  82. @router.get('/info/{id}')
  83. async def get_emergency_contact_id_info(
  84. id: str ,
  85. db: Session = Depends(get_db),
  86. user_id = Depends(valid_access_token)
  87. ):
  88. try:
  89. # 构建查询
  90. query = db.query(EmergencyContactInfo)
  91. query = query.filter(EmergencyContactInfo.del_flag != '2')
  92. # 应用查询条件
  93. if id:
  94. query = query.filter(EmergencyContactInfo.id == id)
  95. else:
  96. return JSONResponse(status_code=404, content={
  97. 'errcode': 404,
  98. 'errmsg': '联系人不存在'
  99. })
  100. # 执行查询
  101. contact = query.first()
  102. if not contact:
  103. return JSONResponse(status_code=404, content={
  104. 'errcode': 404,
  105. 'errmsg': '联系人不存在'
  106. })
  107. # 将查询结果转换为列表形式的字典
  108. contact_result = {
  109. "id": contact.id,
  110. "unitId": contact.unit_id,
  111. "unitName": contact.unit_name,
  112. "contactName": contact.contact_name,
  113. "position": contact.position,
  114. "phone": mpfun.dec_data(contact.yue_gov_ease_phone),
  115. "create_time": contact.create_time.strftime('%Y-%m-%d')
  116. }
  117. # 返回结果
  118. return {
  119. "code": 200,
  120. "msg": "成功",
  121. "data": contact_result
  122. }
  123. except Exception as e:
  124. # 处理异常
  125. raise HTTPException(status_code=500, detail=str(e))
  126. @router.post('/create')
  127. async def create_contact(
  128. request: Request,
  129. db: Session = Depends(get_db),
  130. body = Depends(remove_xss_json),
  131. auth_user: AuthUser = Depends(find_auth_user),
  132. user_id = Depends(valid_access_token)
  133. ):
  134. try:
  135. # 提取请求数据
  136. unit_id = body['unitId']
  137. contact_name = body['contactName']
  138. position = body['position']
  139. yue_gov_ease_phone = body['phone']
  140. unit_name = db_dept.get_dept_name_by_id(db, unit_id)
  141. if unit_name == '':
  142. raise Exception('单位不正确')
  143. # 创建新的预案记录
  144. new_contact = EmergencyContactInfo(
  145. unit_id = unit_id,
  146. unit_name = unit_name,
  147. contact_name = contact_name,
  148. position = position,
  149. yue_gov_ease_phone = yue_gov_ease_phone,
  150. create_by = user_id,
  151. sign = ''
  152. )
  153. # 添加到数据库会话并提交
  154. db.add(new_contact)
  155. db.commit()
  156. emergency_contact_info_data.sign_table()
  157. db_czrz.log(db, auth_user, "系统管理", f"后台管理新建应急预案人员信息成功", request.client.host)
  158. # 返回创建成功的响应
  159. return {
  160. "code": 200,
  161. "msg": "创建成功",
  162. "data": None
  163. }
  164. except Exception as e:
  165. traceback.print_exc()
  166. # 处理异常
  167. raise HTTPException(status_code=500, detail=str(e))
  168. @router.put('/update')
  169. async def update_contact(
  170. request: Request,
  171. db: Session = Depends(get_db),
  172. body = Depends(remove_xss_json),
  173. auth_user: AuthUser = Depends(find_auth_user),
  174. user_id = Depends(valid_access_token)
  175. ):
  176. try:
  177. # 提取请求数据
  178. query = db.query(EmergencyContactInfo)
  179. query = query.filter(EmergencyContactInfo.del_flag != '2')
  180. id = body['id']
  181. query = query.filter(EmergencyContactInfo.id == id)
  182. contact = query.first()
  183. if not contact:
  184. return JSONResponse(status_code=404, content={
  185. 'errcode': 404,
  186. 'errmsg': '联系人不存在'
  187. })
  188. if "unitId" in body:
  189. unit_name = db_dept.get_dept_name_by_id(db, body['unitId'])
  190. if unit_name == '':
  191. raise Exception('单位不正确')
  192. contact.unit_id = body['unitId']
  193. contact.unit_name = unit_name
  194. if "contactName" in body:
  195. contact.contact_name = body['contactName']
  196. if "position" in body:
  197. contact.position = body['position']
  198. if "phone" in body:
  199. contact.yue_gov_ease_phone = mpfun.enc_data(body['phone'])
  200. contact.sign = emergency_contact_info_data.get_sign_hmac(contact)
  201. contact.update_time = datetime.now()
  202. db.commit()
  203. db_czrz.log(db, auth_user, "系统管理", f"后台管理更新应急预案人员信息【{unit_name}】成功", request.client.host)
  204. # 返回创建成功的响应
  205. return {
  206. "code": 200,
  207. "msg": "更新成功",
  208. "data": None
  209. }
  210. except Exception as e:
  211. traceback.print_exc()
  212. # 处理异常
  213. raise HTTPException(status_code=500, detail=str(e))
  214. @router.delete('/delete')
  215. async def delete_emergency_plans(
  216. request: Request,
  217. ids: list,
  218. db: Session = Depends(get_db),
  219. body = Depends(remove_xss_json),
  220. auth_user: AuthUser = Depends(find_auth_user),
  221. user_id = Depends(valid_access_token)
  222. ):
  223. try:
  224. # 提取请求数据
  225. query = db.query(EmergencyContactInfo)
  226. query = query.filter(EmergencyContactInfo.del_flag != '2')
  227. query = query.filter(EmergencyContactInfo.id.in_(ids))
  228. contacts = query.all()
  229. if not contacts:
  230. return JSONResponse(status_code=404, content={
  231. 'errcode': 404,
  232. 'errmsg': '联系人不存在'
  233. })
  234. for contact in contacts:
  235. contact.del_flag = '2'
  236. contact.create_by = user_id
  237. contact.update_time = datetime.now()
  238. contact.sign = emergency_contact_info_data.get_sign_hmac(contact)
  239. # 更新到数据库会话并提交
  240. db.commit()
  241. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除应急预案人员信息成功", request.client.host)
  242. # 返回创建成功的响应
  243. return {
  244. "code": 200,
  245. "msg": "删除成功",
  246. "data": None
  247. }
  248. except Exception as e:
  249. # 处理异常
  250. raise HTTPException(status_code=500, detail=str(e))
  251. @router.delete('/delete/{id}')
  252. async def delete_emergency_plans(
  253. request: Request,
  254. id: int,
  255. db: Session = Depends(get_db),
  256. body = Depends(remove_xss_json),
  257. auth_user: AuthUser = Depends(find_auth_user),
  258. user_id = Depends(valid_access_token)
  259. ):
  260. try:
  261. # 提取请求数据
  262. query = db.query(EmergencyContactInfo)
  263. query = query.filter(EmergencyContactInfo.del_flag != '2')
  264. query = query.filter(EmergencyContactInfo.id==id)
  265. contact = query.first()
  266. if not contact:
  267. return JSONResponse(status_code=404, content={
  268. 'errcode': 404,
  269. 'errmsg': '联系人不存在'
  270. })
  271. contact.del_flag = '2'
  272. contact.create_by = user_id
  273. contact.update_time = datetime.now()
  274. contact.sign = emergency_contact_info_data.get_sign_hmac(contact)
  275. # 更新到数据库会话并提交
  276. db.commit()
  277. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除应急预案人员信息成功", request.client.host)
  278. # 返回创建成功的响应
  279. return {
  280. "code": 200,
  281. "msg": "删除成功",
  282. "data": None
  283. }
  284. except Exception as e:
  285. # 处理异常
  286. raise HTTPException(status_code=500, detail=str(e))
  287. @router.post('/createImport')
  288. async def create_contact(
  289. request: Request,
  290. db: Session = Depends(get_db),
  291. body = Depends(remove_xss_json),
  292. auth_user: AuthUser = Depends(find_auth_user),
  293. user_id = Depends(valid_access_token)
  294. ):
  295. try:
  296. # 提取请求数据
  297. filename = body['filename']
  298. if len(filename) == 0:
  299. raise Exception()
  300. file_name = filename[0]['url']
  301. file_path = f'/data/upload/mergefile/uploads/{file_name}'
  302. # 检查文件是否存在
  303. if not os.path.isfile(file_path):
  304. return JSONResponse(status_code=404, content={
  305. 'errcode': 404,
  306. 'errmsg': f'{file_name}不存在'
  307. })
  308. # 定义预期的列名和对应的最大长度
  309. expected_columns = {
  310. '单位名称': 255,
  311. '联系人': 255,
  312. '职务': 255,
  313. '粤政易手机号码': 20
  314. }
  315. try:
  316. df = pd.read_excel(file_path, engine='openpyxl', header=0)
  317. except Exception as e:
  318. raise AppException(500, "请按模板上传!")
  319. # 读取Excel文件
  320. # try:
  321. # df = pd.read_excel(file_path, engine='openpyxl', header=0)
  322. # except Exception as e:
  323. # return f"读取Excel文件时出错: {e}"
  324. # 获取前两行的数据
  325. first_two_rows = df
  326. # print(first_two_rows)
  327. # 检查列名是否匹配
  328. actual_columns = first_two_rows.columns.tolist()
  329. # print('actual_columns', actual_columns)
  330. missing_columns = [col for col in expected_columns.keys() if col not in actual_columns]
  331. if len(missing_columns) > 0:
  332. raise AppException(500, "请按模板上传")
  333. head1 = df.head(1)
  334. head1data = head1.to_dict(orient='records')[0]
  335. print(head1data)
  336. if head1data['单位名称'] == '填写单位名称' and head1data['联系人'] == '填写单位联系人' and head1data['职务'] == '填写联系人职务' and \
  337. head1data['粤政易手机号码'] == '填写联系人的粤政易注册手机号码':
  338. df = df.drop(index=0)
  339. else:
  340. raise AppException(500, "请按模板上传。")
  341. # 检查前两行的字段长度
  342. for index, row in first_two_rows.iterrows():
  343. for col, max_length in expected_columns.items():
  344. # if pd.isna(row[col]):
  345. # return f"第{index + 1}行的'{col}'字段不能为空。"
  346. if pd.notna(row[col]) and len(str(row[col])) > max_length:
  347. raise AppException(500, f"第{index + 1}行的'{col}'字段长度超过{max_length}字符。")
  348. data = df.to_dict(orient='records')
  349. # print(data)
  350. infos = []
  351. for info in data:
  352. if pd.isna(info['单位名称']) and pd.isna(info['联系人']) and pd.isna(info['粤政易手机号码']):
  353. continue
  354. if pd.isna(info['单位名称']) or pd.isna(info['联系人']) or pd.isna(info['粤政易手机号码']):
  355. return "单位名称、联系人、粤政易手机号码为必填"
  356. if pd.isna(info['职务']):
  357. info['职务'] = None
  358. infos.append(info)
  359. # 创建新的预案记录
  360. for contact in infos:
  361. unit_id = db_dept.get_dept_id_by_name(db, contact['单位名称'])
  362. if unit_id == '':
  363. raise AppException(500, "单位名称不正确")
  364. # 删除之前同一个部门的人员
  365. db.query(EmergencyContactInfo).filter(and_(EmergencyContactInfo.del_flag == "0", EmergencyContactInfo.unit_id == unit_id, )).update({"del_flag": "2"})
  366. new_contact = EmergencyContactInfo(
  367. unit_id=unit_id,
  368. unit_name=contact['单位名称'],
  369. contact_name = contact['联系人'],
  370. position = contact['职务'],
  371. yue_gov_ease_phone = contact['粤政易手机号码'],
  372. create_by = user_id,
  373. sign = ''
  374. )
  375. # 添加到数据库会话
  376. db.add(new_contact)
  377. # 提交
  378. db.commit()
  379. emergency_contact_info_data.sign_table()
  380. db_czrz.log(db, auth_user, "系统管理", f"后台管理导入应急预案人员信息成功", request.client.host)
  381. # 返回创建成功的响应
  382. return {
  383. "code": 200,
  384. "msg": "创建成功",
  385. "data": None
  386. }
  387. except AppException as e:
  388. return {
  389. "code": 500,
  390. "msg": e.msg
  391. }
  392. except Exception as e:
  393. traceback.print_exc()
  394. # 处理异常
  395. raise HTTPException(status_code=500, detail=str(e))