doc.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. from fastapi import APIRouter, Request, Depends, HTTPException, Query,status
  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 os
  11. import random
  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 xlrd
  21. router = APIRouter()
  22. # 目录在文档上传接口写死
  23. UPLOAD_mergefile_PATH = '/data/upload/mergefile'
  24. # 获取预案结构化文档
  25. @router.post('/detail')
  26. async def doc(
  27. request: Request,
  28. db: Session = Depends(get_db),
  29. body = Depends(remove_xss_json),
  30. user_id = Depends(valid_access_token)
  31. ):
  32. plan_id = body['plan_id']
  33. items = []
  34. rows = db.query(EmergencyDoc).filter(and_(EmergencyDoc.pid == 0, EmergencyDoc.plan_id == plan_id)).all()
  35. for row in rows:
  36. items.append(get_item_data(db, row.id, 1))
  37. return {
  38. 'code': 200,
  39. 'msg': '查询成功',
  40. 'data': items
  41. }
  42. def get_item_data(db: Session, id: int, level: int):
  43. data = []
  44. row = db.query(EmergencyDoc).filter(EmergencyDoc.id == id).first()
  45. if row is not None:
  46. pid = row.id
  47. data = get_model_dict(row)
  48. data['level'] = level
  49. if data['value'] is None:
  50. data['value'] = ''
  51. if level == 2:
  52. rows = db.query(EmergencyDoc).filter(EmergencyDoc.pid == pid).all()
  53. if len(rows) > 0:
  54. value_level3 = "<p>"
  55. for row in rows:
  56. title3 = row.title
  57. value3 = row.value
  58. if title3 != "":
  59. value_level3 = value_level3 + "<strong>" + title3 + "</strong></p><p>"
  60. if value3 != "":
  61. value_level3 = value_level3 + format_value(value3) + "</p><p>"
  62. data['value'] = data['value'] + value_level3 + "</p>"
  63. data['items'] = []
  64. rows = db.query(EmergencyDoc).filter(EmergencyDoc.pid == pid).all()
  65. for row in rows:
  66. item = get_item_data(db, row.id, level + 1)
  67. data['items'].append(item)
  68. if len(data['items']) == 0 and level == 2:
  69. del data['items']
  70. data['id'] = data['plan_id']+str(data['id'])
  71. data['href'] = "#" + data['id']
  72. data['containerRef'] = "containerRef" + data['id']
  73. data['value'] = format_value(data['value'])
  74. return data
  75. def format_value(value: str) -> str:
  76. return value.replace("\r\n", "</p><p>").replace("\n", "</p><p>")
  77. @router.post('/import')
  78. async def import_doc(
  79. request: Request,
  80. db: Session = Depends(get_db),
  81. body = Depends(remove_xss_json),
  82. user_id = Depends(valid_access_token)
  83. ):
  84. # print(body)
  85. try:
  86. plan_id = body['plan_id']
  87. filename = body['filename']
  88. if len(filename) == 0:
  89. raise Exception()
  90. file = filename[0]
  91. url = file['url']
  92. file_path = f"{UPLOAD_mergefile_PATH}/uploads/{url}"
  93. file_path = os.path.abspath(file_path)
  94. print(file_path)
  95. book = xlrd.open_workbook(file_path)
  96. sheet = book.sheet_by_index(0)
  97. data = []
  98. for i in range(9, sheet.nrows):
  99. # 预案名称
  100. plan_name = sheet.cell(i, 0).value
  101. # 一级目录
  102. title1 = sheet.cell(i, 1).value
  103. # 二级目录
  104. title2 = sheet.cell(i, 2).value
  105. # 三级目录
  106. title3 = sheet.cell(i, 3).value
  107. # 正文
  108. content = sheet.cell(i, 4).value
  109. if len(plan_name) < 1 and len(title1) < 1 and len(title2) < 1 and len(title3) < 1 and len(content) < 1 :
  110. break
  111. data.append({
  112. 'plan_name': plan_name,
  113. 'title1': title1,
  114. 'title2': title2,
  115. 'title3': title3,
  116. 'content': content,
  117. })
  118. if len(data) > 0:
  119. db.query(EmergencyDoc).filter(EmergencyDoc.plan_id == plan_id).delete()
  120. db.commit()
  121. title1 = ''
  122. content = ''
  123. docs = []
  124. for n in data:
  125. if n['title1'] != '':
  126. if len(docs) > 0:
  127. add_doc_1(db, title1, content, docs, plan_id)
  128. docs = []
  129. title1 = n['title1']
  130. content = n['content']
  131. if n['title2'] != '':
  132. docs.append(n)
  133. continue
  134. docs.append(n)
  135. if len(docs) > 0:
  136. add_doc_1(db, title1, content, docs, plan_id)
  137. return {
  138. 'code': 200,
  139. 'msg': '导入成功'
  140. }
  141. except Exception:
  142. traceback.print_exc()
  143. return {
  144. 'code': 500,
  145. 'msg': '导入发生异常'
  146. }
  147. def add_doc_1(db: Session, title: str, content: str, docs: list, plan_id: str):
  148. print(title)
  149. print(docs)
  150. # 一级记录
  151. main_entity = EmergencyDoc(title = title, value= content, pid = 0, plan_id = plan_id)
  152. db.add(main_entity)
  153. db.commit()
  154. db.refresh(main_entity)
  155. main_id = main_entity.id
  156. print('main_id: ', main_id, 1)
  157. title2 = ''
  158. content = ''
  159. docs_2 = []
  160. for n in docs:
  161. if n['title2'] != '':
  162. if len(docs_2) > 0:
  163. add_doc_2(db, title2, content, docs_2, plan_id, main_id)
  164. docs_2 = []
  165. title2 = n['title2']
  166. content = n['content']
  167. docs_2.append(n)
  168. continue
  169. docs_2.append(n)
  170. if len(docs_2) > 0:
  171. add_doc_2(db, title2, content, docs_2, plan_id, main_id)
  172. def add_doc_2(db: Session, title: str, content: str, docs: list, plan_id: str, pid: int):
  173. # 二级记录
  174. main_entity = EmergencyDoc(title = title, value= content, pid = pid, plan_id = plan_id)
  175. db.add(main_entity)
  176. db.commit()
  177. db.refresh(main_entity)
  178. main_id = main_entity.id
  179. print('main_id: ', main_id, 2)
  180. i = 0
  181. for n in docs:
  182. i = i + 1
  183. # 第一行是二级记录
  184. if i == 1:
  185. continue
  186. sub_entity = EmergencyDoc(title = n['title3'], value= n['content'], pid = main_id, plan_id = plan_id)
  187. db.add(sub_entity)
  188. db.commit()
  189. db.refresh(sub_entity)
  190. sub_id = sub_entity.id
  191. print('sub_id: ', sub_id, 3)