system_service.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. package backend
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "kpt-tmr-group/model"
  7. "kpt-tmr-group/pkg/jwt"
  8. "kpt-tmr-group/pkg/logger/zaplog"
  9. "kpt-tmr-group/pkg/tool"
  10. "kpt-tmr-group/pkg/xerr"
  11. operationPb "kpt-tmr-group/proto/go/backend/operation"
  12. "net/http"
  13. "strconv"
  14. "strings"
  15. "go.uber.org/zap"
  16. "gorm.io/gorm"
  17. )
  18. // Auth 用户登录
  19. func (s *StoreEntry) Auth(ctx context.Context, auth *operationPb.UserAuthData) (*operationPb.SystemToken, error) {
  20. systemUser := &model.SystemUser{}
  21. if err := s.DB.Where("name = ?", auth.UserName).Find(systemUser).Error; err != nil {
  22. return nil, xerr.WithStack(err)
  23. }
  24. if systemUser.Password != auth.Password {
  25. return nil, xerr.Customf("密码错误,来自用户:%s", auth.UserName)
  26. }
  27. if systemUser.IsShow == operationPb.IsShow_NO {
  28. return nil, xerr.Customf("该账号已被禁用,请联系管理员")
  29. }
  30. token, err := jwt.GenerateToken(systemUser.Name, systemUser.Password)
  31. if err != nil {
  32. return nil, xerr.WithStack(err)
  33. }
  34. if token == "" {
  35. return nil, xerr.Custom("获取token错误")
  36. }
  37. return &operationPb.SystemToken{
  38. Code: http.StatusOK,
  39. Msg: "ok",
  40. Data: &operationPb.TokenData{Token: token},
  41. }, nil
  42. }
  43. // GetUserInfo 获取用户信息
  44. func (s *StoreEntry) GetUserInfo(ctx context.Context, token string) (*operationPb.UserAuth, error) {
  45. systemUser := &model.SystemUser{}
  46. claims, err := jwt.ParseToken(token)
  47. if err != nil {
  48. return nil, xerr.WithStack(err)
  49. }
  50. if claims.Username == "" {
  51. return nil, xerr.Custom("token解析失败")
  52. }
  53. if err = s.DB.Where("name = ?", claims.Username).First(systemUser).Error; err != nil {
  54. return nil, xerr.WithStack(err)
  55. }
  56. systemRole := make([]*model.SystemRole, 0)
  57. pastureList := make([]*operationPb.UserPasture, 0)
  58. roleIdStr := strings.Split(systemUser.RoleIds, ",")
  59. if len(roleIdStr) > 0 {
  60. roleIds := make([]int, 0)
  61. for _, v := range roleIdStr {
  62. roleId, _ := strconv.Atoi(v)
  63. roleIds = append(roleIds, roleId)
  64. }
  65. if err = s.DB.Model(new(model.SystemGroupPasturePermissions)).Select("DISTINCT(group_pasture.id) AS did, group_pasture.id as id,group_pasture.name as name").
  66. Where("system_group_pasture_permissions.role_id IN ?", roleIds).Where("system_group_pasture_permissions.is_show = ?", operationPb.IsShow_OK).
  67. Joins("right join group_pasture on system_group_pasture_permissions.pasture_id = group_pasture.id").Find(&pastureList).Debug().Error; err != nil {
  68. }
  69. if err = s.DB.Find(&systemRole, roleIds).Error; err != nil {
  70. return nil, xerr.WithStack(err)
  71. }
  72. }
  73. return systemUser.SystemUserFormat(systemRole, pastureList), nil
  74. }
  75. // CreateSystemUser 创建系统用户
  76. func (s *StoreEntry) CreateSystemUser(ctx context.Context, req *operationPb.AddSystemUser) error {
  77. systemUsers := &model.SystemUser{
  78. Name: req.Name,
  79. EmployeeName: req.EmployeeName,
  80. Phone: req.Phone,
  81. Password: tool.Md5String(model.InitManagerPassword),
  82. CreateUser: req.CreateUser,
  83. IsShow: operationPb.IsShow_OK,
  84. IsDelete: operationPb.IsShow_OK,
  85. }
  86. systemUsers.SystemUserRoleFormat(req)
  87. if err := s.DB.Create(systemUsers).Error; err != nil {
  88. return xerr.WithStack(err)
  89. }
  90. return nil
  91. }
  92. // SearchSystemUserList 查询系统用户
  93. func (s *StoreEntry) SearchSystemUserList(ctx context.Context, req *operationPb.SearchUserRequest) (*operationPb.SearchUserResponse, error) {
  94. systemUserList := make([]*model.SystemUser, 0)
  95. var count int64 = 0
  96. pref := s.DB.Model(new(model.SystemUser)).Where("is_delete = ?", operationPb.IsShow_OK)
  97. if req.Name != "" {
  98. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  99. }
  100. if req.EmployeeName != "" {
  101. pref.Where("employee_name like ?", fmt.Sprintf("%s%s%s", "%", req.EmployeeName, "%"))
  102. }
  103. if req.IsShow > 0 {
  104. pref.Where("is_show = ?", req.IsShow)
  105. }
  106. if req.CreatedStartTime > 0 && req.CreatedEndTime > 0 && req.CreatedStartTime <= req.CreatedEndTime {
  107. pref.Where("created_at BETWEEN ? AND ?", req.CreatedStartTime, req.CreatedEndTime)
  108. }
  109. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  110. Find(&systemUserList).Debug().Error; err != nil {
  111. return nil, xerr.WithStack(err)
  112. }
  113. roleList, err := s.SearchSystemRoleListByIds(ctx, []int64{})
  114. if err != nil {
  115. return nil, xerr.WithStack(err)
  116. }
  117. return &operationPb.SearchUserResponse{
  118. Code: http.StatusOK,
  119. Msg: "ok",
  120. Data: &operationPb.SearchUserData{
  121. Page: req.Pagination.Page,
  122. Total: int32(count),
  123. PageSize: req.Pagination.PageSize,
  124. List: model.SystemUserSlice(systemUserList).ToPB(roleList),
  125. },
  126. }, nil
  127. }
  128. // EditSystemUser 编辑用户
  129. func (s *StoreEntry) EditSystemUser(ctx context.Context, req *operationPb.AddSystemUser) error {
  130. systemUser := &model.SystemUser{Id: int64(req.Id)}
  131. if err := s.DB.First(systemUser).Error; err != nil {
  132. if errors.Is(err, gorm.ErrRecordNotFound) {
  133. return xerr.Custom("该数据不存在!")
  134. }
  135. return xerr.WithStack(err)
  136. }
  137. updateData := &model.SystemUser{
  138. Name: req.Name,
  139. EmployeeName: req.EmployeeName,
  140. Phone: req.Phone,
  141. }
  142. updateData.SystemUserRoleFormat(req)
  143. if err := s.DB.Model(new(model.SystemUser)).Omit("is_show", "password", "is_delete", "create_user").
  144. Where("id = ?", systemUser.Id).
  145. Updates(updateData).Error; err != nil {
  146. return xerr.WithStack(err)
  147. }
  148. return nil
  149. }
  150. // DeleteSystemUser 删除系统用户
  151. func (s *StoreEntry) DeleteSystemUser(ctx context.Context, userId int64) error {
  152. systemUser := &model.SystemUser{
  153. Id: userId,
  154. }
  155. if err := s.DB.First(systemUser).Error; err != nil {
  156. if errors.Is(err, gorm.ErrRecordNotFound) {
  157. return xerr.Custom("该用户不存在")
  158. }
  159. return xerr.WithStack(err)
  160. }
  161. if err := s.DB.Model(systemUser).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  162. return xerr.WithStack(err)
  163. }
  164. return nil
  165. }
  166. // ResetPasswordSystemUser 重置系统用户密码
  167. func (s *StoreEntry) ResetPasswordSystemUser(ctx context.Context, userId int64) error {
  168. systemUser := &model.SystemUser{
  169. Id: userId,
  170. }
  171. if err := s.DB.First(systemUser).Error; err != nil {
  172. if errors.Is(err, gorm.ErrRecordNotFound) {
  173. return xerr.Custom("该用户不存在")
  174. }
  175. return xerr.WithStack(err)
  176. }
  177. if err := s.DB.Model(systemUser).Update("password", tool.Md5String(model.InitManagerPassword)).Error; err != nil {
  178. return xerr.WithStack(err)
  179. }
  180. return nil
  181. }
  182. // DetailsSystemUser 系统用户详情
  183. func (s *StoreEntry) DetailsSystemUser(ctx context.Context, userId int64) (*operationPb.UserDetails, error) {
  184. systemUser := &model.SystemUser{
  185. Id: userId,
  186. }
  187. if err := s.DB.First(systemUser).Error; err != nil {
  188. if errors.Is(err, gorm.ErrRecordNotFound) {
  189. return nil, xerr.Custom("该用户不存在")
  190. }
  191. return nil, xerr.WithStack(err)
  192. }
  193. return &operationPb.UserDetails{
  194. Code: http.StatusOK,
  195. Msg: "ok",
  196. Data: systemUser.ToPb(),
  197. }, nil
  198. }
  199. // IsShowSystemUser 用户是否启用
  200. func (s *StoreEntry) IsShowSystemUser(ctx context.Context, req *operationPb.IsShowSystemUserRequest) error {
  201. systemUser := &model.SystemUser{
  202. Id: int64(req.UserId),
  203. }
  204. if err := s.DB.First(systemUser).Error; err != nil {
  205. if errors.Is(err, gorm.ErrRecordNotFound) {
  206. return xerr.Custom("该用户不存在")
  207. }
  208. return xerr.WithStack(err)
  209. }
  210. if err := s.DB.Model(systemUser).Update("is_show", req.IsShow).Error; err != nil {
  211. return xerr.WithStack(err)
  212. }
  213. return nil
  214. }
  215. // GetSystemUserPermissions 返回系统用户相关菜单权限
  216. func (s *StoreEntry) GetSystemUserPermissions(ctx context.Context, token string) (*operationPb.SystemUserMenuPermissions, error) {
  217. // 解析token
  218. claims, err := jwt.ParseToken(token)
  219. if err != nil {
  220. return nil, xerr.WithStack(err)
  221. }
  222. if err = claims.Valid(); err != nil {
  223. return nil, xerr.WithStack(err)
  224. }
  225. // 根据用户token获取用户数据
  226. systemUser := &model.SystemUser{Name: claims.Username}
  227. if err = s.DB.Where("name = ?", claims.Username).First(systemUser).Error; err != nil {
  228. if errors.Is(err, gorm.ErrRecordNotFound) {
  229. return nil, xerr.Custom("该用户数据不存在")
  230. }
  231. return nil, xerr.WithStack(err)
  232. }
  233. roleIds := systemUser.SystemUserRoleToSlice()
  234. // 获取用户角色数据
  235. systemRoles := make([]*model.SystemRole, 0)
  236. if err = s.DB.Where("is_show = ?", operationPb.IsShow_OK).Find(&systemRoles, roleIds).Error; err != nil {
  237. return nil, xerr.WithStack(err)
  238. }
  239. systemAllPermissionsList := &SystemAllPermissionsList{
  240. PastureList: make([]*model.SystemGroupPasturePermissions, 0),
  241. MenuList: make([]*model.SystemMenuPermissions, 0),
  242. MobileList: make([]*model.SystemMobilePermissions, 0),
  243. }
  244. for _, role := range systemRoles {
  245. item := s.GetSystemAllPermissionsList(ctx, role.Id)
  246. systemAllPermissionsList.PastureList = append(systemAllPermissionsList.PastureList, item.PastureList...)
  247. systemAllPermissionsList.MenuList = append(systemAllPermissionsList.MenuList, item.MenuList...)
  248. systemAllPermissionsList.MobileList = append(systemAllPermissionsList.MobileList, item.MobileList...)
  249. }
  250. systemAllPermissionsList.SystemUserMenuPermissionsUnDuplicate()
  251. groupPastureList, err := s.GetPastureList(ctx, systemAllPermissionsList.PastureList)
  252. if err != nil {
  253. return nil, xerr.WithStack(err)
  254. }
  255. menuList, err := s.GetMenuList(ctx, systemAllPermissionsList.MenuList)
  256. if err != nil {
  257. return nil, xerr.WithStack(err)
  258. }
  259. mobileList, err := s.GetMobileList(ctx, systemAllPermissionsList.MobileList)
  260. if err != nil {
  261. return nil, xerr.WithStack(err)
  262. }
  263. return s.SystemPermissionsFormatPb(groupPastureList, mobileList, menuList), nil
  264. }
  265. // CreateSystemRole 添加角色
  266. func (s *StoreEntry) CreateSystemRole(ctx context.Context, req *operationPb.AddRoleRequest) error {
  267. if err := s.DB.Transaction(func(tx *gorm.DB) error {
  268. // 创建角色数据
  269. role := model.NewSystemRole(req)
  270. if err := tx.Create(role).Error; err != nil {
  271. return xerr.WithStack(err)
  272. }
  273. // 创建角色菜单权限数据
  274. if len(req.MenuId) > 0 {
  275. menuPermissions := model.NewSystemMenuPermissions(role.Id, req.MenuId)
  276. if err := tx.Create(menuPermissions).Error; err != nil {
  277. return xerr.WithStack(err)
  278. }
  279. }
  280. // 创建角色移动端权限数据
  281. if len(req.MobileId) > 0 {
  282. mobilePermissions := model.NewSystemMobilePermissions(role.Id, req.MobileId)
  283. if err := tx.Create(mobilePermissions).Error; err != nil {
  284. return xerr.WithStack(err)
  285. }
  286. }
  287. // 创建角色牧场端权限数据
  288. if len(req.PastureId) > 0 {
  289. pasturePermissions := model.NewSystemGroupPasturePermissions(role.Id, req.PastureId)
  290. if err := tx.Create(pasturePermissions).Error; err != nil {
  291. return xerr.WithStack(err)
  292. }
  293. }
  294. return nil
  295. }); err != nil {
  296. return xerr.WithStack(err)
  297. }
  298. return nil
  299. }
  300. // EditSystemRole 编辑角色
  301. func (s *StoreEntry) EditSystemRole(ctx context.Context, req *operationPb.AddRoleRequest) error {
  302. role := &model.SystemRole{Id: int64(req.Id)}
  303. if err := s.DB.First(role).Error; err != nil {
  304. if errors.Is(err, gorm.ErrRecordNotFound) {
  305. return xerr.Custom("该数据不存在")
  306. }
  307. return xerr.WithStack(err)
  308. }
  309. if err := s.DB.Transaction(func(tx *gorm.DB) error {
  310. updateSystemRole := model.NewSystemRole(req)
  311. if err := tx.Omit("is_show").
  312. Where("id = ?", role.Id).
  313. Updates(updateSystemRole).Error; err != nil {
  314. return xerr.WithStack(err)
  315. }
  316. // 更新牧场权限关系表
  317. pastureIds := req.PastureId
  318. if err := tx.Model(new(model.SystemGroupPasturePermissions)).
  319. Where("role_id = ?", req.Id).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  320. return xerr.WithStack(err)
  321. }
  322. newSystemGroupPasturePermissions := model.NewSystemGroupPasturePermissions(int64(req.Id), pastureIds)
  323. if err := tx.Create(newSystemGroupPasturePermissions).Error; err != nil {
  324. return xerr.WithStack(err)
  325. }
  326. // 更新菜单权限关系表
  327. menuIds := req.MenuId
  328. if err := tx.Model(new(model.SystemMenuPermissions)).
  329. Where("role_id = ?", req.Id).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  330. return xerr.WithStack(err)
  331. }
  332. newSystemMenuPermissions := model.NewSystemMenuPermissions(int64(req.Id), menuIds)
  333. if err := tx.Create(newSystemMenuPermissions).Error; err != nil {
  334. return xerr.WithStack(err)
  335. }
  336. // 更新移动端权限关系表
  337. mobileIds := req.MobileId
  338. if err := tx.Model(new(model.SystemMobilePermissions)).
  339. Where("role_id = ?", req.Id).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  340. return xerr.WithStack(err)
  341. }
  342. newSystemMobilePermissions := model.NewSystemMobilePermissions(int64(req.Id), mobileIds)
  343. if err := tx.Create(newSystemMobilePermissions).Error; err != nil {
  344. return xerr.WithStack(err)
  345. }
  346. return nil
  347. }); err != nil {
  348. return xerr.WithStack(err)
  349. }
  350. return nil
  351. }
  352. // DeleteSystemRole 删除系统角色
  353. func (s *StoreEntry) DeleteSystemRole(ctx context.Context, roleId int64) error {
  354. systemRole := &model.SystemRole{
  355. Id: roleId,
  356. }
  357. if err := s.DB.First(systemRole).Error; err != nil {
  358. if errors.Is(err, gorm.ErrRecordNotFound) {
  359. return xerr.Custom("该数据不存在")
  360. }
  361. return xerr.WithStack(err)
  362. }
  363. if err := s.DB.Model(systemRole).Update("is_show", operationPb.IsShow_NO).Error; err != nil {
  364. return xerr.WithStack(err)
  365. }
  366. return nil
  367. }
  368. // SearchSystemRoleList 查询系统角色
  369. func (s *StoreEntry) SearchSystemRoleList(ctx context.Context, req *operationPb.SearchRoleRequest) (*operationPb.SearchRoleResponse, error) {
  370. systemRoleList := make([]*model.SystemRole, 0)
  371. var count int64 = 0
  372. pref := s.DB.Model(new(model.SystemRole)).Where("is_show = ?", operationPb.IsShow_OK)
  373. if req.Name != "" {
  374. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  375. }
  376. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).
  377. Offset(int(req.Pagination.PageOffset)).Find(&systemRoleList).Error; err != nil {
  378. return nil, xerr.WithStack(err)
  379. }
  380. permissionsPastureMap := make(map[int64][]*model.GroupPasture, 0)
  381. permissionsMenuMap := make(map[int64][]*model.SystemMenu, 0)
  382. for _, role := range systemRoleList {
  383. groupPastureList := make([]*model.GroupPasture, 0)
  384. if err := s.DB.Table(new(model.GroupPasture).TableName()).Select(fmt.Sprintf("%s.*", new(model.GroupPasture).TableName())).
  385. Joins(fmt.Sprintf("left join %s on %s = %s and %s", new(model.SystemGroupPasturePermissions).TableName(), fmt.Sprintf("%s.pasture_id", new(model.SystemGroupPasturePermissions).TableName()),
  386. fmt.Sprintf("%s.id", new(model.GroupPasture).TableName()), fmt.Sprintf("%s.is_show = %d", new(model.SystemGroupPasturePermissions).TableName(), operationPb.IsShow_OK))).
  387. Where(fmt.Sprintf("%s.role_id = ?", new(model.SystemGroupPasturePermissions).TableName()), role.Id).
  388. Find(&groupPastureList).Error; err != nil {
  389. zaplog.Error("SearchSystemRoleList", zap.Any("SystemGroupPasturePermissions", err))
  390. }
  391. permissionsPastureMap[role.Id] = groupPastureList
  392. systemMenuList := make([]*model.SystemMenu, 0)
  393. if err := s.DB.Table(new(model.SystemMenu).TableName()).Select(fmt.Sprintf("%s.*", new(model.SystemMenu).TableName())).
  394. Joins(fmt.Sprintf("left join %s on %s = %s and %s", new(model.SystemMenuPermissions).TableName(), fmt.Sprintf("%s.menu_id", new(model.SystemMenuPermissions).TableName()),
  395. fmt.Sprintf("%s.id", new(model.SystemMenu).TableName()), fmt.Sprintf("%s.is_show = %d", new(model.SystemMenuPermissions).TableName(), operationPb.IsShow_OK))).
  396. Where(fmt.Sprintf("%s.role_id = ?", new(model.SystemMenuPermissions).TableName()), role.Id).Where(fmt.Sprintf("%s.level = ?", new(model.SystemMenu).TableName()), model.Level2).
  397. Find(&systemMenuList).Error; err != nil {
  398. zaplog.Error("SearchSystemRoleList", zap.Any("SystemMenuPermissions", err))
  399. }
  400. permissionsMenuMap[role.Id] = systemMenuList
  401. }
  402. return &operationPb.SearchRoleResponse{
  403. Code: http.StatusOK,
  404. Msg: "ok",
  405. Data: &operationPb.SearchRoleData{
  406. Page: req.Pagination.Page,
  407. Total: int32(count),
  408. PageSize: req.Pagination.PageSize,
  409. List: model.SystemRoleSlice(systemRoleList).ToPB(permissionsPastureMap, permissionsMenuMap),
  410. },
  411. }, nil
  412. }
  413. // SearchSystemRoleListByIds 根据id查询角色列表
  414. func (s *StoreEntry) SearchSystemRoleListByIds(ctx context.Context, ids []int64) ([]*model.SystemRole, error) {
  415. systemRoleList := make([]*model.SystemRole, 0)
  416. if err := s.DB.Model(new(model.SystemRole)).Where("is_show = ?", operationPb.IsShow_OK).Find(&systemRoleList, ids).Error; err != nil {
  417. return nil, xerr.WithStack(err)
  418. }
  419. return systemRoleList, nil
  420. }
  421. // GetRolePermissions 查询系统角色权限
  422. func (s *StoreEntry) GetRolePermissions(ctx context.Context, roleId int64) (*operationPb.RolePermissionsList, error) {
  423. systemRole := &model.SystemRole{
  424. Id: roleId,
  425. }
  426. if err := s.DB.First(systemRole).Error; err != nil {
  427. if errors.Is(err, gorm.ErrRecordNotFound) {
  428. return nil, xerr.Custom("该数据不存在")
  429. }
  430. return nil, xerr.WithStack(err)
  431. }
  432. systemAllPermissionsList := &SystemAllPermissionsList{
  433. PastureList: make([]*model.SystemGroupPasturePermissions, 0),
  434. MenuList: make([]*model.SystemMenuPermissions, 0),
  435. MobileList: make([]*model.SystemMobilePermissions, 0),
  436. }
  437. item := s.GetSystemAllPermissionsList(ctx, systemRole.Id)
  438. systemAllPermissionsList.PastureList = append(systemAllPermissionsList.PastureList, item.PastureList...)
  439. systemAllPermissionsList.MenuList = append(systemAllPermissionsList.MenuList, item.MenuList...)
  440. systemAllPermissionsList.MobileList = append(systemAllPermissionsList.MobileList, item.MobileList...)
  441. return s.AllPermissionsListToRolePermissions(systemAllPermissionsList), nil
  442. }
  443. // CreateSystemMenu 添加系统菜单权限
  444. func (s *StoreEntry) CreateSystemMenu(ctx context.Context, req *operationPb.AddMenuRequest) error {
  445. systemMenu := model.NewSystemMenu(req)
  446. if err := s.DB.Create(systemMenu).Error; err != nil {
  447. return xerr.WithStack(err)
  448. }
  449. return nil
  450. }
  451. // EditSystemMenu 编辑系统菜单权限
  452. func (s *StoreEntry) EditSystemMenu(ctx context.Context, req *operationPb.AddMenuRequest) error {
  453. systemMenu := &model.SystemMenu{Id: int64(req.Id)}
  454. if err := s.DB.First(systemMenu).Error; err != nil {
  455. if errors.Is(err, gorm.ErrRecordNotFound) {
  456. return xerr.Custom("该数据不存在!")
  457. }
  458. return xerr.WithStack(err)
  459. }
  460. updateData := &model.SystemMenu{
  461. Name: req.Name,
  462. MenuType: req.MenuType,
  463. Title: req.Title,
  464. Path: req.Path,
  465. Component: req.Component,
  466. Icon: req.Icon,
  467. Sort: req.Sort,
  468. Redirect: req.Redirect,
  469. ParentId: int64(req.ParentId),
  470. }
  471. if err := s.DB.Model(new(model.SystemMenu)).Omit("is_show").
  472. Where("id = ?", systemMenu.Id).
  473. Updates(updateData).Error; err != nil {
  474. return xerr.WithStack(err)
  475. }
  476. return nil
  477. }
  478. // IsShowSystemMenu 菜单是否启用
  479. func (s *StoreEntry) IsShowSystemMenu(ctx context.Context, req *operationPb.IsShowSystemMenuRequest) error {
  480. systemMenu := &model.SystemMenu{Id: int64(req.MenuId)}
  481. if err := s.DB.First(systemMenu).Error; err != nil {
  482. if errors.Is(err, gorm.ErrRecordNotFound) {
  483. return xerr.Custom("该数据不存在")
  484. }
  485. return xerr.WithStack(err)
  486. }
  487. if err := s.DB.Model(systemMenu).Update("is_show", req.IsShow).Error; err != nil {
  488. return xerr.WithStack(err)
  489. }
  490. return nil
  491. }
  492. // SearchSystemMenuList 菜单列表查询
  493. func (s *StoreEntry) SearchSystemMenuList(ctx context.Context, req *operationPb.SearchMenuRequest) (*operationPb.SearchMenuResponse, error) {
  494. systemMenuLevel1 := make([]*model.SystemMenu, 0)
  495. var count int64 = 0
  496. pref := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level1)
  497. if req.Name != "" {
  498. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  499. }
  500. if err := pref.Order("sort desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  501. Find(&systemMenuLevel1).Debug().Error; err != nil {
  502. return nil, xerr.WithStack(err)
  503. }
  504. systemMenuLevel1 = append(systemMenuLevel1, s.searchMenuLevel23ByLevel1(ctx, systemMenuLevel1)...)
  505. return &operationPb.SearchMenuResponse{
  506. Code: http.StatusOK,
  507. Msg: "ok",
  508. Data: &operationPb.SearchMenuData{
  509. Page: req.Pagination.Page,
  510. Total: int32(count),
  511. List: model.SystemMenuSlice(systemMenuLevel1).ToPB(),
  512. },
  513. }, nil
  514. }
  515. // searchMenuLevel23ByLevel1 根据一级菜单返回对应二三级菜单
  516. func (s *StoreEntry) searchMenuLevel23ByLevel1(ctx context.Context, res []*model.SystemMenu) []*model.SystemMenu {
  517. systemMenuLevel23 := make([]*model.SystemMenu, 0)
  518. if len(res) <= 0 {
  519. return systemMenuLevel23
  520. }
  521. ids1 := make([]int64, 0)
  522. for _, v := range res {
  523. ids1 = append(ids1, v.Id)
  524. }
  525. if err := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level2).
  526. Where("parent_id IN ?", ids1).Order("sort desc").
  527. Find(&systemMenuLevel23).Error; err != nil {
  528. return systemMenuLevel23
  529. }
  530. ids2 := make([]int64, 0)
  531. for _, v := range systemMenuLevel23 {
  532. ids2 = append(ids2, v.Id)
  533. }
  534. systemMenuLevel3 := make([]*model.SystemMenu, 0)
  535. if err := s.DB.Model(new(model.SystemMenu)).Where("is_delete = ? and level = ?", operationPb.IsShow_OK, model.Level3).
  536. Where("parent_id IN ?", ids2).Order("sort desc").
  537. Find(&systemMenuLevel3).Error; err != nil {
  538. return systemMenuLevel23
  539. }
  540. if len(systemMenuLevel3) > 0 {
  541. systemMenuLevel23 = append(systemMenuLevel23, systemMenuLevel3...)
  542. }
  543. return systemMenuLevel23
  544. }
  545. // DeleteSystemMenu 删除系统菜单
  546. func (s *StoreEntry) DeleteSystemMenu(ctx context.Context, menuId int64) error {
  547. systemMenu := &model.SystemMenu{Id: menuId}
  548. if err := s.DB.First(systemMenu).Error; err != nil {
  549. if errors.Is(err, gorm.ErrRecordNotFound) {
  550. return xerr.Custom("该数据不存在")
  551. }
  552. return xerr.WithStack(err)
  553. }
  554. if err := s.DB.Model(systemMenu).Update("is_delete", operationPb.IsShow_NO).Error; err != nil {
  555. return xerr.WithStack(err)
  556. }
  557. return nil
  558. }
  559. // SearchMobileList 查询移动端角色
  560. func (s *StoreEntry) SearchMobileList(ctx context.Context, req *operationPb.SearchMobileRequest) (*operationPb.SearchMobileResponse, error) {
  561. systemMobile := make([]*model.SystemMobile, 0)
  562. var count int64 = 0
  563. pref := s.DB.Model(new(model.SystemMobile)).Where("is_show = ?", operationPb.IsShow_OK)
  564. if req.Name != "" {
  565. pref.Where("name like ?", fmt.Sprintf("%s%s%s", "%", req.Name, "%"))
  566. }
  567. if err := pref.Order("id desc").Count(&count).Limit(int(req.Pagination.PageSize)).Offset(int(req.Pagination.PageOffset)).
  568. Find(&systemMobile).Debug().Error; err != nil {
  569. return nil, xerr.WithStack(err)
  570. }
  571. return &operationPb.SearchMobileResponse{
  572. Code: http.StatusOK,
  573. Msg: "ok",
  574. Data: &operationPb.SearchMobileData{
  575. Page: req.Pagination.Page,
  576. Total: int32(count),
  577. PageSize: req.Pagination.PageSize,
  578. List: model.SystemMobileSlice(systemMobile).ToPB(),
  579. },
  580. }, nil
  581. }