back.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, HTTPException, Query
  4. from sqlalchemy.exc import IntegrityError
  5. from fastapi.responses import HTMLResponse, FileResponse
  6. from fastapi.responses import JSONResponse
  7. from database import get_db
  8. from sqlalchemy import text, exists, and_, or_, not_
  9. from sqlalchemy.orm import Session
  10. from models import *
  11. import json
  12. import os
  13. from sqlalchemy import create_engine, select
  14. from typing import Optional
  15. from utils.StripTagsHTMLParser import *
  16. from common.db import db_event_management, db_user, db_area, db_emergency_plan
  17. from common.security import valid_access_token
  18. import traceback
  19. from utils import *
  20. from datetime import datetime, timedelta
  21. from common import YzyApi
  22. from common.db import db_dict
  23. from urllib.parse import quote
  24. import base64
  25. from config import settings
  26. router = APIRouter()
  27. EXAMINE_TYPE_DICT = {
  28. 0: "草稿",
  29. 10: "提交",
  30. 20: "领导审批",
  31. 30: "重新提交"
  32. }
  33. EXAMINE_SUB_TYPE_DICT = {
  34. 0: "草稿",
  35. 10: "提交",
  36. 20: "待审批",
  37. 21: "审批通过",
  38. 22: "审批不通过",
  39. 30: "重新提交"
  40. }
  41. # 信息发布创建
  42. @router.post('/create')
  43. async def create_emergency_plan(
  44. db: Session = Depends(get_db),
  45. body = Depends(remove_xss_json),
  46. user_id = Depends(valid_access_token)
  47. ):
  48. try:
  49. dept_id = 0
  50. dept_name = ''
  51. user_row = db.query(SysUser).filter(SysUser.user_id == user_id).first()
  52. user_name = user_row.user_name
  53. nick_name = user_row.nick_name
  54. dept_id = user_row.dept_id
  55. dept_row = db.query(SysDept).filter(SysDept.dept_id == dept_id).first()
  56. dept_name = dept_row.dept_name
  57. new_publish = InfoPublishBase(
  58. title = body['title'],
  59. publish_group = body['publish_group'],
  60. template_id = body['template_id'],
  61. content = body['content'],
  62. recorded_by = user_id,
  63. del_flag = '0',
  64. dept_id = dept_id,
  65. dept_name = dept_name,
  66. add_time = datetime.now(),
  67. response_type = body['response_type'],
  68. publish_time = body['publish_time'],
  69. examine_by = body['examine_by'],
  70. publish_status = 0,
  71. examine_status = 0,
  72. publish_channel = body['publish_channel'],
  73. user_count = body['user_count'],
  74. user_ok_count = 0,
  75. user_err_count = 0,
  76. user_sending_count = 0
  77. )
  78. db.add(new_publish)
  79. db.commit()
  80. db.refresh(new_publish)
  81. new_publish_id = new_publish.id
  82. # 发送人员
  83. for u in body['users']:
  84. send_user_id = u['user_id']
  85. send_nick_name = u['nick_name']
  86. send_user_name = ''
  87. send_dept_name = ''
  88. user_row = db.query(SysUser).filter(SysUser.user_id == send_user_id).first()
  89. if user_row is not None:
  90. send_user_name = user_row.user_name
  91. send_dept_row = db.query(SysDept).filter(SysDept.dept_id == user_row.dept_id).first()
  92. send_dept_name = send_dept_row.dept_name
  93. new_resp = InfoPublishResponses(
  94. publish_id = new_publish_id,
  95. user_id = send_user_id,
  96. user_name = send_user_name,
  97. nick_name = send_nick_name,
  98. dept_name = send_dept_name,
  99. sent_status = 0,
  100. response_type = body['response_type'],
  101. publish_channel = body['publish_channel']
  102. )
  103. db.add(new_resp)
  104. db.commit()
  105. # 附件
  106. if 'attachs' in body:
  107. infopublish_files = [
  108. InfoPublishFile(
  109. file_name=fileName["name"],
  110. storage_file_name=fileName["url"],
  111. file_path=f'/data/upload/mergefile/uploads/{fileName["url"]}',
  112. file_size=os.path.getsize(f'/data/upload/mergefile/uploads/{fileName["url"]}'),
  113. foreign_key=str(new_publish_id),
  114. from_scenario="infopublish_attach_file",
  115. update_time=datetime.now(),
  116. create_time=datetime.now(),
  117. create_by=user_id,
  118. create_dept=dept_id,
  119. del_flag='0',
  120. status=0,
  121. )
  122. for fileName in body['attachs']
  123. ]
  124. db.add_all(infopublish_files)
  125. db.commit()
  126. # 审批附件
  127. if 'examine_attachs' in body:
  128. infopublish_files = [
  129. InfoPublishFile(
  130. file_name=fileName["name"],
  131. storage_file_name=fileName["url"],
  132. file_path=f'/data/upload/mergefile/uploads/{fileName["url"]}',
  133. file_size=os.path.getsize(f'/data/upload/mergefile/uploads/{fileName["url"]}'),
  134. foreign_key=str(new_publish_id),
  135. from_scenario="infopublish_examine_attach_file",
  136. update_time=datetime.now(),
  137. create_time=datetime.now(),
  138. create_by=user_id,
  139. create_dept=dept_id,
  140. del_flag='0',
  141. status=0,
  142. )
  143. for fileName in body['examine_attachs']
  144. ]
  145. db.add_all(infopublish_files)
  146. db.commit()
  147. # 审批记录
  148. infopublish_examine = InfoPublishExamine(
  149. publish_id = new_publish_id,
  150. examine_type = 10, # 提交
  151. examine_sub_type = 10, # 提交
  152. examine_time = datetime.now(),
  153. content = '',
  154. user_id = user_id,
  155. user_name = user_name,
  156. nick_name = nick_name,
  157. del_flag = '0'
  158. )
  159. db.add(infopublish_examine)
  160. db.commit()
  161. # 改草稿、待审批状态
  162. db.query(InfoPublishBase).filter(InfoPublishBase.id == new_publish_id).update({"publish_status": 1, "examine_status": 1})
  163. db.commit()
  164. return {
  165. "code": 200,
  166. "msg": "信息创建成功",
  167. "data": new_publish_id
  168. }
  169. except Exception as e:
  170. traceback.print_exc()
  171. # 处理异常
  172. raise HTTPException(status_code=500, detail=str(e))
  173. # 信息发布分页查询
  174. @router.get('/list')
  175. async def get_publish_list(
  176. publish_group: str = Query('', description='发布单位'),
  177. publish_status: str = Query('', description='发布状态的字典键值'),
  178. examine_status: str = Query('', description='审批状态的字典键值'),
  179. dispose_status: str = Query('', description='处理状态的字典键值'),
  180. sort_by: str = Query('', description='排序字段'),
  181. sort_order: str = Query("asc", description='排序方式'),
  182. page: int = Query(1, gt=0, description='页码'),
  183. page_size: int = Query(10, gt=0, description='pageSize'),
  184. db: Session = Depends(get_db),
  185. user_id = Depends(valid_access_token)
  186. ):
  187. try:
  188. # 应用查询条件
  189. where = and_(InfoPublishBase.del_flag == '0')
  190. if publish_status not in ['', '0'] :
  191. where = and_(where, InfoPublishBase.publish_status == publish_status)
  192. if examine_status not in ['', '0'] :
  193. where = and_(where, InfoPublishBase.examine_status == examine_status)
  194. if publish_group != '':
  195. where = and_(where, InfoPublishBase.publish_group.like('%{}%'.format(publish_group)))
  196. if dispose_status not in ['', '0'] :
  197. where = and_(where, InfoPublishBase.examine_status == 1, InfoPublishBase.examine_by == user_id)
  198. print(where)
  199. # 计算总条目数
  200. q = db.query(func.count(InfoPublishBase.id))
  201. q = q.filter(where)
  202. total = q.scalar()
  203. # 执行分页查询
  204. q = db.query(InfoPublishBase)
  205. q = q.filter(where)
  206. rows = q.order_by(InfoPublishBase.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
  207. data = []
  208. for row in rows:
  209. # 发布申请人
  210. recorded_by = row.recorded_by
  211. user_row = db.query(SysUser).filter(SysUser.user_id == recorded_by).first()
  212. nick_name = ""
  213. dept_name = ""
  214. if user_row is not None:
  215. nick_name = user_row.nick_name
  216. dept_id = user_row.dept_id
  217. dept_row = db.query(SysDept).filter(SysDept.dept_id == dept_id).first()
  218. if dept_row is not None:
  219. dept_name = dept_row.dept_name
  220. # 待处理人
  221. examine_user = "无"
  222. examine_by = row.examine_by
  223. user_row = db.query(SysUser).filter(SysUser.user_id == examine_by).first()
  224. if user_row is not None:
  225. examine_user = user_row.nick_name
  226. data.append({
  227. "id": row.id,
  228. "title": row.title,
  229. "publish_group": row.publish_group,
  230. "content": row.content,
  231. "publish_time": get_datetime_str(row.publish_time),
  232. "publish_channel": row.publish_channel,
  233. "nick_name": nick_name,
  234. "dept_name": dept_name,
  235. "examine_user": examine_user,
  236. "publish_status": db_dict.get_dict_label(db, "mm_publish_status", row.publish_status),
  237. "examine_status": db_dict.get_dict_label(db, "mm_examine_status", row.examine_status),
  238. "user_count": row.user_count,
  239. "user_ok_count": row.user_ok_count,
  240. "user_err_count": row.user_err_count,
  241. "user_sending_count": row.user_sending_count,
  242. "is_my_edit": (row.examine_status == 0 or row.examine_status == 9) and row.recorded_by == user_id, # 是否我的编辑事项
  243. "is_my_examine": row.examine_status == 1 and int(row.examine_by) == user_id # 是否我的审批事项
  244. })
  245. # 返回结果
  246. return {
  247. "code": 200,
  248. "msg": "查询成功",
  249. "data": data,
  250. "total": total
  251. }
  252. except Exception as e:
  253. # 处理异常
  254. traceback.print_exc()
  255. raise HTTPException(status_code=500, detail=str(e))
  256. # 信息发布查看
  257. @router.get('/edit')
  258. async def get_edit_info(
  259. request: Request,
  260. info_id: str = Query(None, description='信息ID'),
  261. db: Session = Depends(get_db)):
  262. row = db.query(InfoPublishBase).filter(InfoPublishBase.id == info_id).first()
  263. data = get_model_dict(row)
  264. data['add_time'] = get_datetime_str(data['add_time'])
  265. data['publish_time'] = get_datetime_str(data['publish_time'])
  266. # 反馈 && 未反馈
  267. data['feedback_count'] = db.query(InfoPublishResponses).filter(and_(InfoPublishResponses.publish_id == info_id, InfoPublishResponses.sent_status > 0, InfoPublishResponses.response_type > 0)).count()
  268. data['unresponsive_count'] = db.query(InfoPublishResponses).filter(and_(InfoPublishResponses.publish_id == info_id, InfoPublishResponses.sent_status > 0, InfoPublishResponses.response_type > 0)).count()
  269. # 附件
  270. rows = db.query(InfoPublishFile).filter(and_(InfoPublishFile.from_scenario=="infopublish_attach_file", InfoPublishFile.foreign_key == info_id, InfoPublishFile.del_flag == '0')).all()
  271. data['attachs'] = [
  272. {
  273. "name": row.file_name,
  274. "url": row.storage_file_name
  275. }
  276. for row in rows
  277. ]
  278. # 审批附件
  279. rows = db.query(InfoPublishFile).filter(and_(InfoPublishFile.from_scenario=="infopublish_examine_attach_file", InfoPublishFile.foreign_key == info_id, InfoPublishFile.del_flag == '0')).all()
  280. data['examine_attachs'] = [
  281. {
  282. "name": row.file_name,
  283. "url": row.storage_file_name
  284. }
  285. for row in rows
  286. ]
  287. data["examines"] = []
  288. rows = db.query(InfoPublishExamine).filter(InfoPublishExamine.publish_id == info_id).filter(InfoPublishExamine.del_flag == '0').all()
  289. for row in rows:
  290. data["examines"].append({
  291. "examine_type": EXAMINE_TYPE_DICT[row.examine_type],
  292. "examine_sub_type": EXAMINE_SUB_TYPE_DICT[row.examine_sub_type],
  293. "content": row.content,
  294. "examine_time": get_datetime_str(row.examine_time),
  295. "user_id": row.user_id,
  296. "user_name": row.user_name,
  297. "nick_name": row.nick_name
  298. })
  299. return {
  300. "code": 200,
  301. "msg": "查询成功",
  302. "data": data
  303. }
  304. # 信息发布编辑保存
  305. @router.post('/edit')
  306. async def post_edit_info(
  307. request: Request,
  308. body = Depends(remove_xss_json),
  309. db: Session = Depends(get_db),
  310. user_id = Depends(valid_access_token)):
  311. try:
  312. id = body['id']
  313. remove_req_param(body, 'info_id')
  314. examines = body['examines']
  315. remove_req_param(body, 'examines')
  316. body['recorded_by'] = user_id
  317. db.query(InfoPublishBase).filter(InfoPublishBase.id == id).update(body)
  318. db.commit()
  319. return {
  320. "code": 200,
  321. "msg": "保存信息成功"
  322. }
  323. except Exception as e:
  324. # 处理异常
  325. traceback.print_exc()
  326. raise HTTPException(status_code=500, detail=str(e))
  327. # 信息发布提交审核
  328. @router.post('/examine')
  329. async def post_examine_info(
  330. request: Request,
  331. body = Depends(remove_xss_json),
  332. db: Session = Depends(get_db),
  333. user_id = Depends(valid_access_token)):
  334. user_row = db.query(SysUser).filter(SysUser.user_id == user_id).first()
  335. new_examine = InfoPublishExamine(
  336. pubish_id = body['info_id'],
  337. examine_type = body['examine_type'],
  338. examine_sub_type = body['examine_sub_type'],
  339. content = body['content'],
  340. examine_time = datetime.now(),
  341. user_id = user_id,
  342. user_name = user_row.user_name,
  343. nick_name = user_row.nick_name
  344. )
  345. db.add(new_examine)
  346. db.commit()
  347. return {
  348. "code": 200,
  349. "msg": "保存审批记录成功"
  350. }
  351. # 信息发布查看发送列表
  352. @router.get("/sent_list")
  353. async def get_sent_list(
  354. info_id: str = Query('', description='信息ID'),
  355. channel: str = Query('', description='渠道'),
  356. keywords: str = Query('', description='关键字'),
  357. sort_by: str = Query('', description='排序字段'),
  358. sort_order: str = Query("asc", description='排序方式'),
  359. page: int = Query(1, gt=0, description='页码'),
  360. page_size: int = Query(10, gt=0, description='pageSize'),
  361. db: Session = Depends(get_db)
  362. ):
  363. try:
  364. # 应用查询条件
  365. where = and_(InfoPublishResponses.publish_id == info_id)
  366. if channel != '':
  367. where = and_(where, InfoPublishResponses.publish_channel.like('%{}%'.format(channel)))
  368. # 计算总条目数
  369. q = db.query(func.count(InfoPublishResponses.id))
  370. q = q.filter(where)
  371. total = q.scalar()
  372. # 执行分页查询
  373. q = db.query(InfoPublishResponses)
  374. q = q.filter(where)
  375. rows = q.order_by(InfoPublishResponses.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
  376. data = [
  377. {
  378. "user_id": row.user_id,
  379. "user_name": row.user_name,
  380. "nick_name": row.nick_name,
  381. "dept_name": row.dept_name,
  382. "sent_status": row.sent_status,
  383. "sent_time": get_datetime_str(row.sent_time),
  384. "response_type": row.response_type,
  385. "publish_channel": row.publish_channel,
  386. "yzy_account": row.yzy_account
  387. }
  388. for row in rows
  389. ]
  390. # 返回结果
  391. return {
  392. "code": 200,
  393. "msg": "查询成功",
  394. "data": data,
  395. "total": total
  396. }
  397. except Exception as e:
  398. # 处理异常
  399. traceback.print_exc()
  400. raise HTTPException(status_code=500, detail=str(e))
  401. # 列出可用模板
  402. @router.post("/template_list")
  403. def template_list(db: Session = Depends(get_db)):
  404. try:
  405. rows = db.query(InfoPublishTemplate).filter(InfoPublishTemplate.del_flag == '0').all()
  406. data = [
  407. {
  408. "id": row.id,
  409. "name": row.name,
  410. "content": row.content
  411. }
  412. for row in rows
  413. ]
  414. return {
  415. "code": 200,
  416. "msg": "查询成功",
  417. "data": data,
  418. "total": len(data)
  419. }
  420. except Exception as e:
  421. # 处理异常
  422. traceback.print_exc()
  423. raise HTTPException(status_code=500, detail=str(e))
  424. # 提交审批
  425. @router.post("/submit_examine")
  426. async def submit_examine(
  427. db: Session = Depends(get_db),
  428. body = Depends(remove_xss_json),
  429. user_id = Depends(valid_access_token)
  430. ):
  431. try:
  432. user_row = db.query(SysUser).filter(SysUser.user_id == user_id).first()
  433. info_id = body['info_id']
  434. examine_type = body['examine_type']
  435. content = body['content']
  436. # 审批通过
  437. if examine_type == 'approved':
  438. new_examine = InfoPublishExamine(
  439. publish_id = info_id,
  440. examine_type = 20,
  441. examine_sub_type = 21,
  442. content = content,
  443. examine_time = datetime.now(),
  444. user_id = user_id,
  445. user_name = user_row.user_name,
  446. nick_name = user_row.nick_name
  447. )
  448. db.add(new_examine)
  449. db.commit()
  450. db.query(InfoPublishBase).filter(InfoPublishBase.id == info_id).update({"publish_status": 3, "examine_status": 2})
  451. db.commit()
  452. # 审批不通过
  453. elif examine_type == 'rejected':
  454. new_examine = InfoPublishExamine(
  455. publish_id = info_id,
  456. examine_type = 20,
  457. examine_sub_type = 22,
  458. content = content,
  459. examine_time = datetime.now(),
  460. user_id = user_id,
  461. user_name = user_row.user_name,
  462. nick_name = user_row.nick_name
  463. )
  464. db.add(new_examine)
  465. db.commit()
  466. db.query(InfoPublishBase).filter(InfoPublishBase.id == info_id).update({"publish_status": 0, "examine_status": 0})
  467. db.commit()
  468. return {
  469. "code": 200,
  470. "msg": "审批成功"
  471. }
  472. except Exception as e:
  473. # 处理异常
  474. traceback.print_exc()
  475. raise HTTPException(status_code=500, detail=str(e))