forked from qor/qor-example
/
notification.go
63 lines (60 loc) · 2.5 KB
/
notification.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
package admin
import (
"path"
"regexp"
"time"
"github.com/qor/admin"
"github.com/qor/notification"
"github.com/qor/notification/channels/database"
"github.com/qor/qor-example/config/db"
"github.com/qor/qor-example/models/orders"
)
// SetupNotification add notification
func SetupNotification(Admin *admin.Admin) {
Notification := notification.New(¬ification.Config{})
Notification.RegisterChannel(database.New(&database.Config{DB: db.DB}))
Notification.Action(¬ification.Action{
Name: "Confirm",
Visible: func(data *notification.QorNotification, context *admin.Context) bool {
return data.ResolvedAt == nil
},
MessageTypes: []string{"order_returned"},
Handler: func(argument *notification.ActionArgument) error {
orderID := regexp.MustCompile(`#(\d+)`).FindStringSubmatch(argument.Message.Body)[1]
err := argument.Context.GetDB().Model(&orders.Order{}).Where("id = ? AND returned_at IS NULL", orderID).Update("returned_at", time.Now()).Error
if err == nil {
return argument.Context.GetDB().Model(argument.Message).Update("resolved_at", time.Now()).Error
}
return err
},
Undo: func(argument *notification.ActionArgument) error {
orderID := regexp.MustCompile(`#(\d+)`).FindStringSubmatch(argument.Message.Body)[1]
err := argument.Context.GetDB().Model(&orders.Order{}).Where("id = ? AND returned_at IS NOT NULL", orderID).Update("returned_at", nil).Error
if err == nil {
return argument.Context.GetDB().Model(argument.Message).Update("resolved_at", nil).Error
}
return err
},
})
Notification.Action(¬ification.Action{
Name: "Check it out",
MessageTypes: []string{"order_paid_cancelled", "order_processed", "order_returned"},
URL: func(data *notification.QorNotification, context *admin.Context) string {
return path.Join("/admin/orders/", regexp.MustCompile(`#(\d+)`).FindStringSubmatch(data.Body)[1])
},
})
Notification.Action(¬ification.Action{
Name: "Dismiss",
MessageTypes: []string{"order_paid_cancelled", "info", "order_processed", "order_returned"},
Visible: func(data *notification.QorNotification, context *admin.Context) bool {
return data.ResolvedAt == nil
},
Handler: func(argument *notification.ActionArgument) error {
return argument.Context.GetDB().Model(argument.Message).Update("resolved_at", time.Now()).Error
},
Undo: func(argument *notification.ActionArgument) error {
return argument.Context.GetDB().Model(argument.Message).Update("resolved_at", nil).Error
},
})
Admin.NewResource(Notification)
}