addressbook.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. from fastapi import APIRouter, Request, Depends, HTTPException, Query, Body
  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. from sqlalchemy import create_engine, select
  12. from typing import Optional
  13. from utils.StripTagsHTMLParser import *
  14. from common.db import db_event_management, db_user, db_area, db_emergency_plan
  15. from common.security import valid_access_token
  16. import traceback
  17. from utils import *
  18. from datetime import datetime, timedelta
  19. from common.db import db_dict
  20. from urllib.parse import quote
  21. import base64
  22. from config import settings
  23. from pydantic import BaseModel
  24. from typing import List, Dict,Set
  25. router = APIRouter()
  26. def get_dept_tree(db: Session, dept_id: int, tag_ids: Optional[Set[int]] = None) -> Dict:
  27. dept = db.query(SysDept).filter(SysDept.dept_id == dept_id).first()
  28. if not dept:
  29. return None
  30. # 收集祖先部门名称
  31. ancestors_names = []
  32. current_dept = dept
  33. while current_dept:
  34. ancestors_names.append(current_dept.dept_name)
  35. current_dept = db.query(SysDept).filter(SysDept.dept_id == current_dept.parent_id).first()
  36. ancestors_names.reverse()
  37. # 获取部门标签
  38. dept_tags = db.query(SysDeptTag).filter(SysDeptTag.dept_id == dept.dept_id).all()
  39. dept_tags_info = [{"tag_id": tag.tag_id, "tag_name": tag.tag_name} for tag in db.query(DeptTag).filter(DeptTag.tag_id.in_([tag.tag_id for tag in dept_tags])).all()]
  40. # 如果提供了标签ID参数,检查部门是否有匹配的标签
  41. if tag_ids and not any(tag['tag_id'] in tag_ids for tag in dept_tags_info):
  42. # 如果没有匹配的标签,检查子部门是否有匹配的标签
  43. child_with_tag = False
  44. for child in db.query(SysDept).filter(SysDept.parent_id == dept.dept_id).all():
  45. if get_dept_tree(db, child.dept_id, tag_ids) is not None:
  46. child_with_tag = True
  47. break
  48. if not child_with_tag:
  49. return None # 如果子部门也没有匹配的标签,则不包含该部门
  50. # 获取用户标签
  51. def get_user_tags(user_id):
  52. user_tags_subquery = db.query(SysUserTag.tag_id).filter(SysUserTag.user_id == user_id).subquery()
  53. tags = db.query(SysTag).filter(SysTag.tag_id.in_(user_tags_subquery)).all()
  54. return [{"tag_id": tag.tag_id, "tag_name": tag.tag_name} for tag in tags]
  55. # 获取部门下的用户
  56. users_info = []
  57. for user in db.query(SysUser).filter(SysUser.dept_id == dept.dept_id).all():
  58. user_tags_info = get_user_tags(user.user_id)
  59. # 如果提供了标签ID参数,检查用户是否有匹配的标签
  60. if tag_ids and not any(tag['tag_id'] in tag_ids for tag in user_tags_info):
  61. continue # 如果用户没有匹配的标签,则不包含该用户
  62. users_info.append({
  63. "user_id": user.user_id,
  64. "dept_id": user.dept_id,
  65. "position": "无",
  66. "user_name": user.user_name,
  67. "email": user.email,
  68. "user_tags": user_tags_info
  69. })
  70. # 构建子部门树
  71. child_trees = [get_dept_tree(db, child.dept_id, tag_ids) for child in db.query(SysDept).filter(SysDept.parent_id == dept.dept_id).all()]
  72. child_trees = [child for child in child_trees if child]
  73. dept_info = {
  74. "dept_id": dept.dept_id,
  75. "parent_id": dept.parent_id,
  76. "ancestors": '/'.join(ancestors_names),
  77. "dept_name": dept.dept_name,
  78. "tags": dept_tags_info,
  79. "users": users_info,
  80. "children": child_trees
  81. }
  82. return dept_info
  83. @router.get("/alldepts", response_model=Dict)
  84. def read_all_depts(db: Session = Depends(get_db), tag_ids: List[int] = Query(None, title="Tag IDs")):
  85. tag_ids_set = set(tag_ids) if tag_ids else None
  86. top_level_depts = get_dept_tree(db, 3, tag_ids_set)
  87. if not top_level_depts:
  88. raise HTTPException(status_code=404, detail="Department not found")
  89. # return [top_level_depts]
  90. return {
  91. "code": 200,
  92. "msg": "成功",
  93. "data": top_level_depts
  94. }
  95. class DeptTagInfo(BaseModel):
  96. tag_id: int
  97. tag_name: str
  98. @router.get("/depts", response_model=Dict)
  99. def get_dept(db: Session = Depends(get_db)):
  100. dept_tags = db.query(DeptTag).all()
  101. # 如果没有找到记录,返回404错误
  102. if not dept_tags:
  103. raise HTTPException(status_code=404, detail="No dept tags found")
  104. dept_tags_data = [
  105. DeptTagInfo(tag_id=dept_tag.tag_id,tag_name=dept_tag.tag_name)
  106. for dept_tag in dept_tags
  107. ]
  108. return {
  109. "code": 200,
  110. "msg": "成功",
  111. "data": dept_tags_data
  112. }
  113. class User(BaseModel):
  114. user_id: int
  115. user_name: str
  116. # nick_name: str
  117. class TagIDs(BaseModel):
  118. tag_ids: List[int]
  119. @router.post("/users_by_tags")
  120. def read_users_by_tags(
  121. db: Session = Depends(get_db),
  122. tag_ids_data: TagIDs = Body(...)
  123. ):
  124. # 提取tag_ids
  125. tag_ids = tag_ids_data.tag_ids
  126. if not tag_ids:
  127. raise HTTPException(status_code=400, detail="Tag IDs are required")
  128. # 构建查询条件
  129. conditions = [SysUserTag.tag_id == tag_id for tag_id in tag_ids]
  130. query = db.query(SysUser).join(SysUserTag, SysUser.user_id == SysUserTag.user_id).filter(or_(*conditions))
  131. distinct_user_count = db.query(SysUserTag.user_id).filter(SysUserTag.tag_id.in_(tag_ids)).count()
  132. # 执行查询并去重 这里的去重只是单纯的用户标签去重,如果有多用户的得看到时候实际数据再规划如何去重
  133. users_with_tags = query.distinct().all()
  134. non_distinct_user_count = len(users_with_tags)
  135. print(distinct_user_count,non_distinct_user_count)
  136. # 如果没有找到用户,返回404错误
  137. if not users_with_tags:
  138. raise HTTPException(status_code=404, detail="No users found for the given tag IDs")
  139. # 将用户模型转换为User Pydantic模型列表
  140. users_data = [
  141. User(user_id=user.user_id, user_name=user.user_name)
  142. for user in users_with_tags
  143. ]
  144. return {
  145. "code": 200,
  146. "msg": "成功",
  147. "distinct_user_count":distinct_user_count,
  148. "non_distinct_user_count":non_distinct_user_count,
  149. "data": users_data
  150. }
  151. class TagTree(BaseModel):
  152. tag_id: int
  153. tag_name: str
  154. parent_id: int
  155. children: List['TagTree'] = []
  156. # 递归构建树形结构
  157. def build_tree(tags, parent_id=0):
  158. tree = []
  159. for tag in tags:
  160. if tag.parent_id == parent_id:
  161. children = build_tree(tags, tag.tag_id)
  162. tree.append(TagTree(tag_id=tag.tag_id, tag_name=tag.tag_name, parent_id=tag.parent_id, children=children))
  163. return tree
  164. @router.post("/tags_tree")
  165. def get_tag_tree(
  166. db: Session = Depends(get_db),
  167. tag_ids_data: TagIDs = Body(...)
  168. ):
  169. # 提取tag_ids
  170. tag_ids = tag_ids_data.tag_ids
  171. if not tag_ids:
  172. raise HTTPException(status_code=400, detail="Tag IDs are required")
  173. # 查询所有相关的标签
  174. tags = db.query(SysTag).filter(SysTag.tag_id.in_(tag_ids)).all()
  175. # 如果没有找到标签,返回404错误
  176. if not tags:
  177. raise HTTPException(status_code=404, detail="Tags not found for the given tag IDs")
  178. # 构建标签树
  179. tag_tree = build_tree(tags)
  180. return {
  181. "code": 200,
  182. "msg": "成功",
  183. "data": tag_tree
  184. }
  185. class TagData(BaseModel):
  186. user_ids: List[int]
  187. tag_name: str
  188. @router.post("/add_common_list_tags")
  189. def add_common_list_tags(
  190. db: Session = Depends(get_db),
  191. data: TagData = Body(...)
  192. ):
  193. user_ids = data.user_ids
  194. tag_name = data.tag_name
  195. if not user_ids or not tag_name:
  196. raise HTTPException(status_code=tag_name, detail="User IDs and Tag Name are required")
  197. # 查询标签是否存在
  198. tag = db.query(Common_List_Tags).filter(Common_List_Tags.tag_name == tag_name).first()
  199. print(tag)
  200. # print(tag.tag_id)
  201. # 如果标签不存在,则创建新标签
  202. if not tag:
  203. tag = Common_List_Tags(tag_name=tag_name)
  204. db.add(tag)
  205. db.commit()
  206. tag_id = tag.tag_id
  207. else:
  208. tag_id = tag.tag_id
  209. # 为每个用户ID插入记录,如果已存在则跳过
  210. for user_id in user_ids:
  211. existing_record = db.query(Sys_Common_List_Tags).filter_by(user_id=user_id, tag_id=tag_id).first()
  212. if not existing_record:
  213. db.add(Sys_Common_List_Tags(user_id=user_id, tag_id=tag_id))
  214. db.commit()
  215. return {"code": 200,"msg": "操作成功", "tag_id": tag_id}
  216. class TagUserCount(BaseModel):
  217. tag_id: int
  218. tag_name: str
  219. user_count: int
  220. @router.get("/tags_user_count", response_model=Dict)
  221. def get_tags_user_count(db: Session = Depends(get_db)):
  222. # 查询所有标签
  223. tags = db.query(Common_List_Tags).all()
  224. # 如果没有找到标签,返回404错误
  225. if not tags:
  226. raise HTTPException(status_code=404, detail="No tags found")
  227. # 构建结果列表
  228. result = []
  229. for tag in tags:
  230. # 查询与标签相关的用户数量
  231. user_count = db.query(Sys_Common_List_Tags).filter(Sys_Common_List_Tags.tag_id == tag.tag_id).count()
  232. result.append(TagUserCount(tag_id=tag.tag_id, tag_name=tag.tag_name, user_count=user_count))
  233. return {
  234. "code": 200,
  235. "msg": "成功",
  236. "data": result
  237. }