__init__.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. from fastapi import APIRouter, Request, Depends, Query, HTTPException, status
  4. from common.security import valid_access_token
  5. from pydantic import BaseModel
  6. from database import get_db
  7. from sqlalchemy import text
  8. from sqlalchemy.orm import Session
  9. from typing import List
  10. from models import *
  11. from utils import *
  12. from utils.ry_system_util import *
  13. import json
  14. from sqlalchemy.sql import func
  15. from common.enc import mpfun, sys_menu_data, sys_menu_layer_data
  16. from common.auth_user import *
  17. from common.db import db_czrz
  18. import traceback
  19. from exceptions import HmacException
  20. router = APIRouter()
  21. # 定义 Meta 和 Child 模型用于嵌套结构
  22. class Meta(BaseModel):
  23. title: str
  24. icon: str
  25. noCache: bool
  26. link: str = None
  27. class Child(BaseModel):
  28. name: str
  29. path: str
  30. hidden: bool
  31. component: str
  32. meta: Meta
  33. children: List['Child'] = []
  34. class Router(BaseModel):
  35. name: str
  36. path: str
  37. hidden: bool
  38. redirect: str = 'noRedirect'
  39. component: str
  40. alwaysShow: bool = True
  41. meta: Meta
  42. children: List[Child] = []
  43. class Router_frame(BaseModel):
  44. component:str
  45. hidden: bool
  46. meta:Meta
  47. name: str
  48. path: str
  49. redirect: str = 'noRedirect'
  50. children: List[Child] = []
  51. alwaysShow: bool = True
  52. # checkedKeys roleMenuTreeselect
  53. @router.get('/roleMenuTreeselect/{roleId}')
  54. async def getmunutreeselect(request: Request,roleId:int,db: Session = Depends(get_db), user_id: int = Depends(valid_access_token)):
  55. def build_dept_tree(menus, parent_dept):
  56. menu_tree = []
  57. for menu_info in menus:
  58. menu = {
  59. "id": menu_info.menu_id,
  60. "label": menu_info.menu_name,
  61. "parentId": menu_info.parent_id,
  62. "weight": menu_info.order_num
  63. }
  64. # print(dept_info.dept_id)
  65. children = parent_id_get_menu_info(db, menu_info.menu_id)
  66. if len(children) > 0:
  67. children_depts = build_dept_tree(children, menu)
  68. menu["children"] = children_depts
  69. menu_tree.append(menu)
  70. return menu_tree
  71. checkedKeys = role_id_get_role_menus(db,roleId)
  72. menus = build_dept_tree(parent_id_get_menu_info(db, 0), None)
  73. return {
  74. "code": 200,
  75. "msg": "操作成功",
  76. "data": {"menus":menus,"checkedKeys":checkedKeys}
  77. }
  78. @router.get('/treeselect')
  79. async def getmunutreeselect(request: Request,db: Session = Depends(get_db), user_id: int = Depends(valid_access_token)):
  80. def build_dept_tree(menus, parent_dept):
  81. menu_tree = []
  82. for menu_info in menus:
  83. menu = {
  84. "id": menu_info.menu_id,
  85. "label": menu_info.menu_name,
  86. "parentId": menu_info.parent_id,
  87. "weight": menu_info.order_num
  88. }
  89. # print(dept_info.dept_id)
  90. children = parent_id_get_menu_info(db, menu_info.menu_id)
  91. if len(children) > 0:
  92. children_depts = build_dept_tree(children, menu)
  93. menu["children"] = children_depts
  94. menu_tree.append(menu)
  95. return menu_tree
  96. result = build_dept_tree(parent_id_get_menu_info(db, 0), None)
  97. return {
  98. "code": 200,
  99. "msg": "操作成功",
  100. "data": result
  101. }
  102. @router.get('/getRouters')
  103. async def getRouters(request: Request, db: Session = Depends(get_db),
  104. body = Depends(remove_xss_json),
  105. user_id = Depends(valid_access_token)):
  106. try:
  107. # 查询数据库中的所有菜单项,根据 parent_id 排序以构建树形结构
  108. query = db.query(SysMenu)
  109. query = query.filter_by(parent_id=0)
  110. query = query.filter(SysMenu.menu_id!=11655)
  111. query = query.filter(SysMenu.del_flag != '2')
  112. query = query.order_by(SysMenu.order_num.asc())
  113. menus = query.all() # 顶级菜单
  114. # 递归函数用于构建树形结构
  115. def build_menu_tree(menus, parent_menu):
  116. menu_tree = [] # 初始化一个列表来存储菜单树结构
  117. for menu in menus:
  118. # 是否我所在角色的菜单
  119. if is_role_menu(menu.menu_id, user_id, db) != True:
  120. continue
  121. if sys_menu_data.sign_valid_row(menu) == False:
  122. raise HmacException(500, "系统菜单表验证异常,已被非法篡改")
  123. component = 'Layout'
  124. if menu.menu_type=='M' and parent_menu:
  125. component = 'ParentView'
  126. if menu.component:
  127. component= menu.component
  128. # print(menu.menu_name)
  129. menu_data = {
  130. "component":component,
  131. "hidden":menu.visible == '1',
  132. "name":menu.path,
  133. "path":'/'+menu.path,
  134. # "redirect":'noRedirect',
  135. # "alwaysShow":True,
  136. "meta":{
  137. "title":menu.menu_name,
  138. 'icon' : menu.icon,
  139. 'noCache' : menu.is_cache == '1',
  140. }
  141. }
  142. if menu.is_frame==0:
  143. menu_data['meta']['link']=menu.path
  144. # 如果菜单有子菜单,则递归构建子菜单
  145. if menu.menu_type == 'M': # 假设 'M' 表示目录类型
  146. # query = db.query(SysMenu)
  147. # query = query.filter_by(parent_id=menu.menu_id)
  148. # query = query.filter(SysMenu.del_flag != '2')
  149. # children_menus = db.query(SysMenu).filter_by(parent_id=menu.menu_id).all()
  150. # children_menus = query.all()
  151. menu_data['redirect'] ='noRedirect'
  152. menu_data['alwaysShow'] =True
  153. children_menus = parent_id_get_menu_info(db,menu.menu_id)
  154. if len(children_menus)>0:
  155. menu_data['children'] = build_menu_tree(children_menus, menu)
  156. elif menu.menu_type == 'C' and parent_menu is None:
  157. menu_data['path'] = '/index'
  158. menu_data['component'] = "Layout"
  159. menu_data['redirect'] = '/index'
  160. menu_data['children'] = [{"path":'',
  161. "component":component,
  162. "name":menu.path,
  163. "meta": { 'title': menu.menu_name, 'icon': menu.icon,'noCache' : menu.is_cache == '1'}}]
  164. if menu.parent_id==0:
  165. pass
  166. else:
  167. menu_data['path'] = menu_data['path'][1:]
  168. menu_tree.append(menu_data) # 将当前菜单数据添加到菜单树列表
  169. return menu_tree
  170. # 是否我所在角色的菜单
  171. def is_role_menu(menu_id: int, user_id: int, db: Session):
  172. # 是否超级管理员
  173. sql = text("select * from sys_user_role where user_id = :user_id and role_id = 1")
  174. rows = db.execute(sql, {"user_id": user_id}).fetchall()
  175. if len(rows) > 0:
  176. return True
  177. sql = text("select menu_id from sys_role_menu inner join sys_user_role on sys_role_menu.role_id = sys_user_role.role_id where sys_role_menu.menu_id = :menu_id and sys_user_role.user_id = :user_id")
  178. rows = db.execute(sql, {"menu_id": menu_id, "user_id": user_id}).fetchall()
  179. return len(rows) > 0
  180. # 构建顶级菜单的树形结构
  181. routers = build_menu_tree(menus, None)
  182. # routers_dict = [router.dict() for router in routers]
  183. # routers_dict = []
  184. # for router in routers:
  185. # router_info = router.dict()
  186. # if len(router_info['children'])==0:
  187. # del router_info['children']
  188. # del router_info['redirect']
  189. # del router_info['alwaysShow']
  190. # router_info['path'] = router_info['path'] #[1:]
  191. #
  192. # routers_dict.append(router_info)
  193. # 返回构建好的路由数据
  194. return {
  195. "code": 200,
  196. "msg": "操作成功",
  197. "data": routers #[router.dict() for router in routers] # 如果没有顶级菜单,返回空列表
  198. }
  199. except HmacException as e:
  200. return {
  201. "code": e.code,
  202. "msg": e.msg
  203. }
  204. except Exception as e:
  205. traceback.print_exc()
  206. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  207. def get_video_routers(db:Session):
  208. from utils.video_util import tag_get_video_tag_list
  209. query = db.query(SysDictData)
  210. query = query.filter(SysDictData.dict_type == 'video_type')
  211. query = query.filter(SysDictData.del_flag != '2')
  212. query = query.order_by(SysDictData.dict_sort)
  213. # dict_data = db.query(SysDictData).filter_by(dict_type==dict_type and del_flag != '2').all()
  214. dict_data = query.all()
  215. # 将模型转换为字典
  216. dict_data_list = [{
  217. "component": '4',
  218. "isVideo":False,
  219. "hidden": True,
  220. "name": '4',
  221. "path": '2',
  222. # "redirect":'noRedirect',
  223. # "alwaysShow":True,
  224. "meta": {
  225. "title": '附近视频',
  226. 'icon': 'icon6',
  227. 'noCache': False,
  228. }
  229. }]
  230. for d in dict_data:
  231. li = tag_get_video_tag_list(db, d.dict_value)
  232. if len(li) > 0:
  233. dict_data_list.append({
  234. "component": d.dict_value or 'Layout',
  235. "isVideo":True,
  236. "hidden": True,
  237. "name": d.dict_value,
  238. "path": '2',
  239. # "redirect":'noRedirect',
  240. # "alwaysShow":True,
  241. "meta": {
  242. "title": d.dict_label,
  243. 'icon': 'icon6',
  244. 'noCache': False,
  245. }
  246. })
  247. return dict_data_list
  248. @router.get('/qydt/getRouters')
  249. async def getRouters(request: Request, db: Session = Depends(get_db),
  250. body = Depends(remove_xss_json),
  251. user_id = Depends(valid_access_token)):
  252. try:
  253. # 查询数据库中的所有菜单项,根据 parent_id 排序以构建树形结构
  254. query = db.query(SysMenu)
  255. query = query.filter_by(parent_id=0)
  256. query = query.filter(SysMenu.menu_id==11655)
  257. query = query.filter(SysMenu.del_flag != '2')
  258. query = query.order_by(SysMenu.order_num.asc())
  259. menus =query.all() # 顶级菜单
  260. # 递归函数用于构建树形结构
  261. def build_menu_tree(menus, parent_menu):
  262. menu_tree = [] # 初始化一个列表来存储菜单树结构
  263. for menu in menus:
  264. # if sys_menu_layer_data.sign_valid_row(menu) == False:
  265. # raise HmacException(500, "系统图层菜单表验证异常,已被非法篡改")
  266. menu_data = {
  267. "component": menu.component or 'Layout',
  268. "isVideo":False,
  269. "hidden": menu.visible == '1',
  270. "name": menu.path,
  271. "path": '/' + menu.path,
  272. # "redirect":'noRedirect',
  273. # "alwaysShow":True,
  274. "meta": {
  275. "title": menu.menu_name,
  276. 'icon': menu.icon,
  277. 'noCache': menu.is_cache == '1',
  278. }
  279. }
  280. if menu.is_frame == 0:
  281. menu_data['meta']['link'] = menu.path
  282. # 如果菜单有子菜单,则递归构建子菜单
  283. if menu.menu_type == 'M': # 假设 'M' 表示目录类型
  284. menu_data['redirect'] = 'noRedirect'
  285. menu_data['alwaysShow'] = True
  286. if menu.menu_id==11684:
  287. menu_data['children']= get_video_routers(db)
  288. menu_tree.append(menu_data)
  289. continue
  290. query = db.query(SysMenu)
  291. query = query.filter_by(parent_id=menu.menu_id)
  292. query = query.filter(SysMenu.del_flag != '2')
  293. query = query.order_by(SysMenu.order_num.asc())
  294. # children_menus = db.query(SysMenu).filter_by(parent_id=menu.menu_id).all()
  295. children_menus = query.all()
  296. # print( menu.menu_id)
  297. # children_menus = parent_id_get_menu_info(db, menu.menu_id)
  298. if len(children_menus) > 0:
  299. menu_data['children'] = build_menu_tree(children_menus, menu)
  300. elif menu.parent_id == 0:
  301. pass
  302. else:
  303. menu_data['path'] = menu_data['path'][1:]
  304. menu_tree.append(menu_data) # 将当前菜单数据添加到菜单树列表
  305. return menu_tree
  306. # 构建顶级菜单的树形结构
  307. routers = build_menu_tree(menus, None)
  308. # routers_dict = [router.dict() for router in routers]
  309. # routers_dict = []
  310. # for router in routers:
  311. # router_info = router.dict()
  312. # if len(router_info['children'])==0:
  313. # del router_info['children']
  314. # del router_info['redirect']
  315. # del router_info['alwaysShow']
  316. # router_info['path'] = router_info['path'] #[1:]
  317. #
  318. # routers_dict.append(router_info)
  319. # 返回构建好的路由数据
  320. return {
  321. "code": 200,
  322. "msg": "操作成功",
  323. "data": routers # [router.dict() for router in routers] # 如果没有顶级菜单,返回空列表
  324. }
  325. except HmacException as e:
  326. return {
  327. "code": e.code,
  328. "msg": e.msg
  329. }
  330. except Exception as e:
  331. traceback.print_exc()
  332. raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
  333. @router.get('/list')
  334. async def get_list(
  335. # request: Request,
  336. menuName: str = Query(None, max_length=100),
  337. status: str = Query(None, max_length=100),
  338. db: Session = Depends(get_db),
  339. body = Depends(remove_xss_json),
  340. user_id = Depends(valid_access_token)
  341. ):
  342. query = db.query(SysMenu)
  343. query = query.filter(SysMenu.del_flag != '2')
  344. if menuName:
  345. query = query.filter(SysMenu.menu_name.like(f'%{menuName}%'))
  346. if status:
  347. query = query.filter(SysMenu.status.like(f'%{status}%'))
  348. # 应用查询
  349. query = query.order_by(SysMenu.order_num.asc())
  350. menu_list = query.all()
  351. # 将模型实例转换为字典
  352. menu_list_dict = []
  353. def menu_parent_life(menu_id):
  354. query = db.query(SysMenu)
  355. query = query.filter(SysMenu.menu_id==menu_id)
  356. data = query.filter(SysMenu.del_flag != '2').first()
  357. if data is None:
  358. return False
  359. if data.parent_id==0 or data.parent_id=='0':
  360. return True
  361. else:
  362. return menu_parent_life(data.parent_id)
  363. for menu in menu_list:
  364. if menu_parent_life(menu.menu_id):
  365. menu_list_dict.append({
  366. "menuId": menu.menu_id,
  367. "menuName": menu.menu_name,
  368. "parentId": menu.parent_id,
  369. "orderNum": menu.order_num,
  370. "path": menu.path,
  371. "component": menu.component,
  372. "queryParam": menu.query_param,
  373. "isFrame": str(menu.is_frame),
  374. "isCache": str(menu.is_cache),
  375. "menuType": menu.menu_type,
  376. "visible": menu.visible,
  377. "status": menu.status,
  378. "perms": menu.perms,
  379. "icon": menu.icon,
  380. "createDept": menu.create_dept,
  381. "remark": menu.remark,
  382. "createTime": menu.create_time.strftime('%Y-%m-%d %H:%M:%S') if menu.create_time else '',
  383. "children": [] # 递归调用以获取子菜单
  384. })
  385. # 构建分页响应
  386. # pagination_info = {
  387. # "total": total_count,
  388. # "page_num": page_num,
  389. # "page_size": page_size,
  390. # "total_pages": (total_count + page_size - 1) // page_size # 计算总页数
  391. # }
  392. return {
  393. "code": 200,
  394. "data": menu_list_dict,
  395. # 'pages': page_num, # 总页数
  396. # 'currentPage': page_num, # 当前页数
  397. # # 'current':current,
  398. # # 'total' : total,
  399. # 'total': total_count, # 总数据量
  400. # # 'size':size,
  401. # 'pageSize': page_size, # 页码
  402. # {
  403. # "items": menu_list_dict,
  404. # "pagination": pagination_info
  405. # },
  406. "msg": "操作成功"
  407. }
  408. @router.get('/layer_list')
  409. async def get_list(
  410. # request: Request,
  411. menuName: str = Query(None, max_length=100),
  412. status: str = Query(None, max_length=100),
  413. db: Session = Depends(get_db),
  414. body = Depends(remove_xss_json),
  415. user_id = Depends(valid_access_token)
  416. ):
  417. query = db.query(SysMenuLayer)
  418. query = query.filter(SysMenuLayer.del_flag != '2')
  419. if menuName:
  420. query = query.filter(SysMenuLayer.menu_name.like(f'%{menuName}%'))
  421. if status:
  422. query = query.filter(SysMenuLayer.status.like(f'%{status}%'))
  423. # 应用查询
  424. # menu_list = db.query(SysMenu).filter(
  425. # (SysMenu.menu_name.like(f'%{menu_name}%')) ,
  426. # (SysMenu.status.like(f'%{status}%'))
  427. # ).all()
  428. menu_list = query.all()
  429. # 将模型实例转换为字典
  430. menu_list_dict = [{
  431. "menuId": menu.menu_id,
  432. "menuName": menu.menu_name,
  433. "parentId": menu.parent_id,
  434. "orderNum": menu.order_num,
  435. "path": menu.path,
  436. "component": menu.component,
  437. "queryParam": menu.query_param,
  438. "isFrame": str(menu.is_frame),
  439. "isCache": str(menu.is_cache),
  440. "menuType": menu.menu_type,
  441. "visible": menu.visible,
  442. "status": menu.status,
  443. "perms": menu.perms,
  444. "icon": menu.icon,
  445. "createDept": menu.create_dept,
  446. "remark": menu.remark,
  447. "createTime": menu.create_time.strftime('%Y-%m-%d %H:%M:%S') if menu.create_time else '',
  448. "children": [] # 递归调用以获取子菜单
  449. } for menu in menu_list]
  450. # 构建分页响应
  451. # pagination_info = {
  452. # "total": total_count,
  453. # "page_num": page_num,
  454. # "page_size": page_size,
  455. # "total_pages": (total_count + page_size - 1) // page_size # 计算总页数
  456. # }
  457. return {
  458. "code": 200,
  459. "data": menu_list_dict,
  460. # 'pages': page_num, # 总页数
  461. # 'currentPage': page_num, # 当前页数
  462. # # 'current':current,
  463. # # 'total' : total,
  464. # 'total': total_count, # 总数据量
  465. # # 'size':size,
  466. # 'pageSize': page_size, # 页码
  467. # {
  468. # "items": menu_list_dict,
  469. # "pagination": pagination_info
  470. # },
  471. "msg": "操作成功"
  472. }
  473. @router.get('/{menuid}')
  474. async def get_list(
  475. # request: Request,
  476. menuid: str = Query(None, max_length=100),
  477. db: Session = Depends(get_db),
  478. body = Depends(remove_xss_json),
  479. user_id = Depends(valid_access_token)
  480. ):
  481. query = db.query(SysMenu)
  482. query = query.filter(SysMenu.del_flag != '2')
  483. if menuid:
  484. query = query.filter(SysMenu.menu_id.like(f'{menuid}'))
  485. menu= query.first()
  486. # 将模型实例转换为字典
  487. menu_list_dict = {
  488. "menuId": menu.menu_id,
  489. "menuName": menu.menu_name,
  490. "parentId": menu.parent_id,
  491. "orderNum": menu.order_num,
  492. "path": menu.path,
  493. "component": menu.component,
  494. "queryParam": menu.query_param,
  495. "isFrame": str(menu.is_frame),
  496. "isCache": str(menu.is_cache),
  497. "menuType": menu.menu_type,
  498. "visible": menu.visible,
  499. "status": menu.status,
  500. "perms": menu.perms,
  501. "icon": menu.icon,
  502. "createDept": menu.create_dept,
  503. "remark": menu.remark,
  504. "createTime": menu.create_time.strftime('%Y-%m-%d %H:%M:%S') if menu.create_time else '',
  505. "children": [] # 递归调用以获取子菜单
  506. }
  507. return {
  508. "code": 200,
  509. "data": menu_list_dict,
  510. "msg": "操作成功"
  511. }
  512. class SysMuneCreateForm(BaseModel):
  513. component:str = None
  514. icon : str
  515. isCache: str
  516. isFrame:str
  517. menuName: str
  518. menuType:str
  519. orderNum:int
  520. parentId:int
  521. path:str
  522. perms:str=None
  523. queryParam:str=None
  524. status:str
  525. visible:str
  526. @router.post('/create')
  527. async def create(
  528. request: Request,
  529. form_data: SysMuneCreateForm,
  530. db: Session = Depends(get_db),
  531. body = Depends(remove_xss_json),
  532. auth_user: AuthUser = Depends(find_auth_user),
  533. user_id = Depends(valid_access_token)
  534. ):
  535. try:
  536. new_menu = SysMenu(
  537. menu_name = form_data.menuName,
  538. parent_id = form_data.parentId,
  539. order_num = form_data.orderNum,
  540. path = form_data.path,
  541. is_frame = int(form_data.isFrame),
  542. is_cache = int(form_data.isCache),
  543. menu_type = form_data.menuType,
  544. visible = form_data.visible,
  545. status = form_data.status,
  546. icon = form_data.icon,
  547. component= form_data.component,
  548. perms=form_data.perms,
  549. query_param=form_data.queryParam,
  550. create_by = user_id
  551. )
  552. db.add(new_menu)
  553. db.commit()
  554. db.refresh(new_menu)
  555. sys_menu_data.sign_table()
  556. db_czrz.log(db, auth_user, "系统管理", f"后台管理新建菜单【{form_data.menuName}】成功", request.client.host)
  557. return {
  558. "code": 200,
  559. "data": None,
  560. "msg": "操作成功"
  561. }
  562. except Exception as e:
  563. traceback.print_exc()
  564. db.rollback()
  565. raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
  566. class SysMuneUpdateForm(BaseModel):
  567. menuId : str
  568. component:str = None
  569. icon : str = None
  570. isCache: str = None
  571. isFrame:str = None
  572. menuName: str = None
  573. menuType:str = None
  574. orderNum:int = None
  575. parentId:int = None
  576. path:str = None
  577. perms:str=None
  578. queryParam:str=None
  579. status:str = None
  580. visible:str = None
  581. @router.put('')
  582. async def update(
  583. request: Request,
  584. # form_data: SysMuneUpdateForm,
  585. db: Session = Depends(get_db),
  586. body = Depends(remove_xss_json),
  587. auth_user: AuthUser = Depends(find_auth_user),
  588. user_id = Depends(valid_access_token)
  589. ):
  590. try:
  591. query = db.query(SysMenu)
  592. query = query.filter(SysMenu.menu_id == body['menuId'])
  593. query = query.filter(SysMenu.del_flag != '2')
  594. menu = query.first()
  595. if not menu:
  596. detail = "菜单不存在"
  597. raise HTTPException(status_code=404, detail="菜单不存在")
  598. # 更新字段,排除主键和不可更新的字段
  599. if 'component' in body:
  600. menu.component=body['component']
  601. if 'icon' in body:
  602. menu.icon=body['icon']
  603. if 'isCache' in body:
  604. menu.is_cache=body['isCache']
  605. if 'isFrame' in body:
  606. menu.is_frame=body['isFrame']
  607. if 'menuName' in body:
  608. menu.menu_name=body['menuName']
  609. if 'menuType' in body:
  610. menu.menu_type=body['menuType']
  611. if 'orderNum' in body:
  612. menu.order_num=body['orderNum']
  613. if 'parentId' in body:
  614. menu.parent_id=body['parentId']
  615. if 'path' in body:
  616. menu.path=body['path']
  617. if 'perms' in body:
  618. menu.perms=body['perms']
  619. if 'queryParam' in body:
  620. menu.query_param=body['queryParam']
  621. if 'status' in body:
  622. menu.status=body['status']
  623. if 'visible' in body:
  624. menu.visible=body['visible']
  625. if user_id:
  626. menu.update_by = user_id
  627. menu.update_time = datetime.now()
  628. menu.sign = sys_menu_data.get_sign_hmac(menu)
  629. # for field, value in menu_data.items():
  630. # if field != 'menu_id' and field in menu_to_update.__dict__:
  631. # setattr(menu_to_update, field, value)
  632. #
  633. # db.add(menu_to_update)
  634. db.commit()
  635. db_czrz.log(db, auth_user, "系统管理", f"后台管理更新菜单【{body['menuName']}】成功", request.client.host)
  636. return {
  637. "code": 200,
  638. "msg": "菜单更新成功"
  639. }
  640. except Exception as e:
  641. # db.rollback()
  642. traceback.print_exc()
  643. if str(e)=='':
  644. e = detail
  645. raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
  646. @router.delete('/{menu_id}')
  647. async def delete(
  648. request: Request,
  649. menu_id: int,
  650. db: Session = Depends(get_db),
  651. body = Depends(remove_xss_json),
  652. auth_user: AuthUser = Depends(find_auth_user),
  653. user_id = Depends(valid_access_token)
  654. ):
  655. try:
  656. query = db.query(SysMenu)
  657. query = query.filter(SysMenu.menu_id == menu_id)
  658. query = query.filter(SysMenu.del_flag != '2')
  659. menu_to_delete =query.first()
  660. if not menu_to_delete:
  661. detail = "菜单不存在"
  662. raise HTTPException(status_code=404, detail="菜单不存在")
  663. menu_to_delete.del_flag='2'
  664. menu_to_delete.update_by = user_id
  665. menu_to_delete.update_time = datetime.now()
  666. menu_to_delete.sign = sys_menu_data.get_sign_hmac(menu_to_delete)
  667. # db.delete(menu_to_delete)
  668. db.commit()
  669. db_czrz.log(db, auth_user, "系统管理", f"后台管理删除菜单【{menu_to_delete.menu_name}】成功", request.client.host)
  670. return {
  671. "code": 200,
  672. "msg": "菜单删除成功"
  673. }
  674. except Exception as e:
  675. traceback.print_exc()
  676. db.rollback()
  677. if str(e)=='':
  678. e = detail
  679. raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))