authorities_menus.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package system
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. sysModel "log-server/model/system"
  7. "log-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[:20]); err != nil {
  40. return next, err
  41. }
  42. if err = db.Model(&authorities[0]).Association("SysBaseMenus").Append(menus[21:]); err != nil {
  43. return next, err
  44. }
  45. // 8881
  46. menu8881 := menus[:2]
  47. menu8881 = append(menu8881, menus[7])
  48. if err = db.Model(&authorities[1]).Association("SysBaseMenus").Replace(menu8881); err != nil {
  49. return next, err
  50. }
  51. // 9528
  52. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Replace(menus[:12]); err != nil {
  53. return next, err
  54. }
  55. if err = db.Model(&authorities[2]).Association("SysBaseMenus").Append(menus[13:17]); err != nil {
  56. return next, err
  57. }
  58. return next, nil
  59. }
  60. func (i *initMenuAuthority) DataInserted(ctx context.Context) bool {
  61. db, ok := ctx.Value("db").(*gorm.DB)
  62. if !ok {
  63. return false
  64. }
  65. var count int64
  66. if err := db.Model(&sysModel.SysAuthority{}).
  67. Where("authority_id = ?", "9528").Preload("SysBaseMenus").Count(&count); err != nil {
  68. return count == 16
  69. }
  70. return false
  71. }