This repository has been archived by the owner on Jan 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmessages.js
250 lines (230 loc) · 8.1 KB
/
messages.js
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
var _ = require('underscore'),
template = require('./template'),
utils = require('./utils'),
logger = require('./logger');
function extendedTemplateContext(doc, extras) {
const templateContext = module.exports.extractTemplateContext(doc);
if (extras.templateContext) {
_.defaults(templateContext, extras.templateContext);
}
if (extras.patient) {
_.defaults(templateContext, module.exports.extractTemplateContext(extras.patient));
// Don't want to add this to extractTemplateContext as 'name' is too generic
// and eTC gets called elsewhere
templateContext.patient_name = templateContext.patient_name || extras.patient.name;
}
if (extras.registrations && extras.registrations.length) {
_.defaults(templateContext, module.exports.extractTemplateContext(extras.registrations[0]));
}
if (!extras.patient && extras.registrations && extras.registrations.length) {
// If you're providing registrations to the template context you need to
// provide the patient contact document as well. Patients can be
// "registered" through the UI, only creating a patient and no registration report
throw Error('Cannot provide registrations to template context without a patient');
}
return templateContext;
}
/**
* Expected opts :
* - doc
* - message : template for the message
* - phone (optional, will get clinic phone if absent)
* - templateContext (optional)
* - registrations (optional)
* - patient (optional)
* - state (optional)
* - taskFields (optional)
* All other fields are ignored.
*/
function addMessage(opts) {
var self = module.exports,
doc = opts.doc,
templateContext = extendedTemplateContext(doc, opts),
phone = opts.phone || self.getRecipientPhone(doc, 'clinic');
if (!phone) {
logger.debug(`Can't add message, no phone number found in opts: ${opts}`);
return;
}
if (!opts.message) {
logger.debug(`Can't add message, no message template found in opts: ${opts}`);
return;
}
let outputOpts = {
phone: String(phone),
message: template.render(opts.message, templateContext),
state: utils.isOutgoingAllowed(doc.from) ? opts.state : 'denied'
};
_.defaults(outputOpts, opts.taskFields);
if (logger.level === 'debug') {
logger.debug(`Adding message: ${outputOpts}`);
}
try {
utils.addMessage(doc, outputOpts);
} catch(e) {
utils.addError(doc, {
message: e.message + ': ' + opts.message,
code: 'parse_error'
});
}
}
/*
* Take message configuration and return message content. The configuration
* should have either a `messages` property with an array of messages, or
* a `translation_key` property with a string.
* Use locale if found otherwise defaults to 'en'.
*/
function getMessage(configuration, locale) {
if (!configuration) {
return '';
}
// use the translation key if provided
if (configuration.translation_key) {
return utils.translate(configuration.translation_key, locale);
}
// otherwise, use the configured messages (deprecated)
var messages = configuration.messages || configuration.message;
if (!_.isArray(messages)) {
console.warn('Message property should be an array. Please check your configuration.');
return '';
}
if (!messages.length) {
console.warn('Message property array was empty. Please check your configuration.');
return '';
}
// default to first item in messages array in case locale match fails
var message = _.findWhere(messages, { locale: locale || 'en' }) || messages[0];
return (message.content && message.content.trim()) || '';
}
module.exports = {
/*
* Provide some extra template context, internal fields always override
* doc/form fields.
*/
extractTemplateContext: function(doc) {
var clinic = utils.getClinic(doc);
var internal = {
contact: clinic && clinic.contact,
clinic: clinic,
parent: utils.getHealthCenter(doc),
health_center: utils.getHealthCenter(doc),
grandparent: utils.getDistrict(doc),
district: utils.getDistrict(doc)
};
return _.defaults(internal, doc.fields, doc);
},
scheduleMessage: function(doc, msg, phone, registrations, patient) {
var templateContext = extendedTemplateContext(doc, {
registrations: registrations,
patient: patient
});
phone = phone ? String(phone) : phone;
try {
utils.addScheduledMessage(doc, {
due: msg.due,
message: template.render(msg.message, templateContext),
group: msg.group,
phone: phone,
type: msg.type,
translation_key: msg.translation_key
});
} catch(e) {
utils.addError(doc, {
message: e.message + ': ' + msg.message,
code: 'parse_error'
});
}
},
/*
* Try to match a recipient return undefined otherwise.
* Assumes `parent` is a health_center and `grandparent` is a district,
* which might not work in all setups.
*/
getRecipientPhone: function(doc, recipient, _default) {
if (!doc) {
return;
}
recipient = recipient && recipient.trim();
if (!recipient) {
return _default || doc.from;
}
var phone;
if (recipient === 'reporting_unit') {
phone = doc.from;
} else if (recipient === 'clinic') {
phone = utils.getClinicPhone(doc);
} else if (recipient === 'parent') {
phone = utils.getHealthCenterPhone(doc);
} else if (recipient === 'grandparent') {
phone = utils.getDistrictPhone(doc);
}
if (!phone && doc.fields && doc.fields[recipient]) {
// try to resolve a specified property/field name
phone = doc.fields[recipient];
}
return phone || _default || doc.from;
},
addMessage: addMessage,
getMessage: getMessage,
notifyGrandparent: function(doc, message, options) {
var self = module.exports;
addMessage({
doc: doc,
message: message,
phone: self.getRecipientPhone(doc, 'grandparent_phone'),
templateContext: options
});
},
notifyParent: function(doc, message, options) {
var self = module.exports;
addMessage({
doc: doc,
message: message,
phone: self.getRecipientPhone(doc, 'parent_phone'),
templateContext: options
});
},
addReply: function(doc, message, options) {
var self = module.exports;
addMessage({
doc: doc,
message: message,
phone: self.getRecipientPhone(doc, 'clinic'),
templateContext: options
});
},
addErrors: function(doc, errors) {
var self = module.exports;
_.each(errors, function(error) {
self.addError(doc, error);
});
},
addError: function(doc, error) {
if (_.isString(error)){
error = {
message: error
};
} else if (_.isObject(error)) {
if (!error.message) {
console.warn('Message property missing on error object.');
error.message = 'Error: ' + JSON.stringify(error);
}
} else {
console.warn('Error should be an object or string.');
error = {
message: 'Error: ' + JSON.stringify(error)
};
}
// support mustache template syntax in error messages
try {
error.message = template.render(
error.message, module.exports.extractTemplateContext(doc)
);
utils.addError(doc, error);
} catch(e) {
utils.addError(doc, {
message: e.message + ': ' + JSON.stringify(error),
code: 'parse_error'
});
}
}
};