forked from qor/notification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction.go
99 lines (85 loc) · 2.58 KB
/
action.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package notification
import (
"errors"
"fmt"
"github.com/qor/admin"
"github.com/qor/qor/utils"
)
func (notification *Notification) Action(action *Action) error {
if a := notification.GetAction(action.Name); a != nil {
message := fmt.Sprintf("Action %v already registered", action.Name)
fmt.Println(message)
return errors.New(message)
}
if action.Label == "" {
action.Label = utils.HumanizeString(action.Name)
}
if action.Method == "" {
if action.URL != nil {
action.Method = "GET"
} else {
action.Method = "PUT"
}
}
if action.FlashMessage == nil {
action.FlashMessage = func(actionArgument *ActionArgument, succeed bool, isUndo bool) string {
context := actionArgument.Context
if succeed {
if isUndo {
return string(context.Admin.T(context.Context, "qor_admin.actions.undone", "Action {{.Name}}: Undone", action))
}
return string(context.Admin.T(context.Context, "qor_admin.actions.executed", "Action {{.Name}}: Executed", action))
} else {
if isUndo {
return string(context.Admin.T(context.Context, "qor_admin.actions.failed_to_undo", "Action {{.Name}}: Failed to undo", action))
}
return string(context.Admin.T(context.Context, "qor_admin.actions.failed_to_execute", "Action {{.Name}}: Failed to execute", action))
}
}
}
if action.Resource != nil && action.Handler == nil {
utils.ExitWithMsg("No Handler registered for action")
}
notification.Actions = append(notification.Actions, action)
return nil
}
func (notification *Notification) GetAction(name string) *Action {
for _, action := range notification.Actions {
if utils.ToParamString(action.Name) == utils.ToParamString(name) {
return action
}
}
return nil
}
type ActionArgument struct {
Message *QorNotification
Context *admin.Context
Argument interface{}
}
type Action struct {
Name string
Label string
Method string
MessageTypes []string
Resource *admin.Resource
Visible func(data *QorNotification, context *admin.Context) bool
URL func(data *QorNotification, context *admin.Context) string
Handler func(actionArgument *ActionArgument) error
Undo func(actionArgument *ActionArgument) error
FlashMessage func(actionArgument *ActionArgument, succeed bool, isUndo bool) string
}
// ToParam used to register routes for actions
func (action Action) ToParam() string {
return utils.ToParamString(action.Name)
}
func (action Action) HasMessageType(t string) bool {
for _, mt := range action.MessageTypes {
if mt == t {
return true
}
}
if len(action.MessageTypes) == 0 {
return true
}
return false
}