-
Notifications
You must be signed in to change notification settings - Fork 20
/
urns.go
86 lines (69 loc) · 2.35 KB
/
urns.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
package modifiers
import (
"encoding/json"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/envs"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/flows/events"
"github.com/nyaruka/goflow/utils"
)
func init() {
registerType(TypeURNs, readURNsModifier)
}
// TypeURNs is the type of our URNs modifier
const TypeURNs string = "urns"
// URNsModification is the type of modification to make
type URNsModification string
// the supported types of modification
const (
URNsAppend URNsModification = "append"
URNsRemove URNsModification = "remove"
URNsSet URNsModification = "set"
)
// URNsModifier modifies the URNs on a contact
type URNsModifier struct {
baseModifier
URNs []urns.URN `json:"urns" validate:"required"`
Modification URNsModification `json:"modification" validate:"required,eq=append|eq=remove|eq=set"`
}
// NewURNs creates a new URNs modifier
func NewURNs(urnz []urns.URN, modification URNsModification) *URNsModifier {
return &URNsModifier{
baseModifier: newBaseModifier(TypeURNs),
URNs: urnz,
Modification: modification,
}
}
// Apply applies this modification to the given contact
func (m *URNsModifier) Apply(env envs.Environment, assets flows.SessionAssets, contact *flows.Contact, log flows.EventCallback) {
modified := false
if m.Modification == URNsSet {
modified = contact.ClearURNs()
}
for _, urn := range m.URNs {
// normalize the URN
urn := urn.Normalize(string(env.DefaultCountry()))
if err := urn.Validate(); err != nil {
log(events.NewErrorf("'%s' is not valid URN", urn))
} else {
if m.Modification == URNsAppend || m.Modification == URNsSet {
modified = contact.AddURN(urn, nil)
} else {
modified = contact.RemoveURN(urn)
}
}
}
if modified {
log(events.NewContactURNsChanged(contact.URNs().RawURNs()))
m.reevaluateGroups(env, assets, contact, log)
}
}
var _ flows.Modifier = (*URNsModifier)(nil)
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
func readURNsModifier(assets flows.SessionAssets, data json.RawMessage, missing assets.MissingCallback) (flows.Modifier, error) {
m := &URNsModifier{}
return m, utils.UnmarshalAndValidate(data, m)
}