system_service.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. package backend
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "kpt-pasture/model"
  7. "kpt-pasture/util"
  8. "net/http"
  9. "sort"
  10. "strings"
  11. "time"
  12. pasturePb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/cow"
  13. operationPb "gitee.com/xuyiping_admin/go_proto/proto/go/backend/operation"
  14. "gitee.com/xuyiping_admin/pkg/jwt"
  15. "gitee.com/xuyiping_admin/pkg/logger/zaplog"
  16. "gitee.com/xuyiping_admin/pkg/xerr"
  17. "go.uber.org/zap"
  18. "gorm.io/gorm"
  19. )
  20. const CurrentUserName = "userName"
  21. // Login 用户登录
  22. func (s *StoreEntry) Login(ctx context.Context, req *pasturePb.SearchUserRequest) (*pasturePb.SystemUserResponse, error) {
  23. systemUser := &model.SystemUser{}
  24. if err := s.DB.Where("name = ?", req.Name).Find(systemUser).Error; err != nil {
  25. return nil, xerr.WithStack(err)
  26. }
  27. if systemUser.Password != req.Password {
  28. return nil, xerr.Customf("密码错误,来自用户:%s", req.Name)
  29. }
  30. if systemUser.IsShow == pasturePb.IsShow_No {
  31. return nil, xerr.Customf("该账号已被禁用,请联系管理员")
  32. }
  33. jwtToken := jwt.NewJWTTokenGen(s.Cfg.AppName, s.Cfg.JwtTokenKeyConfig.PrivateKey)
  34. token, err := jwtToken.GenerateToken(systemUser.Name, s.Cfg.JwtExpireTime)
  35. if err != nil {
  36. return nil, xerr.WithStack(err)
  37. }
  38. if token == "" {
  39. return nil, xerr.Custom("获取token错误")
  40. }
  41. expires := time.Now().Add(time.Duration(s.Cfg.JwtExpireTime) * time.Second).Format(util.LayoutTime)
  42. return &pasturePb.SystemUserResponse{
  43. Code: http.StatusOK,
  44. Message: "ok",
  45. Data: &pasturePb.SystemUserData{
  46. AccessToken: token,
  47. Expires: expires,
  48. RefreshToken: expires,
  49. Username: systemUser.Name,
  50. Roles: []string{"admin"},
  51. Avatar: systemUser.Avatar,
  52. },
  53. }, nil
  54. }
  55. // SearchSystemUserList 查询系统用户
  56. func (s *StoreEntry) SearchSystemUserList(ctx context.Context, req *pasturePb.SearchUserRequest) (*pasturePb.SearchUserResponse, error) {
  57. systemUserList := make([]*model.SystemUser, 0)
  58. var count int64 = 0
  59. pref := s.DB.Model(new(model.SystemUser)).Where("is_delete = ?", operationPb.IsShow_OK)
  60. if req.Name != "" {
  61. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  62. }
  63. if req.Mobile != "" {
  64. pref.Where("mobile = ?", req.Mobile)
  65. }
  66. if req.DeptId > 0 {
  67. pref.Where("dept_id = ?", req.DeptId)
  68. }
  69. if req.IsShow > 0 {
  70. pref.Where("is_show = ?", req.IsShow)
  71. }
  72. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  73. Find(&systemUserList).Debug().Error; err != nil {
  74. return nil, xerr.WithStack(err)
  75. }
  76. roleList, err := s.SearchSystemRoleListByIds(ctx, []int64{})
  77. if err != nil {
  78. return nil, xerr.WithStack(err)
  79. }
  80. deptList, err := s.SearchSystemDeptListByIds(ctx, []int64{})
  81. if err != nil {
  82. return nil, xerr.WithStack(err)
  83. }
  84. return &pasturePb.SearchUserResponse{
  85. Code: http.StatusOK,
  86. Message: "ok",
  87. Data: &pasturePb.SearchUserData{
  88. List: model.SystemUserSlice(systemUserList).ToPB(deptList, roleList),
  89. Total: int32(count),
  90. PageSize: req.Pagination.PageSize,
  91. Page: req.Pagination.Page,
  92. },
  93. }, nil
  94. }
  95. // DeleteSystemUser 删除系统用户
  96. func (s *StoreEntry) DeleteSystemUser(ctx context.Context, userId int64) error {
  97. systemUser := &model.SystemUser{
  98. Id: userId,
  99. }
  100. if err := s.DB.First(systemUser).Error; err != nil {
  101. if errors.Is(err, gorm.ErrRecordNotFound) {
  102. return xerr.Custom("该用户不存在")
  103. }
  104. return xerr.WithStack(err)
  105. }
  106. if err := s.DB.Model(systemUser).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  107. return xerr.WithStack(err)
  108. }
  109. return nil
  110. }
  111. // IsShowSystemUser 用户是否启用
  112. func (s *StoreEntry) IsShowSystemUser(ctx context.Context, userId int64) error {
  113. systemUser := &model.SystemUser{
  114. Id: userId,
  115. }
  116. if err := s.DB.First(systemUser).Error; err != nil {
  117. if errors.Is(err, gorm.ErrRecordNotFound) {
  118. return xerr.Custom("该用户不存在")
  119. }
  120. return xerr.WithStack(err)
  121. }
  122. isShow := pasturePb.IsShow_No
  123. if systemUser.IsShow == pasturePb.IsShow_No {
  124. isShow = pasturePb.IsShow_Ok
  125. }
  126. if err := s.DB.Model(systemUser).Update("is_show", isShow).Error; err != nil {
  127. return xerr.WithStack(err)
  128. }
  129. return nil
  130. }
  131. // GetCurrentUserName 获取当前用户名
  132. func (s *StoreEntry) GetCurrentUserName(ctx context.Context) (string, error) {
  133. userNameInter := ctx.Value(CurrentUserName)
  134. if userNameInter == nil {
  135. return "", xerr.Customf("cannot userName")
  136. }
  137. if userName, ok := userNameInter.(string); ok {
  138. return userName, nil
  139. } else {
  140. return "", xerr.Customf("waring userName")
  141. }
  142. }
  143. // GetUserInfo 获取用户信息
  144. func (s *StoreEntry) GetUserInfo(ctx context.Context, token string) (*operationPb.UserAuth, error) {
  145. systemUser := &model.SystemUser{}
  146. userName, err := s.GetCurrentUserName(ctx)
  147. if err != nil {
  148. return nil, xerr.WithStack(err)
  149. }
  150. if err = s.DB.Where("name = ?", userName).First(systemUser).Error; err != nil {
  151. return nil, xerr.WithStack(err)
  152. }
  153. systemRole := make([]*model.SystemRole, 0)
  154. return systemUser.SystemUserFormat(systemRole, nil), nil
  155. }
  156. // SystemUserCreateOrUpdate 创建或者更新系统用户
  157. func (s *StoreEntry) SystemUserCreateOrUpdate(ctx context.Context, req *pasturePb.SearchUserRequest) error {
  158. if req.Id > 0 {
  159. systemUser := &model.SystemUser{}
  160. if err := s.DB.First(systemUser).Error; err != nil {
  161. return xerr.WithStack(err)
  162. }
  163. req.Password = systemUser.Password
  164. }
  165. if err := s.DB.Model(&model.SystemUser{}).Where(map[string]interface{}{
  166. "id": req.Id,
  167. }).Assign(map[string]interface{}{
  168. "name": req.Name,
  169. "nick_name": req.NickName,
  170. "mobile": req.Mobile,
  171. "gender": req.Gender,
  172. "password": req.Password,
  173. "dept_id": req.DeptId,
  174. "remarks": req.Remarks,
  175. "is_delete": operationPb.IsShow_OK,
  176. "is_show": req.IsShow,
  177. }).FirstOrCreate(&model.SystemUser{}).Error; err != nil {
  178. return xerr.WithStack(err)
  179. }
  180. return nil
  181. }
  182. // ResetPasswordSystemUser 重置系统用户密码
  183. func (s *StoreEntry) ResetPasswordSystemUser(ctx context.Context, req *pasturePb.ResetUserPasswordRequest) error {
  184. systemUser := &model.SystemUser{
  185. Id: int64(req.Id),
  186. }
  187. if err := s.DB.First(systemUser).Error; err != nil {
  188. if errors.Is(err, gorm.ErrRecordNotFound) {
  189. return xerr.Custom("该用户不存在")
  190. }
  191. return xerr.WithStack(err)
  192. }
  193. if err := s.DB.Model(systemUser).Update("password", req.Password).Error; err != nil {
  194. return xerr.WithStack(err)
  195. }
  196. return nil
  197. }
  198. // DetailsSystemUser 系统用户详情
  199. func (s *StoreEntry) DetailsSystemUser(ctx context.Context, userId int64) (*operationPb.UserDetails, error) {
  200. systemUser := &model.SystemUser{
  201. Id: userId,
  202. }
  203. if err := s.DB.First(systemUser).Error; err != nil {
  204. if errors.Is(err, gorm.ErrRecordNotFound) {
  205. return nil, xerr.Custom("该用户不存在")
  206. }
  207. return nil, xerr.WithStack(err)
  208. }
  209. return &operationPb.UserDetails{
  210. Code: http.StatusOK,
  211. Msg: "ok",
  212. Data: systemUser.ToPb(),
  213. }, nil
  214. }
  215. // GetSystemUserPermissions 返回系统用户相关菜单权限
  216. func (s *StoreEntry) GetSystemUserPermissions(ctx context.Context, token string) (*operationPb.SystemUserMenuPermissions, error) {
  217. // 解析token
  218. userName, err := s.GetCurrentUserName(ctx)
  219. if err != nil {
  220. return nil, xerr.WithStack(err)
  221. }
  222. // 根据用户token获取用户数据
  223. systemUser := &model.SystemUser{Name: userName}
  224. if err = s.DB.Where("name = ?", userName).First(systemUser).Error; err != nil {
  225. if errors.Is(err, gorm.ErrRecordNotFound) {
  226. return nil, xerr.Custom("该用户数据不存在")
  227. }
  228. return nil, xerr.WithStack(err)
  229. }
  230. /*roleIds := systemUser.SystemUserRoleToSlice()*/
  231. roleIds := []int64{1}
  232. // 获取用户角色数据
  233. systemRoles := make([]*model.SystemRole, 0)
  234. if err = s.DB.Where("is_show = ?", operationPb.IsShow_OK).Find(&systemRoles, roleIds).Error; err != nil {
  235. return nil, xerr.WithStack(err)
  236. }
  237. systemAllPermissionsList := &SystemAllPermissionsList{
  238. MenuList: make([]*model.SystemMenuPermissions, 0),
  239. }
  240. for _, role := range systemRoles {
  241. item := s.GetSystemAllPermissionsList(ctx, role.Id)
  242. systemAllPermissionsList.MenuList = append(systemAllPermissionsList.MenuList, item.MenuList...)
  243. }
  244. systemAllPermissionsList.SystemUserMenuPermissionsUnDuplicate()
  245. menuList, err := s.GetMenuList(ctx, systemAllPermissionsList.MenuList)
  246. if err != nil {
  247. return nil, xerr.WithStack(err)
  248. }
  249. return s.SystemPermissionsFormatPb(menuList), nil
  250. }
  251. func (s *StoreEntry) SystemPermissionsFormatPb(menuList []*model.SystemMenu) *operationPb.SystemUserMenuPermissions {
  252. systemUserMenuPermissions := &operationPb.SystemUserMenuPermissions{
  253. Code: http.StatusOK,
  254. Msg: "ok",
  255. Data: &operationPb.SystemUserMenuData{
  256. PastureList: make([]*operationPb.AddPastureRequest, 0),
  257. MenuList: make([]*operationPb.AddMenuRequest, 0),
  258. MobileList: make([]*operationPb.AddMobileRequest, 0),
  259. MenuButtonsPath: make([]*operationPb.MenuButtonsPath, 0),
  260. },
  261. }
  262. // TODO 后面优化成递归算法
  263. level := make(map[int32][]*operationPb.AddMenuRequest, 0)
  264. for _, menu := range menuList {
  265. if _, ok := level[menu.Level]; !ok {
  266. level[menu.Level] = make([]*operationPb.AddMenuRequest, 0)
  267. }
  268. level[menu.Level] = append(level[menu.Level], &operationPb.AddMenuRequest{
  269. Id: int32(menu.Id),
  270. Name: menu.Name,
  271. ParentId: int32(menu.ParentId),
  272. MenuType: menu.MenuType,
  273. Title: menu.Title,
  274. Path: menu.Path,
  275. IsShow: menu.IsShow,
  276. Component: menu.Component,
  277. Icon: menu.Icon,
  278. Sort: menu.Sort,
  279. Redirect: menu.Redirect,
  280. CreatedAt: int32(menu.CreatedAt),
  281. CreatedAtFormat: time.Unix(menu.CreatedAt, 0).Format(model.LayoutTime),
  282. Level: menu.Level,
  283. Affix: true,
  284. KeepAlive: true,
  285. Children: make([]*operationPb.AddMenuRequest, 0),
  286. })
  287. if menu.Level == model.Level3 {
  288. systemUserMenuPermissions.Data.MenuButtonsPath = append(systemUserMenuPermissions.Data.MenuButtonsPath, &operationPb.MenuButtonsPath{
  289. Path: menu.Path,
  290. MenuId: int32(menu.Id),
  291. })
  292. }
  293. }
  294. level2IsShow := make([]int32, 0)
  295. for _, leve2Data := range level[model.Level2] {
  296. for _, leve3Data := range level[model.Level3] {
  297. if leve3Data.ParentId == leve2Data.Id && strings.Contains(leve3Data.Path, ":page") {
  298. level2IsShow = append(level2IsShow, leve2Data.Id)
  299. }
  300. if leve3Data.ParentId == leve2Data.Id {
  301. if leve2Data.Children == nil {
  302. leve2Data.Children = make([]*operationPb.AddMenuRequest, 0)
  303. }
  304. leve2Data.Children = append(leve2Data.Children, leve3Data)
  305. }
  306. }
  307. }
  308. sort.SliceStable(level[model.Level2], func(i, j int) bool {
  309. return level[model.Level2][i].Sort > level[model.Level2][j].Sort
  310. })
  311. for _, leve2Data := range level[model.Level2] {
  312. var info bool
  313. for _, v := range level2IsShow {
  314. if v == leve2Data.Id {
  315. info = true
  316. }
  317. }
  318. if !info {
  319. continue
  320. }
  321. for _, leve1Data := range level[model.Level1] {
  322. if leve2Data.ParentId == leve1Data.Id {
  323. if leve1Data.Children == nil {
  324. leve1Data.Children = make([]*operationPb.AddMenuRequest, 0)
  325. }
  326. leve1Data.Children = append(leve1Data.Children, leve2Data)
  327. }
  328. }
  329. }
  330. sort.SliceStable(level[model.Level1], func(i, j int) bool {
  331. return level[model.Level1][i].Sort > level[model.Level1][j].Sort
  332. })
  333. systemUserMenuPermissions.Data.MenuList = level[model.Level1]
  334. return systemUserMenuPermissions
  335. }
  336. // CreateSystemRole 添加角色
  337. func (s *StoreEntry) CreateSystemRole(ctx context.Context, req *operationPb.AddRoleRequest) error {
  338. if err := s.DB.Transaction(func(tx *gorm.DB) error {
  339. // 创建角色数据
  340. role := model.NewSystemRole(req)
  341. if err := tx.Create(role).Error; err != nil {
  342. return xerr.WithStack(err)
  343. }
  344. // 创建角色菜单权限数据
  345. if len(req.MenuId) > 0 {
  346. menuPermissions := model.NewSystemMenuPermissions(role.Id, req.MenuId)
  347. if err := tx.Create(menuPermissions).Error; err != nil {
  348. return xerr.WithStack(err)
  349. }
  350. }
  351. return nil
  352. }); err != nil {
  353. return xerr.WithStack(err)
  354. }
  355. return nil
  356. }
  357. // EditSystemRole 编辑角色
  358. func (s *StoreEntry) EditSystemRole(ctx context.Context, req *operationPb.AddRoleRequest) error {
  359. role := &model.SystemRole{Id: int64(req.Id)}
  360. if err := s.DB.First(role).Error; err != nil {
  361. if errors.Is(err, gorm.ErrRecordNotFound) {
  362. return xerr.Custom("该数据不存在")
  363. }
  364. return xerr.WithStack(err)
  365. }
  366. if err := s.DB.Transaction(func(tx *gorm.DB) error {
  367. updateSystemRole := model.NewSystemRole(req)
  368. if err := tx.Omit("is_show").
  369. Where("id = ?", role.Id).
  370. Updates(updateSystemRole).Error; err != nil {
  371. return xerr.WithStack(err)
  372. }
  373. // 更新菜单权限关系表
  374. menuIds := req.MenuId
  375. if err := tx.Model(new(model.SystemMenuPermissions)).
  376. Where("role_id = ?", req.Id).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  377. return xerr.WithStack(err)
  378. }
  379. newSystemMenuPermissions := model.NewSystemMenuPermissions(int64(req.Id), menuIds)
  380. if err := tx.Create(newSystemMenuPermissions).Error; err != nil {
  381. return xerr.WithStack(err)
  382. }
  383. return nil
  384. }); err != nil {
  385. return xerr.WithStack(err)
  386. }
  387. return nil
  388. }
  389. // DeleteSystemRole 删除系统角色
  390. func (s *StoreEntry) DeleteSystemRole(ctx context.Context, roleId int64) error {
  391. systemRole := &model.SystemRole{
  392. Id: roleId,
  393. }
  394. if err := s.DB.First(systemRole).Error; err != nil {
  395. if errors.Is(err, gorm.ErrRecordNotFound) {
  396. return xerr.Custom("该数据不存在")
  397. }
  398. return xerr.WithStack(err)
  399. }
  400. if err := s.DB.Model(systemRole).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  401. return xerr.WithStack(err)
  402. }
  403. return nil
  404. }
  405. // SearchSystemRoleList 查询系统角色
  406. func (s *StoreEntry) SearchSystemRoleList(ctx context.Context, req *operationPb.SearchRoleRequest) (*operationPb.SearchRoleResponse, error) {
  407. systemRoleList := make([]*model.SystemRole, 0)
  408. var count int64 = 0
  409. pref := s.DB.Model(new(model.SystemRole)).Where("is_show = ?", operationPb.IsShow_OK)
  410. if req.Name != "" {
  411. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  412. }
  413. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).
  414. Offset(int(req.Pagination.PageOffset)).Find(&systemRoleList).Error; err != nil {
  415. return nil, xerr.WithStack(err)
  416. }
  417. permissionsMenuMap := make(map[int64][]*model.SystemMenu, 0)
  418. for _, role := range systemRoleList {
  419. systemMenuList := make([]*model.SystemMenu, 0)
  420. if err := s.DB.Table(new(model.SystemMenu).TableName()).Select(fmt.Sprintf("%s.*", new(model.SystemMenu).TableName())).
  421. Joins(fmt.Sprintf("left join %s on %s = %s and %s", new(model.SystemMenuPermissions).TableName(), fmt.Sprintf("%s.menu_id", new(model.SystemMenuPermissions).TableName()),
  422. fmt.Sprintf("%s.id", new(model.SystemMenu).TableName()), fmt.Sprintf("%s.is_show = %d", new(model.SystemMenuPermissions).TableName(), operationPb.IsShow_OK))).
  423. Where(fmt.Sprintf("%s.role_id = ?", new(model.SystemMenuPermissions).TableName()), role.Id).Where(fmt.Sprintf("%s.level = ?", new(model.SystemMenu).TableName()), model.Level2).
  424. Find(&systemMenuList).Error; err != nil {
  425. zaplog.Error("SearchSystemRoleList", zap.Any("SystemMenuPermissions", err))
  426. }
  427. permissionsMenuMap[role.Id] = systemMenuList
  428. }
  429. return &operationPb.SearchRoleResponse{
  430. Code: http.StatusOK,
  431. Msg: "ok",
  432. Data: &operationPb.SearchRoleData{
  433. Page: req.Pagination.Page,
  434. Total: int32(count),
  435. PageSize: req.Pagination.PageSize,
  436. List: model.SystemRoleSlice(systemRoleList).ToPB(permissionsMenuMap),
  437. },
  438. }, nil
  439. }
  440. // SearchSystemRoleListByIds 根据id查询角色列表
  441. func (s *StoreEntry) SearchSystemRoleListByIds(ctx context.Context, ids []int64) ([]*model.SystemRole, error) {
  442. systemRoleList := make([]*model.SystemRole, 0)
  443. if err := s.DB.Model(new(model.SystemRole)).
  444. Where("is_show = ?", operationPb.IsShow_OK).
  445. Find(&systemRoleList, ids).Error; err != nil {
  446. return nil, xerr.WithStack(err)
  447. }
  448. return systemRoleList, nil
  449. }
  450. // GetRolePermissions 查询系统角色权限
  451. func (s *StoreEntry) GetRolePermissions(ctx context.Context, roleId int64) (*operationPb.RolePermissionsList, error) {
  452. systemRole := &model.SystemRole{
  453. Id: roleId,
  454. }
  455. if err := s.DB.First(systemRole).Error; err != nil {
  456. if errors.Is(err, gorm.ErrRecordNotFound) {
  457. return nil, xerr.Custom("该数据不存在")
  458. }
  459. return nil, xerr.WithStack(err)
  460. }
  461. systemAllPermissionsList := &SystemAllPermissionsList{
  462. MenuList: make([]*model.SystemMenuPermissions, 0),
  463. }
  464. item := s.GetSystemAllPermissionsList(ctx, systemRole.Id)
  465. systemAllPermissionsList.MenuList = append(systemAllPermissionsList.MenuList, item.MenuList...)
  466. return s.AllPermissionsListToRolePermissions(systemAllPermissionsList), nil
  467. }
  468. // CreateSystemMenu 添加系统菜单权限
  469. func (s *StoreEntry) CreateSystemMenu(ctx context.Context, req *operationPb.AddMenuRequest) error {
  470. systemMenu := model.NewSystemMenu(req)
  471. if err := s.DB.Create(systemMenu).Error; err != nil {
  472. return xerr.WithStack(err)
  473. }
  474. return nil
  475. }
  476. // EditSystemMenu 编辑系统菜单权限
  477. func (s *StoreEntry) EditSystemMenu(ctx context.Context, req *operationPb.AddMenuRequest) error {
  478. systemMenu := &model.SystemMenu{Id: int64(req.Id)}
  479. if err := s.DB.First(systemMenu).Error; err != nil {
  480. if errors.Is(err, gorm.ErrRecordNotFound) {
  481. return xerr.Custom("该数据不存在!")
  482. }
  483. return xerr.WithStack(err)
  484. }
  485. updateData := &model.SystemMenu{
  486. Name: req.Name,
  487. MenuType: req.MenuType,
  488. Title: req.Title,
  489. Path: req.Path,
  490. Component: req.Component,
  491. Icon: req.Icon,
  492. Sort: req.Sort,
  493. Redirect: req.Redirect,
  494. ParentId: int64(req.ParentId),
  495. }
  496. if err := s.DB.Model(new(model.SystemMenu)).Omit("is_show").
  497. Where("id = ?", systemMenu.Id).
  498. Updates(updateData).Error; err != nil {
  499. return xerr.WithStack(err)
  500. }
  501. return nil
  502. }
  503. // IsShowSystemMenu 菜单是否启用
  504. func (s *StoreEntry) IsShowSystemMenu(ctx context.Context, req *operationPb.IsShowSystemMenuRequest) error {
  505. systemMenu := &model.SystemMenu{Id: int64(req.MenuId)}
  506. if err := s.DB.First(systemMenu).Error; err != nil {
  507. if errors.Is(err, gorm.ErrRecordNotFound) {
  508. return xerr.Custom("该数据不存在")
  509. }
  510. return xerr.WithStack(err)
  511. }
  512. if err := s.DB.Model(systemMenu).Update("is_show", req.IsShow).Error; err != nil {
  513. return xerr.WithStack(err)
  514. }
  515. return nil
  516. }
  517. // SearchSystemMenuList 菜单列表查询
  518. func (s *StoreEntry) SearchSystemMenuList(ctx context.Context, req *operationPb.SearchMenuRequest) (*operationPb.SearchMenuResponse, error) {
  519. systemMenuLevel1 := make([]*model.SystemMenu, 0)
  520. var count int64 = 0
  521. pref := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level1)
  522. if req.Name != "" {
  523. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  524. }
  525. if err := pref.Order("sort desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  526. Find(&systemMenuLevel1).Debug().Error; err != nil {
  527. return nil, xerr.WithStack(err)
  528. }
  529. systemMenuLevel1 = append(systemMenuLevel1, s.searchMenuLevel23ByLevel1(ctx, systemMenuLevel1)...)
  530. return &operationPb.SearchMenuResponse{
  531. Code: http.StatusOK,
  532. Msg: "ok",
  533. Data: &operationPb.SearchMenuData{
  534. Page: req.Pagination.Page,
  535. Total: int32(count),
  536. List: model.SystemMenuSlice(systemMenuLevel1).ToPB(),
  537. },
  538. }, nil
  539. }
  540. // searchMenuLevel23ByLevel1 根据一级菜单返回对应二三级菜单
  541. func (s *StoreEntry) searchMenuLevel23ByLevel1(ctx context.Context, res []*model.SystemMenu) []*model.SystemMenu {
  542. systemMenuLevel23 := make([]*model.SystemMenu, 0)
  543. if len(res) <= 0 {
  544. return systemMenuLevel23
  545. }
  546. ids1 := make([]int64, 0)
  547. for _, v := range res {
  548. ids1 = append(ids1, v.Id)
  549. }
  550. if err := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level2).
  551. Where("parent_id IN ?", ids1).Order("sort desc").
  552. Find(&systemMenuLevel23).Error; err != nil {
  553. return systemMenuLevel23
  554. }
  555. ids2 := make([]int64, 0)
  556. for _, v := range systemMenuLevel23 {
  557. ids2 = append(ids2, v.Id)
  558. }
  559. systemMenuLevel3 := make([]*model.SystemMenu, 0)
  560. if err := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level3).
  561. Where("parent_id IN ?", ids2).Order("sort desc").
  562. Find(&systemMenuLevel3).Error; err != nil {
  563. return systemMenuLevel23
  564. }
  565. if len(systemMenuLevel3) > 0 {
  566. systemMenuLevel23 = append(systemMenuLevel23, systemMenuLevel3...)
  567. }
  568. return systemMenuLevel23
  569. }
  570. // DeleteSystemMenu 删除系统菜单
  571. func (s *StoreEntry) DeleteSystemMenu(ctx context.Context, menuId int64) error {
  572. systemMenu := &model.SystemMenu{Id: menuId}
  573. if err := s.DB.First(systemMenu).Error; err != nil {
  574. if errors.Is(err, gorm.ErrRecordNotFound) {
  575. return xerr.Custom("该数据不存在")
  576. }
  577. return xerr.WithStack(err)
  578. }
  579. if err := s.DB.Model(systemMenu).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  580. return xerr.WithStack(err)
  581. }
  582. return nil
  583. }
  584. func (s *StoreEntry) SearchSystemDeptList(ctx context.Context, req *pasturePb.SearchDeptRequest) (*pasturePb.SearchDeptResponse, error) {
  585. deptList := make([]*model.SystemDept, 0)
  586. var count int64 = 0
  587. pref := s.DB.Model(new(model.SystemDept)).Where("is_delete = ?", operationPb.IsShow_OK)
  588. if req.Name != "" {
  589. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  590. }
  591. if req.IsShow > 0 {
  592. pref.Where("is_show = ?", req.IsShow)
  593. }
  594. if err := pref.Order("sort desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  595. Find(&deptList).Error; err != nil {
  596. return nil, xerr.WithStack(err)
  597. }
  598. return &pasturePb.SearchDeptResponse{
  599. Code: http.StatusOK,
  600. Message: "ok",
  601. Data: model.SystemDeptSlice(deptList).ToPB(),
  602. }, nil
  603. }
  604. func (s *StoreEntry) SystemDepDelete(ctx context.Context, id int64) error {
  605. dept := &model.SystemDept{Id: id}
  606. if err := s.DB.First(dept).Error; err != nil {
  607. return xerr.WithStack(err)
  608. }
  609. if dept.IsShow == pasturePb.IsShow_No {
  610. return nil
  611. }
  612. if err := s.DB.Model(dept).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  613. return xerr.WithStack(err)
  614. }
  615. return nil
  616. }
  617. func (s *StoreEntry) SystemDeptCreateOrUpdate(ctx context.Context, req *pasturePb.SearchDeptRequest) error {
  618. if err := s.DB.Model(&model.SystemDept{}).Where(map[string]interface{}{
  619. "id": req.Id,
  620. }).Assign(map[string]interface{}{
  621. "name": req.Name,
  622. "sort": req.Sort,
  623. "parent_id": req.ParentId,
  624. "remarks": req.Remarks,
  625. "is_delete": operationPb.IsShow_OK,
  626. "is_show": req.IsShow,
  627. "dept_type": pasturePb.Depth_Department,
  628. "leader_id": req.LeaderId,
  629. }).FirstOrCreate(&model.SystemDept{}).Error; err != nil {
  630. return xerr.WithStack(err)
  631. }
  632. return nil
  633. }
  634. // SearchSystemDeptListByIds 根据id查询部门列表
  635. func (s *StoreEntry) SearchSystemDeptListByIds(ctx context.Context, ids []int64) ([]*model.SystemDept, error) {
  636. systemDeptList := make([]*model.SystemDept, 0)
  637. if err := s.DB.Model(new(model.SystemDept)).
  638. Where("is_show = ?", operationPb.IsShow_OK).
  639. Find(&systemDeptList, ids).Error; err != nil {
  640. return nil, xerr.WithStack(err)
  641. }
  642. return systemDeptList, nil
  643. }