__init__.py 26 KB

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