-
Notifications
You must be signed in to change notification settings - Fork 20
/
field.go
331 lines (280 loc) · 8.98 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
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
package flows
import (
"encoding/json"
"fmt"
"github.com/nyaruka/goflow/excellent/types"
"github.com/nyaruka/goflow/utils"
)
// FieldValueType is the data type of values for each field
type FieldValueType string
// field value types
const (
FieldValueTypeText FieldValueType = "text"
FieldValueTypeNumber FieldValueType = "number"
FieldValueTypeDatetime FieldValueType = "datetime"
FieldValueTypeWard FieldValueType = "ward"
FieldValueTypeDistrict FieldValueType = "district"
FieldValueTypeState FieldValueType = "state"
)
// Field represents a contact field
type Field struct {
key string
name string
valueType FieldValueType
}
// NewField returns a new field object with the passed in uuid, key and value type
func NewField(key string, name string, valueType FieldValueType) *Field {
return &Field{key: key, name: name, valueType: valueType}
}
// Key returns the key of the field
func (f *Field) Key() string { return f.key }
// FieldValue represents a contact's value for a specific field
type FieldValue struct {
field *Field
text types.XText
datetime *types.XDateTime
number *types.XNumber
state LocationPath
district LocationPath
ward LocationPath
}
// NewEmptyFieldValue creates a new empty value for the given field
func NewEmptyFieldValue(field *Field) *FieldValue {
return &FieldValue{field: field}
}
// IsEmpty returns whether this field value is set for any type
func (v *FieldValue) IsEmpty() bool {
return v.text.Empty() && v.datetime == nil && v.number == nil && v.state == "" && v.district == "" && v.ward == ""
}
// TypedValue returns the value in its proper type
func (v *FieldValue) TypedValue() types.XValue {
switch v.field.valueType {
case FieldValueTypeText:
return v.text
case FieldValueTypeDatetime:
if v.datetime != nil {
return *v.datetime
}
case FieldValueTypeNumber:
if v.number != nil {
return *v.number
}
case FieldValueTypeState:
return types.NewXText(string(v.state))
case FieldValueTypeDistrict:
return types.NewXText(string(v.district))
case FieldValueTypeWard:
return types.NewXText(string(v.ward))
}
return nil
}
// Resolve resolves the given key when this field value is referenced in an expression
func (v *FieldValue) Resolve(env utils.Environment, key string) types.XValue {
switch key {
case "text":
return v.text
}
return types.NewXResolveError(v, key)
}
// Describe returns a representation of this type for error messages
func (v *FieldValue) Describe() string { return "field value" }
// Reduce is called when this object needs to be reduced to a primitive
func (v *FieldValue) Reduce(env utils.Environment) types.XPrimitive {
typed := v.TypedValue()
if typed != nil {
return typed.Reduce(env)
}
return nil
}
// ToXJSON is called when this type is passed to @(json(...))
func (v *FieldValue) ToXJSON(env utils.Environment) types.XText {
j, _ := types.ToXJSON(env, v.Reduce(env))
return j
}
var _ types.XValue = (*FieldValue)(nil)
var _ types.XResolvable = (*FieldValue)(nil)
// EmptyFieldValue is used when a contact doesn't have a value set for a field
var EmptyFieldValue = &FieldValue{}
// FieldValues is the set of all field values for a contact
type FieldValues map[string]*FieldValue
// Clone returns a clone of this set of field values
func (f FieldValues) clone() FieldValues {
clone := make(FieldValues, len(f))
for k, v := range f {
clone[k] = v
}
return clone
}
func (f FieldValues) getValue(key string) *FieldValue {
return f[key]
}
func (f FieldValues) setValue(env RunEnvironment, fieldSet *FieldSet, key string, rawValue string) error {
field := fieldSet.FindByKey(key)
if field == nil {
return fmt.Errorf("no such field: %s", key)
}
if rawValue == "" {
f[key] = NewEmptyFieldValue(field)
return nil
}
var asText = types.NewXText(rawValue)
var asDateTime *types.XDateTime
var asNumber *types.XNumber
if parsedNumber, xerr := types.ToXNumber(env, asText); xerr == nil {
asNumber = &parsedNumber
}
if parsedDate, xerr := types.ToXDateTime(env, asText); xerr == nil {
asDateTime = &parsedDate
}
var asLocation *utils.Location
// for locations, if it has a '>' then it is explicit, look it up that way
if IsPossibleLocationPath(rawValue) {
asLocation, _ = env.LookupLocation(LocationPath(rawValue))
} else {
var matchingLocations []*utils.Location
if field.valueType == FieldValueTypeWard {
parent := f.getFirstLocationValue(env, fieldSet, FieldValueTypeDistrict)
if parent != nil {
matchingLocations, _ = env.FindLocationsFuzzy(rawValue, LocationLevelWard, parent)
}
} else if field.valueType == FieldValueTypeDistrict {
parent := f.getFirstLocationValue(env, fieldSet, FieldValueTypeState)
if parent != nil {
matchingLocations, _ = env.FindLocationsFuzzy(rawValue, LocationLevelDistrict, parent)
}
} else if field.valueType == FieldValueTypeState {
matchingLocations, _ = env.FindLocationsFuzzy(rawValue, LocationLevelState, nil)
}
if len(matchingLocations) > 0 {
asLocation = matchingLocations[0]
}
}
var asState, asDistrict, asWard LocationPath
if asLocation != nil {
switch asLocation.Level() {
case LocationLevelState:
asState = LocationPath(asLocation.Path())
case LocationLevelDistrict:
asState = LocationPath(asLocation.Parent().Path())
asDistrict = LocationPath(asLocation.Path())
case LocationLevelWard:
asState = LocationPath(asLocation.Parent().Parent().Path())
asDistrict = LocationPath(asLocation.Parent().Path())
asWard = LocationPath(asLocation.Path())
}
}
f[key] = &FieldValue{
field: field,
text: asText,
datetime: asDateTime,
number: asNumber,
state: asState,
district: asDistrict,
ward: asWard,
}
return nil
}
func (f FieldValues) getFirstLocationValue(env RunEnvironment, fieldSet *FieldSet, valueType FieldValueType) *utils.Location {
field := fieldSet.FirstOfType(FieldValueTypeDistrict)
if field == nil {
return nil
}
value := f[field.Key()].TypedValue()
location, err := env.LookupLocation(value.(LocationPath))
if err != nil {
return nil
}
return location
}
// Length is called to get the length of this object
func (f FieldValues) Length() int {
return len(f)
}
// Resolve resolves the given key when this set of field values is referenced in an expression
func (f FieldValues) Resolve(env utils.Environment, key string) types.XValue {
val, exists := f[key]
if !exists {
return types.NewXErrorf("no such contact field '%s'", key)
}
return val
}
// Describe returns a representation of this type for error messages
func (f FieldValues) Describe() string { return "field values" }
// Reduce is called when this object needs to be reduced to a primitive
func (f FieldValues) Reduce(env utils.Environment) types.XPrimitive {
values := types.NewEmptyXMap()
for k, v := range f {
values.Put(string(k), v)
}
return values
}
// ToXJSON is called when this type is passed to @(json(...))
func (f FieldValues) ToXJSON(env utils.Environment) types.XText {
return f.Reduce(env).ToXJSON(env)
}
var _ types.XValue = (FieldValues)(nil)
var _ types.XLengthable = (FieldValues)(nil)
var _ types.XResolvable = (FieldValues)(nil)
// FieldSet defines the unordered set of all fields for a session
type FieldSet struct {
fields []*Field
fieldsByKey map[string]*Field
}
// NewFieldSet creates a new set of fields
func NewFieldSet(fields []*Field) *FieldSet {
s := &FieldSet{
fields: fields,
fieldsByKey: make(map[string]*Field, len(fields)),
}
for _, field := range s.fields {
s.fieldsByKey[field.key] = field
}
return s
}
// FindByKey finds the contact field with the given key
func (s *FieldSet) FindByKey(key string) *Field {
return s.fieldsByKey[key]
}
// FirstOfType returns the first field in this set with the given value type
func (s *FieldSet) FirstOfType(valueType FieldValueType) *Field {
for _, field := range s.fields {
if field.valueType == valueType {
return field
}
}
return nil
}
// All returns all the fields in this set
func (s *FieldSet) All() []*Field {
return s.fields
}
//------------------------------------------------------------------------------------------
// JSON Encoding / Decoding
//------------------------------------------------------------------------------------------
type fieldEnvelope struct {
Key string `json:"key"`
Name string `json:"name"`
ValueType FieldValueType `json:"value_type,omitempty"`
}
// ReadField reads a contact field from the given JSON
func ReadField(data json.RawMessage) (*Field, error) {
var fe fieldEnvelope
if err := utils.UnmarshalAndValidate(data, &fe); err != nil {
return nil, fmt.Errorf("unable to read field: %s", err)
}
return NewField(fe.Key, fe.Name, fe.ValueType), nil
}
// ReadFieldSet reads a set of contact fields from the given JSON
func ReadFieldSet(data json.RawMessage) (*FieldSet, error) {
items, err := utils.UnmarshalArray(data)
if err != nil {
return nil, err
}
fields := make([]*Field, len(items))
for d := range items {
if fields[d], err = ReadField(items[d]); err != nil {
return nil, err
}
}
return NewFieldSet(fields), nil
}