contact.py 13 KB

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