-
Notifications
You must be signed in to change notification settings - Fork 20
/
contact.go
426 lines (364 loc) · 11.8 KB
/
contact.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package flows
import (
"encoding/json"
"time"
"github.com/nyaruka/gocommon/urns"
"github.com/nyaruka/goflow/contactql"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/utils"
)
// Contact represents a person who is interacting with the flow. It renders as the person's name
// (or perferred URN if name isn't set) in a template, and has the following properties which can be accessed:
//
// * `uuid` the UUID of the contact
// * `name` the full name of the contact
// * `first_name` the first name of the contact
// * `language` the [ISO-639-3](http://www-01.sil.org/iso639-3/) language code of the contact
// * `urns` all [URNs](#context:urn) the contact has set
// * `urns.[scheme]` all the [URNs](#context:urn) the contact has set for the particular URN scheme
// * `urn` shorthand for `@(format_urn(c.urns.0))`, i.e. the contact's preferred [URN](#context:urn) in friendly formatting
// * `groups` all the [groups](#context:group) that the contact belongs to
// * `fields` all the custom contact fields the contact has set
// * `fields.[snaked_field_name]` the value of the specific field
// * `channel` shorthand for `contact.urns.0.channel`, i.e. the [channel](#context:channel) of the contact's preferred URN
//
// Examples:
//
// @contact -> Ryan Lewis
// @contact.name -> Ryan Lewis
// @contact.first_name -> Ryan
// @contact.language -> eng
// @contact.urns -> ["tel:+12065551212","twitterid:54784326227#nyaruka","mailto:foo@bar.com"]
// @contact.urns.0 -> tel:+12065551212
// @contact.urns.tel -> ["tel:+12065551212"]
// @contact.urns.mailto.0 -> mailto:foo@bar.com
// @contact.urn -> (206) 555-1212
// @contact.groups -> ["Testers","Males"]
// @contact.fields -> {"activation_token":"AACC55","age":"23","gender":"Male","join_date":"2017-12-02T00:00:00.000000-02:00"}
// @contact.fields.activation_token -> AACC55
// @contact.fields.gender -> Male
//
// @context contact
type Contact struct {
uuid ContactUUID
id int
name string
language utils.Language
timezone *time.Location
urns URNList
groups *GroupList
fields FieldValues
}
// NewContact returns a new contact
func NewContact(name string, language utils.Language, timezone *time.Location) *Contact {
return &Contact{
uuid: ContactUUID(utils.NewUUID()),
name: name,
language: language,
timezone: timezone,
groups: NewGroupList([]*Group{}),
}
}
// Clone creates a copy of this contact
func (c *Contact) Clone() *Contact {
if c == nil {
return nil
}
return &Contact{
uuid: c.uuid,
id: c.id,
name: c.name,
language: c.language,
timezone: c.timezone,
urns: c.urns.clone(),
groups: c.groups.clone(),
fields: c.fields.clone(),
}
}
// UUID returns the UUID of this contact
func (c *Contact) UUID() ContactUUID { return c.uuid }
// UUID returns the numeric ID of this contact
func (c *Contact) ID() int { return c.id }
// SetLanguage sets the language for this contact
func (c *Contact) SetLanguage(lang utils.Language) { c.language = lang }
// Language gets the language for this contact
func (c *Contact) Language() utils.Language { return c.language }
// SetTimezone sets the timezone of this contact
func (c *Contact) SetTimezone(tz *time.Location) {
c.timezone = tz
}
// Timezone returns the timezone of this contact
func (c *Contact) Timezone() *time.Location { return c.timezone }
// SetName sets the name of this contact
func (c *Contact) SetName(name string) { c.name = name }
// Name returns the name of this contact
func (c *Contact) Name() string { return c.name }
// URNs returns the URNs of this contact
func (c *Contact) URNs() URNList { return c.urns }
// AddURN adds a new URN to this contact
func (c *Contact) AddURN(urn urns.URN) bool {
if c.HasURN(urn) {
return false
}
c.urns = append(c.urns, &ContactURN{URN: urn.Normalize("")})
return true
}
// HasURN checks whether the contact has the given URN
func (c *Contact) HasURN(urn urns.URN) bool {
urn = urn.Normalize("")
for _, u := range c.urns {
if u.URN == urn {
return true
}
}
return false
}
// Groups returns the groups that this contact belongs to
func (c *Contact) Groups() *GroupList { return c.groups }
// Fields returns this contact's field values
func (c *Contact) Fields() FieldValues { return c.fields }
// Reference returns a reference to this contact
func (c *Contact) Reference() *ContactReference { return NewContactReference(c.uuid, c.name) }
// Resolve resolves the given key when this contact is referenced in an expression
func (c *Contact) Resolve(env utils.Environment, key string) types.XValue {
switch key {
case "uuid":
return types.NewXText(string(c.uuid))
case "id":
return types.NewXNumberFromInt(c.id)
case "name":
return types.NewXText(c.name)
case "first_name":
names := utils.TokenizeString(c.name)
if len(names) >= 1 {
return types.NewXText(names[0])
}
return nil
case "language":
return types.NewXText(string(c.language))
case "timezone":
if c.timezone != nil {
return types.NewXText(c.timezone.String())
}
return nil
case "urns":
return c.urns
case "urn":
if len(c.urns) > 0 {
return types.NewXText(c.urns[0].Format())
}
return nil
case "groups":
return c.groups
case "fields":
return c.fields
case "channel":
if len(c.urns) > 0 {
return c.urns[0].Channel()
}
return nil
}
return types.NewXResolveError(c, key)
}
// Describe returns a representation of this type for error messages
func (c *Contact) Describe() string { return "contact" }
// Reduce is called when this object needs to be reduced to a primitive
func (c *Contact) Reduce(env utils.Environment) types.XPrimitive {
return types.NewXText(c.name)
}
// ToXJSON is called when this type is passed to @(json(...))
func (c *Contact) ToXJSON(env utils.Environment) types.XText {
return types.ResolveKeys(env, c, "uuid", "name", "language", "timezone", "urns", "groups", "fields", "channel").ToXJSON(env)
}
var _ types.XValue = (*Contact)(nil)
var _ types.XResolvable = (*Contact)(nil)
// SetFieldValue updates the given contact field value for this contact
func (c *Contact) SetFieldValue(env utils.Environment, fieldSet *FieldSet, key string, rawValue string) {
runEnv := env.(RunEnvironment)
c.fields.setValue(runEnv, fieldSet, key, rawValue)
}
// UpdatePreferredChannel updates the preferred channel
func (c *Contact) UpdatePreferredChannel(channel Channel) {
priorityURNs := make([]*ContactURN, 0)
otherURNs := make([]*ContactURN, 0)
for _, urn := range c.urns {
// tel URNs can be re-assigned, other URN schemes are considered channel specific
if urn.URN.Scheme() == urns.TelScheme && channel.SupportsScheme(urns.TelScheme) {
urn.SetChannel(channel)
}
// move any URNs with this channel to the front of the list
if urn.Channel() == channel {
priorityURNs = append(priorityURNs, urn)
} else {
otherURNs = append(otherURNs, urn)
}
}
c.urns = append(priorityURNs, otherURNs...)
}
// ReevaluateDynamicGroups reevaluates membership of all dynamic groups for this contact
func (c *Contact) ReevaluateDynamicGroups(session Session) error {
groups, err := session.Assets().GetGroupSet()
if err != nil {
return err
}
for _, group := range groups.Dynamic() {
qualifies, err := group.CheckDynamicMembership(session, c)
if err != nil {
return err
}
if qualifies {
c.groups.Add(group)
} else {
c.groups.Remove(group)
}
}
return nil
}
// ResolveQueryKey resolves a contact query search key for this contact
func (c *Contact) ResolveQueryKey(env utils.Environment, key string) []interface{} {
// try as a URN scheme
if urns.IsValidScheme(key) {
if env.RedactionPolicy() != utils.RedactionPolicyURNs {
urnsWithScheme := c.urns.WithScheme(key)
vals := make([]interface{}, len(urnsWithScheme))
for u := range urnsWithScheme {
vals[u] = string(urnsWithScheme[u].URN)
}
return vals
} else {
return nil
}
}
// try as a contact field
for k, value := range c.fields {
if key == string(k) {
fieldValue := value.TypedValue()
var nativeValue interface{}
switch typed := fieldValue.(type) {
case nil:
return nil
case LocationPath:
nativeValue = typed.Name()
case types.XText:
nativeValue = typed.Native()
case types.XNumber:
nativeValue = typed.Native()
case types.XDateTime:
nativeValue = typed.Native()
}
return []interface{}{nativeValue}
}
}
return nil
}
var _ contactql.Queryable = (*Contact)(nil)
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type fieldValueEnvelope struct {
Text types.XText `json:"text"`
Datetime *types.XDateTime `json:"datetime,omitempty"`
Number *types.XNumber `json:"number,omitempty"`
State LocationPath `json:"state,omitempty"`
District LocationPath `json:"district,omitempty"`
Ward LocationPath `json:"ward,omitempty"`
}
type contactEnvelope struct {
UUID ContactUUID `json:"uuid" validate:"required,uuid4"`
ID int `json:"id"`
Name string `json:"name"`
Language utils.Language `json:"language"`
Timezone string `json:"timezone"`
URNs []urns.URN `json:"urns" validate:"dive,urn"`
Groups []*GroupReference `json:"groups,omitempty" validate:"dive"`
Fields map[string]*fieldValueEnvelope `json:"fields,omitempty"`
}
// ReadContact decodes a contact from the passed in JSON
func ReadContact(session Session, data json.RawMessage) (*Contact, error) {
var envelope contactEnvelope
var err error
if err := utils.UnmarshalAndValidate(data, &envelope, "contact"); err != nil {
return nil, err
}
c := &Contact{
uuid: envelope.UUID,
id: envelope.ID,
name: envelope.Name,
language: envelope.Language,
}
if envelope.Timezone != "" {
if c.timezone, err = time.LoadLocation(envelope.Timezone); err != nil {
return nil, err
}
}
if envelope.URNs == nil {
c.urns = make(URNList, 0)
} else {
if c.urns, err = ReadURNList(session, envelope.URNs); err != nil {
return nil, err
}
}
if envelope.Groups == nil {
c.groups = NewGroupList([]*Group{})
} else {
groups := make([]*Group, len(envelope.Groups))
for g := range envelope.Groups {
if groups[g], err = session.Assets().GetGroup(envelope.Groups[g].UUID); err != nil {
return nil, err
}
}
c.groups = NewGroupList(groups)
}
fieldSet, err := session.Assets().GetFieldSet()
if err != nil {
return nil, err
}
c.fields = make(FieldValues, len(fieldSet.All()))
for _, field := range fieldSet.All() {
value := NewEmptyFieldValue(field)
if envelope.Fields != nil {
valueEnvelope := envelope.Fields[field.key]
if valueEnvelope != nil {
value.text = valueEnvelope.Text
value.number = valueEnvelope.Number
value.datetime = valueEnvelope.Datetime
value.state = valueEnvelope.State
value.district = valueEnvelope.District
value.ward = valueEnvelope.Ward
}
}
c.fields[field.key] = value
}
return c, nil
}
// MarshalJSON marshals this contact into JSON
func (c *Contact) MarshalJSON() ([]byte, error) {
ce := &contactEnvelope{
Name: c.name,
UUID: c.uuid,
ID: c.id,
Language: c.language,
}
ce.URNs = c.urns.RawURNs(true)
if c.timezone != nil {
ce.Timezone = c.timezone.String()
}
ce.Groups = make([]*GroupReference, c.groups.Count())
for g, group := range c.groups.All() {
ce.Groups[g] = group.Reference()
}
ce.Fields = make(map[string]*fieldValueEnvelope)
for _, v := range c.fields {
if !v.IsEmpty() {
ce.Fields[v.field.Key()] = &fieldValueEnvelope{
Text: v.text,
Number: v.number,
Datetime: v.datetime,
State: v.state,
District: v.district,
Ward: v.ward,
}
}
}
return json.Marshal(ce)
}