person.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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
  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('/info/{id}')
  336. async def get_emergency_contact_id_info(
  337. id: str,
  338. db: Session = Depends(get_db),
  339. user_id=Depends(valid_access_token)
  340. ):
  341. try:
  342. contact = get_person_info_by_id(db,id)
  343. if not contact:
  344. return JSONResponse(status_code=404, content={
  345. 'errcode': 404,
  346. 'errmsg': '联系人不存在'
  347. })
  348. # 将查询结果转换为列表形式的字典
  349. area_info = id_get_area_info(db,contact.area_code)
  350. user_info = user_id_get_user_info(db,contact.create_by)
  351. area_list = db_area.id_get_area_parent_list(db, contact.area_code, [])
  352. if contact.order_num == -1:
  353. order_num = ''
  354. else:
  355. order_num = str(contact.order_num)
  356. contact_result = {
  357. "id": contact.id,
  358. "unit_id": contact.unit_id,
  359. "unit_name": contact.unit_name,
  360. "name": contact.name,
  361. "area_list":area_list,
  362. "area_code":contact.area_code,
  363. "area_name": area_info.area_name,
  364. "position": contact.position,
  365. "phone": mpfun.dec_data(contact.phone),
  366. "telephone":mpfun.dec_data(contact.telephone),
  367. "order_num":order_num,
  368. "online_status":'0',
  369. "create_time": contact.create_time.strftime('%Y-%m-%d %H:%M:%S'),
  370. "create_by":contact.create_by,
  371. "create_user":user_info.nick_name,
  372. "type_list":[]
  373. }
  374. type_parent_id_list = []
  375. type_list = get_person_type_by_person_id(db,contact.id)
  376. for type_info in type_list:
  377. if type_info.type_parent_id not in type_parent_id_list:
  378. type_parent_id_list.append(type_info.type_parent_id)
  379. for type_parent_id in type_parent_id_list:
  380. dict_data = get_dict_data_info(db, 'three_proofing', type_parent_id)
  381. type_data = {"type_parent_id": type_parent_id, "type_parent": dict_data.dict_label,"children":[],"labelData":[]}
  382. for type_info in get_person_type_by_person_id_and_type_parent_id(db,contact.id,type_parent_id):
  383. type_data_info = get_type_info_by_id(db,type_info.type_id)
  384. # type_data['children'].append({"id": type_info.type_id, "label": type_data_info.type_name})
  385. type_data['children'].append(type_info.type_id)
  386. type_data['labelData'].append( type_data_info.type_name)
  387. other_info = get_person_other_info_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  388. if other_info:
  389. type_data['dept_name'] = other_info.dept_name
  390. type_data['denger_point_name'] = other_info.denger_point_name
  391. type_data['other_type_2_name'] = other_info.other_type_2_name
  392. other_type_list = get_person_other_type_by_person_id_and_type_parent_id(db, contact.id, type_parent_id)
  393. if other_type_list:
  394. type_data['children2'] = []
  395. type_data['other_type_label'] = []
  396. for other_type in other_type_list:
  397. other_type_info = get_other_type_info_by_id(db, other_type.other_type_id)
  398. label= ''
  399. if other_type_info:
  400. label = other_type_info.type_name
  401. # type_data['children2'].append({"id": other_type.other_type_id, "label": label})
  402. type_data['children2'].append(other_type.other_type_id)
  403. type_data['other_type_label'].append(label)
  404. contact_result['type_list'].append(type_data)
  405. # 返回结果
  406. return {
  407. "code": 200,
  408. "msg": "成功",
  409. "data": contact_result
  410. }
  411. except Exception as e:
  412. # 处理异常
  413. traceback.print_exc()
  414. raise HTTPException(status_code=500, detail=str(e))
  415. @router.delete('/delete')
  416. async def delete_emergency_plans(
  417. request: Request,
  418. ids: list,
  419. db: Session = Depends(get_db),
  420. body=Depends(remove_xss_json),
  421. auth_user: AuthUser = Depends(find_auth_user),
  422. user_id=Depends(valid_access_token)
  423. ):
  424. try:
  425. # 提取请求数据
  426. query = db.query(ThreeProofingResponsiblePerson)
  427. query = query.filter(ThreeProofingResponsiblePerson.del_flag != '2')
  428. query = query.filter(ThreeProofingResponsiblePerson.id.in_(ids))
  429. contacts = query.all()
  430. if not contacts:
  431. return JSONResponse(status_code=404, content={
  432. 'errcode': 404,
  433. 'errmsg': '联系人不存在'
  434. })
  435. for contact in contacts:
  436. contact.del_flag = '2'
  437. contact.update_by = user_id
  438. contact.update_time = datetime.now()
  439. contact.sign = three_proofing_responsible_person_data.get_sign_hmac(contact)
  440. # 更新到数据库会话并提交
  441. db.commit()
  442. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除三防责任人管理人员信息成功", request.client.host)
  443. # 返回创建成功的响应
  444. return {
  445. "code": 200,
  446. "msg": "删除成功",
  447. "data": None
  448. }
  449. except Exception as e:
  450. # 处理异常
  451. traceback.print_exc()
  452. raise HTTPException(status_code=500, detail=str(e))
  453. @router.delete('/delete/{id}')
  454. async def delete_emergency_plans(
  455. request: Request,
  456. id: int,
  457. db: Session = Depends(get_db),
  458. body=Depends(remove_xss_json),
  459. auth_user: AuthUser = Depends(find_auth_user),
  460. user_id=Depends(valid_access_token)
  461. ):
  462. try:
  463. contact = get_person_info_by_id(db, id)
  464. if not contact:
  465. return JSONResponse(status_code=404, content={
  466. 'errcode': 404,
  467. 'errmsg': '联系人不存在'
  468. })
  469. contact.del_flag = '2'
  470. contact.update_by = user_id
  471. contact.update_time = datetime.now()
  472. contact.sign = three_proofing_responsible_person_data.get_sign_hmac(contact)
  473. # 更新到数据库会话并提交
  474. db.commit()
  475. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除三防责任人管理人员信息成功", request.client.host)
  476. # 返回创建成功的响应
  477. return {
  478. "code": 200,
  479. "msg": "删除成功",
  480. "data": None
  481. }
  482. except Exception as e:
  483. # 处理异常
  484. traceback.print_exc()
  485. raise HTTPException(status_code=500, detail=str(e))
  486. def string_type_parent_id_create_data(db,string,type_parent_id,file_info,new_person,user_id,row) :
  487. type_name_list = [i for i in string.split(',')]
  488. reslte = []
  489. for type_name in type_name_list:
  490. type_id = get_type_id_by_type_parent_id_and_type_name(db, type_parent_id, type_name)
  491. if type_id:
  492. new_person_type = ThreeProofingResponsiblePersonType(
  493. type_parent_id=type_parent_id,
  494. type_id=type_id,
  495. person_id=new_person.id,
  496. create_by=user_id
  497. )
  498. reslte.append(new_person_type)
  499. else:
  500. file_info.remark= file_info.remark+f'\n行<{row+1}>责任类别未找到<{type_name}>'
  501. return reslte ,False
  502. return reslte ,True
  503. def other_type_string_type_parent_id_create_data(db,string,type_parent_id,file_info,new_person,user_id,row) :
  504. type_name_list = [i for i in string.split(',')]
  505. reslte = []
  506. for other_type_name in type_name_list:
  507. other_type_id = get_other_type_id_by_type_parent_id_and_other_type_name(db, type_parent_id, other_type_name)
  508. if other_type_id:
  509. new_person_type = ThreeProofingResponsiblePersonOtherType(
  510. type_parent_id=type_parent_id,
  511. other_type_id=other_type_id,
  512. person_id=new_person.id,
  513. create_by=user_id
  514. )
  515. reslte.append(new_person_type)
  516. else:
  517. file_info.remark= file_info.remark+f'\n行<{row+1}>责任类别未找到<{other_type_name}>'
  518. file_info.error_num +=1
  519. return reslte ,False
  520. return reslte ,True
  521. def import_data(db,file_path,user_id,file_info):
  522. import_status = True
  523. try:
  524. book = xlrd.open_workbook(file_path)
  525. sheet = book.sheet_by_index(0)
  526. except :
  527. file_info.remark = file_info.remark + f'\n文件打开失败,请核实文件格式为xlsx/xlx>'
  528. file_info.error_num +=1
  529. import_status = False
  530. data = []
  531. for row in range(4, sheet.nrows):
  532. # 姓名
  533. name = sheet.cell(row, 0).value
  534. if name == '':
  535. file_info.remark = file_info.remark+f'\n行<{row+1}>姓名不能为空<{name}>'
  536. file_info.error_num +=1
  537. import_status = False
  538. # 所属单位
  539. unit_name = sheet.cell(row, 1).value
  540. if unit_name == '':
  541. file_info.remark = file_info.remark+f'\n行<{row+1}>所属单位不能为空<{unit_name}>'
  542. file_info.error_num +=1
  543. import_status = False
  544. unit_id = db_dept.get_dept_id_by_name(db, unit_name)
  545. # 职务
  546. position = sheet.cell(row, 2).value
  547. if position =='':
  548. file_info.remark = file_info.remark+f'\n行<{row+1}>职务不能为空<{position}>'
  549. file_info.error_num +=1
  550. import_status = False
  551. # 电话号码(如有多个手机号请用“,”分隔)
  552. phone = str(sheet.cell(row, 3).value)
  553. if phone =='':
  554. file_info.remark = file_info.remark+f'\n行<{row+1}>电话号码不能为空<{phone}>'
  555. file_info.error_num +=1
  556. import_status = False
  557. phone_list = [i for i in phone.split(',')]
  558. user_id_1=-1
  559. for i in phone_list:
  560. user_id_1 = db_user.get_user_id_by_phonenumber(db, i)
  561. if user_id_1 != -1:
  562. break
  563. # 办公电话
  564. # (选填,格式:区号-电话号码)
  565. telephone = sheet.cell(row, 4).value
  566. # 排位顺序
  567. # (选填,请输入排序号1-9999,排序号数值越小越靠前,不填则默认排至最末)
  568. order_num = sheet.cell(row, 5).value
  569. if order_num == '':
  570. order_num=-1
  571. area_name = sheet.cell(row, 7).value
  572. if area_name=='':
  573. area_code=2
  574. area_code2='440900000000'
  575. else:
  576. area_code=get_area_info_by_area_name(db,area_name)
  577. if area_code is None:
  578. file_info.remark = file_info.remark+f'\n行<{row+1}>责任区域未找到'
  579. file_info.error_num +=1
  580. import_status = False
  581. area_code2 = area_code.area_code
  582. area_code = area_code.id
  583. new_person = ThreeProofingResponsiblePerson(
  584. unit_id=unit_id,
  585. unit_name=unit_name,
  586. name=name,
  587. area_code2=area_code2,
  588. area_code=area_code,
  589. position=position,
  590. phone=phone.replace,
  591. telephone=telephone,
  592. user_id=user_id_1,
  593. order_num=order_num,
  594. create_by=user_id,
  595. sign = ''
  596. )
  597. data.append(new_person)
  598. db.add(new_person)
  599. db.commit()
  600. # 党委政府
  601. a1 = sheet.cell(row, 6).value
  602. if a1 != '':
  603. new_type_list,status = string_type_parent_id_create_data(db,a1,'1',file_info,new_person,user_id,row)
  604. if status:
  605. db.add_all(new_type_list)
  606. data +=new_type_list
  607. else:
  608. import_status = status
  609. # type_name_list = [i for i in a1.split(',')]
  610. # for type_name in type_name_list:
  611. # type_id = get_type_id_by_type_parent_id_and_type_name(db, '1', type_name)
  612. # if type_id:
  613. # pass
  614. # 三防指挥部
  615. b1 = sheet.cell(row, 8).value
  616. if b1 != '':
  617. new_type_list,status = string_type_parent_id_create_data(db,b1,'2',file_info,new_person,user_id,row)
  618. if status:
  619. db.add_all(new_type_list)
  620. data +=new_type_list
  621. else:
  622. import_status = status
  623. b2 = sheet.cell(row, 9).value
  624. # 应急部门
  625. c1 = sheet.cell(row, 10).value
  626. if c1!='':
  627. new_type_list, status = string_type_parent_id_create_data(db, c1, '3', file_info, new_person, user_id,row)
  628. if status:
  629. db.add_all(new_type_list)
  630. data += new_type_list
  631. else:
  632. import_status = status
  633. # 成员单位
  634. d1 = sheet.cell(row, 11).value
  635. if d1!='':
  636. new_type_list, status = string_type_parent_id_create_data(db, d1, '4', file_info, new_person, user_id,row)
  637. if status:
  638. db.add_all(new_type_list)
  639. data += new_type_list
  640. else:
  641. import_status = status
  642. d2 = sheet.cell(row, 12).value
  643. if d2!='':
  644. dept_name = d2
  645. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  646. type_parent_id='4',
  647. dept_name=dept_name,
  648. person_id=new_person.id,
  649. create_by=user_id
  650. )
  651. db.add(new_person_other_info)
  652. data.append(new_person_other_info)
  653. # 重点部门
  654. e1 = sheet.cell(row, 13).value
  655. if e1!='':
  656. new_type_list, status = string_type_parent_id_create_data(db, e1, '5', file_info, new_person, user_id,row)
  657. if status:
  658. db.add_all(new_type_list)
  659. data += new_type_list
  660. else:
  661. import_status = status
  662. e2 = sheet.cell(row, 14).value
  663. if e2!='':
  664. dept_name = e2
  665. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  666. type_parent_id='5',
  667. dept_name=dept_name,
  668. person_id=new_person.id,
  669. create_by=user_id
  670. )
  671. db.add(new_person_other_info)
  672. data.append(new_person_other_info)
  673. e3 = sheet.cell(row, 15).value
  674. if e3!='':
  675. new_type_list,status = other_type_string_type_parent_id_create_data(db,e3,'5',file_info,new_person,user_id,row)
  676. if status:
  677. db.add_all(new_type_list)
  678. data +=new_type_list
  679. else:
  680. import_status = status
  681. # 行政村
  682. f1 = sheet.cell(row, 16).value
  683. if f1!='':
  684. new_type_list, status = string_type_parent_id_create_data(db, f1, '6', file_info, new_person, user_id,row)
  685. if status:
  686. db.add_all(new_type_list)
  687. data += new_type_list
  688. else:
  689. import_status = status
  690. # 水利工程
  691. g1 = sheet.cell(row, 17).value
  692. if g1!='':
  693. new_type_list, status = string_type_parent_id_create_data(db, g1, '7', file_info, new_person, user_id,row)
  694. if status:
  695. db.add_all(new_type_list)
  696. data += new_type_list
  697. else:
  698. import_status = status
  699. g2 = sheet.cell(row, 18).value
  700. if g2!='':
  701. dept_name = g2
  702. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  703. type_parent_id='7',
  704. dept_name=dept_name,
  705. person_id=new_person.id,
  706. create_by=user_id
  707. )
  708. db.add(new_person_other_info)
  709. data.append(new_person_other_info)
  710. g3 = sheet.cell(row, 19).value
  711. if g3!='':
  712. new_type_list, status = other_type_string_type_parent_id_create_data(db, g3, '11', file_info, new_person, user_id,
  713. row)
  714. if status:
  715. db.add_all(new_type_list)
  716. data += new_type_list
  717. else:
  718. import_status = status
  719. # 受威胁转移
  720. h1 = sheet.cell(row, 20).value
  721. if h1!='':
  722. new_type_list, status = string_type_parent_id_create_data(db, h1, '8', file_info, new_person, user_id,row)
  723. if status:
  724. db.add_all(new_type_list)
  725. data += new_type_list
  726. else:
  727. import_status = status
  728. # 抢险队伍
  729. j1 = sheet.cell(row, 21).value
  730. if j1!='':
  731. new_type_list, status = string_type_parent_id_create_data(db, j1, '9', file_info, new_person, user_id,row)
  732. if status:
  733. db.add_all(new_type_list)
  734. data += new_type_list
  735. else:
  736. import_status = status
  737. j2 = sheet.cell(row, 22).value
  738. if j2!='':
  739. new_type_list, status = other_type_string_type_parent_id_create_data(db, j2, '9', file_info, new_person, user_id,
  740. row)
  741. if status:
  742. db.add_all(new_type_list)
  743. data += new_type_list
  744. else:
  745. import_status = status
  746. # 地质灾害
  747. k1 = sheet.cell(row, 23).value
  748. if k1!='':
  749. new_type_list, status = string_type_parent_id_create_data(db, k1, '10', 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. k2 = sheet.cell(row, 24).value
  756. if k2!='':
  757. denger_point_name = k2
  758. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  759. type_parent_id='10',
  760. denger_point_name=denger_point_name,
  761. person_id=new_person.id,
  762. create_by=user_id
  763. )
  764. db.add(new_person_other_info)
  765. data.append(new_person_other_info)
  766. # 其他
  767. l1 = sheet.cell(row, 25).value
  768. if l1!='':
  769. new_type_list, status = string_type_parent_id_create_data(db, l1, '11', file_info, new_person, user_id,row)
  770. if status:
  771. db.add_all(new_type_list)
  772. data += new_type_list
  773. else:
  774. import_status = status
  775. l2 = sheet.cell(row, 26).value
  776. if l2!='':
  777. other_type_2_name = l2
  778. new_person_other_info = ThreeProofingResponsiblePersonOtherInfo(
  779. type_parent_id='11',
  780. other_type_2_name=other_type_2_name,
  781. person_id=new_person.id,
  782. create_by=user_id
  783. )
  784. db.add(new_person_other_info)
  785. data.append(new_person_other_info)
  786. db.commit()
  787. if import_status == False:
  788. # print(1111111)
  789. for info in data:
  790. db.delete(info)
  791. file_info.status = 2
  792. db.commit()
  793. three_proofing_responsible_person_data.sign_table()
  794. @router.post('/createImport')
  795. async def create_contact(
  796. request: Request,
  797. background_tasks: BackgroundTasks,
  798. db: Session = Depends(get_db),
  799. body=Depends(remove_xss_json),
  800. auth_user: AuthUser = Depends(find_auth_user),
  801. user_id=Depends(valid_access_token)
  802. ):
  803. try:
  804. # 提取请求数据
  805. filename = body['filename']
  806. file_name_desc = body['file_name_desc']
  807. if len(filename) == 0:
  808. raise Exception()
  809. file_path = f'/data/upload/mergefile/uploads/{filename}'
  810. # 检查文件是否存在
  811. if not os.path.isfile(file_path):
  812. return JSONResponse(status_code=404, content={
  813. 'errcode': 404,
  814. 'errmsg': f'{filename}不存在'
  815. })
  816. new_file = ThreeProofingResponsiblePersonImportFileStatus(
  817. file_uuid=filename,
  818. file_name = file_name_desc,
  819. status = '1',
  820. remark = '',
  821. user_id=user_id
  822. )
  823. db.add(new_file)
  824. db.commit()
  825. background_tasks.add_task(import_data,db,file_path, user_id,new_file)
  826. db_czrz.log(db, auth_user, "系统管理", f"后台管理导入三防责任人管理人员信息成功", request.client.host)
  827. # 返回创建成功的响应
  828. return {
  829. "code": 200,
  830. "msg": "成功",
  831. "data": None
  832. }
  833. except AppException as e:
  834. return {
  835. "code": 500,
  836. "msg": e.msg
  837. }
  838. except Exception as e:
  839. traceback.print_exc()
  840. # 处理异常
  841. db.rollback()
  842. raise HTTPException(status_code=500, detail=str(e))
  843. @router.get("/export")
  844. async def download_file(filename: str,filenameDesc: str = None):
  845. """
  846. 根据提供的文件名下载文件。
  847. :param filename: 要下载的文件的名称。
  848. """
  849. try:
  850. # 构造文件的完整路径
  851. file_path = os.path.join('', 'uploads/', filename)
  852. # 检查文件是否存在
  853. if not os.path.isfile(file_path):
  854. raise HTTPException(status_code=404, detail="文件未找到")
  855. if not filenameDesc:
  856. filenameDesc = filename
  857. # 设置文件头部和内容类型
  858. headers = {
  859. 'Content-Disposition': f'attachment; filename={filenameDesc}'
  860. }
  861. # 使用FileResponse返回文件流
  862. return FileResponse(
  863. path=file_path,
  864. headers=headers,
  865. media_type='application/octet-stream' # 可以按需更改为适当的MIME类型
  866. )
  867. except HTTPException as e:
  868. raise e
  869. except Exception as e:
  870. # 处理其他异常情况
  871. raise HTTPException(status_code=500, detail=str(e))