fix
wangpengfei
2023-08-15 c60d971f9bf50e364cc50f0699249217ef9bbb6b
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
package system
 
import (
    "aps_crm/constvar"
    "aps_crm/model"
    "aps_crm/pkg/encrypt"
    "aps_crm/pkg/logx"
    "aps_crm/pkg/snowflake"
    "aps_crm/service"
    "context"
    "fmt"
    "github.com/pkg/errors"
    "gorm.io/gorm"
)
 
const (
    initMenuSequence = iota + 1
    initUserSequence
)
 
type initUser struct{}
 
// auto run
func init() {
    service.RegisterInit(initUserSequence, &initUser{})
}
 
func (i initUser) InitializerName() string {
    return model.User{}.TableName()
}
 
func (i *initUser) InitializeData(ctx context.Context) (next context.Context, err error) {
    adminPassword := encrypt.BcryptHash("123456")
    entities := []*model.User{
        {
            UUID:     fmt.Sprintf("u%v", snowflake.GenerateId()),
            Username: "admin",
            Password: adminPassword,
            NickName: "admin",
            UserType: constvar.UserTypeSuper,
            //ParentId: "basic", // 超级管理员账户的父亲为空字符串,或者起个名字
            //Enable:   true,
        },
    }
    if err = model.NewUserSearch(nil).CreateBatch(entities); err != nil {
        return ctx, errors.Wrap(err, model.User{}.TableName()+"表数据初始化失败!")
    }
    next = context.WithValue(ctx, i.InitializerName(), entities)
 
    menuEntities, ok := ctx.Value(initMenu{}.InitializerName()).([]*model.Menu)
    if !ok {
        return next, errors.New("no find menus")
    }
 
    if err = model.NewUserSearch(nil).ReplaceMenu(entities[0], menuEntities); err != nil {
        return next, err
    }
    logx.Infof("InitializeData success initName:%v", i.InitializerName())
    return next, err
}
 
func (i *initUser) DataInserted(ctx context.Context) bool {
    _, err := model.NewUserSearch(nil).SetUserName("admin").First()
    if errors.Is(err, gorm.ErrRecordNotFound) { // 判断是否存在数据
        return false
    }
    return true
}