-
Notifications
You must be signed in to change notification settings - Fork 20
/
field.go
87 lines (71 loc) · 2.43 KB
/
field.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
package modifiers
import (
"encoding/json"
"github.com/nyaruka/goflow/assets"
"github.com/nyaruka/goflow/flows"
"github.com/nyaruka/goflow/flows/events"
"github.com/nyaruka/goflow/utils"
)
func init() {
RegisterType(TypeField, readFieldModifier)
}
// TypeField is the type of our field modifier
const TypeField string = "field"
// FieldModifier modifies a field value on the contact
type FieldModifier struct {
baseModifier
field *flows.Field
value *flows.Value
}
// NewFieldModifier creates a new field modifier
func NewFieldModifier(field *flows.Field, value *flows.Value) *FieldModifier {
return &FieldModifier{
baseModifier: newBaseModifier(TypeField),
field: field,
value: value,
}
}
// Apply applies this modification to the given contact
func (m *FieldModifier) Apply(env utils.Environment, assets flows.SessionAssets, contact *flows.Contact, log flows.EventCallback) {
oldValue := contact.Fields().Get(m.field)
if !m.value.Equals(oldValue) {
// truncate text value if necessary
if m.value != nil && m.value.Text.Length() > env.MaxValueLength() {
m.value.Text = m.value.Text.Slice(0, env.MaxValueLength())
}
contact.Fields().Set(m.field, m.value)
log(events.NewContactFieldChangedEvent(m.field, m.value))
m.reevaluateDynamicGroups(env, assets, contact, log)
}
}
var _ flows.Modifier = (*FieldModifier)(nil)
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type fieldModifierEnvelope struct {
utils.TypedEnvelope
Field *assets.FieldReference `json:"field" validate:"required"`
Value *flows.Value `json:"value"`
}
func readFieldModifier(assets flows.SessionAssets, data json.RawMessage, missing assets.MissingCallback) (flows.Modifier, error) {
e := &fieldModifierEnvelope{}
if err := utils.UnmarshalAndValidate(data, e); err != nil {
return nil, err
}
var field *flows.Field
if e.Field != nil {
field = assets.Fields().Get(e.Field.Key)
if field == nil {
missing(e.Field)
return nil, ErrNoModifier // nothing left to modify without the field
}
}
return NewFieldModifier(field, e.Value), nil
}
func (m *FieldModifier) MarshalJSON() ([]byte, error) {
return json.Marshal(&fieldModifierEnvelope{
TypedEnvelope: utils.TypedEnvelope{Type: m.Type()},
Field: m.field.Reference(),
Value: m.value,
})
}