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