-
Notifications
You must be signed in to change notification settings - Fork 72
/
state_change_log.go
74 lines (62 loc) · 1.9 KB
/
state_change_log.go
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
package transition
import (
"fmt"
"strings"
"github.com/jinzhu/gorm"
"github.com/qor/admin"
"github.com/qor/audited"
"github.com/qor/qor/resource"
"github.com/qor/roles"
)
// StateChangeLog a model that used to keep state change logs
type StateChangeLog struct {
gorm.Model
ReferTable string
ReferID string
From string
To string
Note string `sql:"size:1024"`
audited.AuditedModel
}
// GenerateReferenceKey generate reference key used for change log
func GenerateReferenceKey(model interface{}, db *gorm.DB) string {
var (
scope = db.NewScope(model)
primaryValues []string
)
for _, field := range scope.PrimaryFields() {
primaryValues = append(primaryValues, fmt.Sprint(field.Field.Interface()))
}
return strings.Join(primaryValues, "::")
}
// GetStateChangeLogs get state change logs
func GetStateChangeLogs(model interface{}, db *gorm.DB) []StateChangeLog {
var (
changelogs []StateChangeLog
scope = db.NewScope(model)
)
db.Where("refer_table = ? AND refer_id = ?", scope.TableName(), GenerateReferenceKey(model, db)).Find(&changelogs)
return changelogs
}
// GetLastStateChange gets last state change
func GetLastStateChange(model interface{}, db *gorm.DB) *StateChangeLog {
var (
changelog StateChangeLog
scope = db.NewScope(model)
)
db.Where("refer_table = ? AND refer_id = ?", scope.TableName(), GenerateReferenceKey(model, db)).Last(&changelog)
if changelog.To == "" {
return nil
}
return &changelog
}
// ConfigureQorResource used to configure transition for qor admin
func (stageChangeLog *StateChangeLog) ConfigureQorResource(res resource.Resourcer) {
if res, ok := res.(*admin.Resource); ok {
if res.Permission == nil {
res.Permission = roles.Deny(roles.Update, roles.Anyone).Deny(roles.Create, roles.Anyone)
} else {
res.Permission = res.Permission.Deny(roles.Update, roles.Anyone).Deny(roles.Create, roles.Anyone)
}
}
}