authorities_menus.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package system
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. sysModel "server/model/system"
  7. "server/service/system"
  8. )
  9. const initOrderMenuAuthority = initOrderMenu + initOrderAuthority
  10. type initMenuAuthority struct{}
  11. // auto run
  12. func init() {
  13. system.RegisterInit(initOrderMenuAuthority, &initMenuAuthority{})
  14. }
  15. func (i *initMenuAuthority) MigrateTable(ctx context.Context) (context.Context, error) {
  16. return ctx, nil // do nothing
  17. }
  18. func (i *initMenuAuthority) TableCreated(ctx context.Context) bool {
  19. return false // always replace
  20. }
  21. func (i initMenuAuthority) InitializerName() string {
  22. return "sys_menu_authorities"
  23. }
  24. func (i *initMenuAuthority) InitializeData(ctx context.Context) (next context.Context, err error) {
  25. db, ok := ctx.Value("db").(*gorm.DB)
  26. if !ok {
  27. return ctx, system.ErrMissingDBContext
  28. }
  29. authorities, ok := ctx.Value(initAuthority{}.InitializerName()).([]sysModel.SysAuthority)
  30. if !ok {
  31. return ctx, errors.Wrap(system.ErrMissingDependentContext, "创建 [菜单-权限] 关联失败, 未找到权限表初始化数据")
  32. }
  33. menus, ok := ctx.Value(initMenu{}.InitializerName()).([]sysModel.SysBaseMenu)
  34. if !ok {
  35. return next, errors.Wrap(errors.New(""), "创建 [菜单-权限] 关联失败, 未找到菜单表初始化数据")
  36. }
  37. next = ctx
  38. // 888
  39. if err = db.Model(&authorities[0]).Association("SysBaseMenus").Replace(menus); err != nil {
  40. return next, err
  41. }
  42. // 8881
  43. menu8881 := menus[:2]
  44. menu8881 = append(menu8881, menus[7])
  45. if err = db.Model(&authorities[1]).Association("SysBaseMenus").Replace(menu8881); err != nil {
  46. return next, err
  47. }
  48. // 9528
  49. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Replace(menus[:11]); err != nil {
  50. return next, err
  51. }
  52. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Append(menus[12:17]); err != nil {
  53. return next, err
  54. }
  55. return next, nil
  56. }
  57. func (i *initMenuAuthority) DataInserted(ctx context.Context) bool {
  58. db, ok := ctx.Value("db").(*gorm.DB)
  59. if !ok {
  60. return false
  61. }
  62. auth := &sysModel.SysAuthority{}
  63. if ret := db.Model(auth).
  64. Where("authority_id = ?", 9528).Preload("SysBaseMenus").Find(auth); ret != nil {
  65. if ret.Error != nil {
  66. return false
  67. }
  68. return len(auth.SysBaseMenus) > 0
  69. }
  70. return false
  71. }