-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgo-app-ussd_registration.js
2418 lines (2249 loc) · 88.6 KB
/
go-app-ussd_registration.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
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var go = {};
go;
go.RapidPro = function() {
var vumigo = require('vumigo_v02');
var url_utils = require('url');
var events = vumigo.events;
var Eventable = events.Eventable;
var RapidPro = Eventable.extend(function(self, json_api, base_url, auth_token) {
self.json_api = json_api;
self.base_url = base_url;
self.auth_token = auth_token;
self.json_api.defaults.headers.Authorization = ["Token " + self.auth_token];
self.json_api.defaults.headers["User-Agent"] = ["Jsbox/MenConnect-Registration"];
self.get_contact = function(filters) {
filters = filters || {};
var url = self.base_url + "/api/v2/contacts.json";
return self.json_api.get(url, {params: filters})
.then(function(response){
var contacts = response.data.results;
if(contacts.length > 0){
return contacts[0];
}
else {
return null;
}
});
};
self.update_contact = function(filter, details) {
var url = self.base_url + "/api/v2/contacts.json";
return self.json_api.post(url, {params: filter, data: details})
.then(function(response) {
return response.data;
});
};
self.create_contact = function(details) {
var url = self.base_url + "/api/v2/contacts.json";
return self.json_api.post(url, {data: details})
.then(function(response) {
return response.data;
});
};
self._get_paginated_response = function(url, params) {
/* Gets all the pages of a paginated response */
return self.json_api.get(url, {params: params})
.then(function(response){
var results = response.data.results;
if(response.data.next === null) {
return results;
}
var query = url_utils.parse(response.data.next).query;
return self._get_paginated_response(url, query)
.then(function(response) {
return results.concat(response);
});
});
};
self.get_flows = function(filter) {
var url = self.base_url + "/api/v2/flows.json";
return self._get_paginated_response(url, filter);
};
self.get_flow_by_name = function(name) {
name = name.toLowerCase().trim();
return self.get_flows().then(function(flows){
flows = flows.filter(function(flow) {
return flow.name.toLowerCase().trim() === name;
});
if(flows.length > 0) {
return flows[0];
} else {
return null;
}
});
};
self.start_flow = function(flow_uuid, contact_uuid, contact_urn, extra) {
var url = self.base_url + "/api/v2/flow_starts.json";
var data = {flow: flow_uuid};
if(contact_uuid) {
data.contacts = [contact_uuid];
}
if(contact_urn) {
data.urns = [contact_urn];
}
if(extra) {
data.extra = extra;
}
return self.json_api.post(url, {data: data});
};
});
return RapidPro;
}();
go.Whatsapp = (function() {
var vumigo = require("vumigo_v02");
var events = vumigo.events;
var Eventable = events.Eventable;
var _ = require("lodash");
var url = require("url");
var Whatsapp = Eventable.extend(function(self, json_api, base_url, token) {
self.json_api = json_api;
self.base_url = base_url;
self.json_api.defaults.headers.Authorization = ["Bearer " + token];
self.json_api.defaults.headers["Content-Type"] = ["application/json"];
self.contact_check = function(msisdn, block) {
return self.json_api
.post(url.resolve(self.base_url, "v1/contacts"), {
data: {
blocking: block ? "wait" : "no_wait",
contacts: [msisdn]
}
})
.then(function(response) {
var existing = _.filter(response.data.contacts, function(obj) {
return obj.status === "valid";
});
return !_.isEmpty(existing);
});
};
self.LANG_MAP = {
zul_ZA: "en",
xho_ZA: "en",
afr_ZA: "af",
eng_ZA: "en",
nso_ZA: "en",
tsn_ZA: "en",
sot_ZA: "en",
tso_ZA: "en",
ssw_ZA: "en",
ven_ZA: "en",
nbl_ZA: "en"
};
});
return Whatsapp;
})();
go.app = (function () {
var _ = require("lodash");
var vumigo = require("vumigo_v02");
var utils = require("seed-jsbox-utils").utils;
var App = vumigo.App;
var moment = require("moment");
var Choice = vumigo.states.Choice;
var ChoiceState = vumigo.states.ChoiceState;
var LanguageState = vumigo.states.LanguageChoice;
var FreeText = vumigo.states.FreeText;
var EndState = vumigo.states.EndState;
var JsonApi = vumigo.http.api.JsonApi;
var MenuState = vumigo.states.MenuState;
var MetricsHelper = require('go-jsbox-metrics-helper');
const { BigQuery } = require('@google-cloud/bigquery');
var GoMenConnect = App.extend(function (self) {
App.call(self, "state_start");
var $ = self.$;
self.init = function () {
self.rapidpro = new go.RapidPro(
new JsonApi(self.im, {
headers: { "User-Agent": ["Jsbox/MenConnect-Registration"] }
}),
self.im.config.services.rapidpro.base_url,
self.im.config.services.rapidpro.token
);
self.whatsapp = new go.Whatsapp(
new JsonApi(self.im, {
headers: { "User-Agent": ["Jsbox/MenConnect-Registration"] }
}),
self.im.config.services.whatsapp.base_url,
self.im.config.services.whatsapp.token
);
self.env = self.im.config.env;
self.metric_prefix = [self.env, self.im.config.name].join('.');
async function insertRowsAsStream(row) {
self.im.log("inside the async function");
const bigqueryClient = new BigQuery({
projectId: self.im.config.services.bigquery.project_id,
credentials: {
client_email: self.im.config.services.bigquery.client_email,
private_key: self.im.config.services.bigquery.private_key
}
});
// Insert data into a table
await bigqueryClient
.dataset("menconnet_redis")
.table("status")
.insert(row);
}
self.im.on('state:enter', function(e, opts) {
if (self.env !== "prd"){
return null;
}
const bigquery = new BigQuery();
const date = new Date();
const d =
date.getFullYear() + "-" +
("00" + (date.getMonth() + 1)).slice(-2) + "-" +
("00" + date.getDate()).slice(-2) + " " +
("00" + date.getHours()).slice(-2) + ":" +
("00" + date.getMinutes()).slice(-2) + ":" +
("00" + date.getSeconds()).slice(-2);
const datetime = bigquery.datetime(d);
const msisdn = self.im.user.addr;
const row = [{uuid: null, msisdn: msisdn, message_id: null, chat_id: null, status: e.state.name, inserted_at: datetime, message_received: null, updated_at: null, amount: 1}];
return insertRowsAsStream(row)
.catch(function(e, opts) {
self.im.log.info(e.message);
});
});
self.im.on('state:enter', function (e) {
return self.im.metrics.fire.sum('enter.' + e.state.name, 1);
});
var mh = new MetricsHelper(self.im);
mh
// Total sum of users for each state for app
// <env>.ussd_clinic_rapidpro.sum.unique_users last metric,
// and a <env>.ussd_clinic_rapidpro.sum.unique_users.transient sum metric
.add.total_unique_users([self.metric_prefix, 'sum', 'unique_users'].join('.'))
;
};
self.contact_current_channel = function (contact) {
// Returns the current channel of the contact
if (_.toUpper(_.get(contact, "fields.preferred_channel", "")) === "WHATSAPP") {
return $("WhatsApp");
} else {
return $("SMS");
}
};
self.contact_alternative_channel = function (contact) {
// Returns the alternative channel of the contact
if (_.toUpper(_.get(contact, "fields.preferred_channel", "")) === "WHATSAPP") {
return $("SMS");
} else {
return $("WhatsApp");
}
};
self.contact_in_group = function (contact, groups) {
var contact_groupids = _.map(_.get(contact, "groups", []), "uuid");
return _.intersection(contact_groupids, groups).length > 0;
};
self.add = function (name, creator) {
self.states.add(name, function (name, opts) {
if (self.im.msg.session_event !== "new") return creator(name, opts);
var timeout_opts = opts || {};
timeout_opts.name = name;
return self.states.create("state_timed_out", timeout_opts);
});
};
self.states.add("state_timed_out", function (name, creator_opts) {
return new MenuState(name, {
question: $("Welcome to MenConnect. Please select an option:"),
choices: [
new Choice(creator_opts.name, $("Continue signing up for messages")),
new Choice("state_start", $("Main menu"))
]
});
});
self.states.add("state_start", function (name, opts) {
// Reset user answers when restarting the app
self.im.user.answers = {};
var msisdn = utils.normalize_msisdn(self.im.user.addr, "ZA");
// Fire and forget a background whatsapp contact check
self.whatsapp.contact_check(msisdn, false).then(_.noop, _.noop);
return self.rapidpro
.get_contact({ urn: "whatsapp:" + _.trim(msisdn, "+") })
.then(function (contact) {
self.im.user.set_answer("contact", contact);
// Set the language if we have it
if (_.get(self.languages, _.get(contact, "language"))) {
return self.im.user.set_lang(contact.language);
}
})
.then(function () {
// Delegate to the correct state depending on group membership
var contact = self.im.user.get_answer("contact");
var isactive = _.toUpper(_.get(contact, "fields.isactive")) === "TRUE";
if (
self.contact_in_group(
contact,
self.im.config.registration_group_ids
)
) {
return self.states.create("state_registered");
} else if (isactive) {
return self.states.create("state_registered");
}
else {
return self.states.create("state_message_consent");
}
})
.catch(function (e) {
// Go to error state after 3 failed HTTP requests
opts.http_error_count = _.get(opts, "http_error_count", 0) + 1;
if (opts.http_error_count === 3) {
self.im.log.error(e.message);
return self.states.create("__error__");
}
return self.states.create("state_start", opts);
});
});
var get_content = function (state_name) {
switch (state_name) {
case "state_name_mo":
return $("One final question from me.\n\nMy name is Mo. What's your name?");
case "state_hiv":
return $("What's your question?");
case "state_treatment":
return $("What do you want to know?");
case "state_reminders":
return $("What would you like to do?");
case "state_new_clinic_date":
return $("When is your next expected clinic date?" +
"\nReply with the full date in the format YYYY-MM-DD");
case "state_new_clinic_date_opt_out":
return $("When is your next expected clinic date?" +
"\nReply with the full date in the format YYYY-MM-DD");
case "state_habit_plan":
return $("Doing something every day is a habit.\n\nBuild a treatment habit:" +
"\nAdd it to your daily schedule\n" +
"Tick it off\n" +
"Plan for changes\n" +
"Give yourself time\n");
case "state_profile":
return $("What would you like to view?");
case "state_profile_change_info":
return $("What would you like to change?");
case "state_new_name":
return $("What name would you like me to call you instead?");
case "state_processing_info_menu":
return $("Choose a question:");
case "state_share":
return $("Do you want to receive an SMS that you can share with other men living with HIV?");
case "state_confirm_share":
return $("Thank you. You will receive an SMS with info that you can share with other men living with HIV.");
case "state_resources":
return $("Select a topic:");
case "state_exit":
return $("It was great talking to you. If you ever want to know more about MenConnect" +
" and how to use it, dial *134*406#.\n\nChat soon!\nMo\nMenConnect");
case "state_what_is_hiv":
return $("It's a virus that enters your body through blood / bodily fluids. \n" +
"It attacks your CD4 cells that protect your body against disease.");
case "state_hiv_body":
return $("What does HIV do to my body?. \n" +
"HIV enters your body & makes more. " +
"It attacks your soldiers so you can't fight off common infections.");
case "state_cure":
return $("Is there a cure?\nThere is currently no cure for HIV. But taking ARVs every day can keep you healthy.");
case "state_viral_load":
return $("What is viral load?\nViral load is the amount of virus in your blood. The higher your viral load, the sicker you may be.");
case "state_low_viral_load":
return $("What is low viral load?\nA low viral load is a result of taking treatment every day.\n" +
"Eventually your viral load will be so low that it's undetectable.");
case "state_language":
return $("What language would you like to receive messages in?");
case "state_age_group":
return $("What is your current age?\nSelect your age group:");
case "state_status_known":
return $("When were you first diagnosed positive?");
case "state_exit_not_hiv":
return $("MenConnect sends you messages to help with your treatment.\n" +
"It seems like you don't need treatment." +
"If you sent the wrong answer, dial *134*406# to restart.");
case "state_treatment_started":
return $("Are you or have you been on ARV treatment?");
case "state_treatment_start_date":
return $("When did you start taking ARV treatment?");
case "state_still_on_treatment":
return $("Are you still taking your treatment?");
case "state_viral_detect":
return $("Is your viral load undetectable?");
case "state_generic_error":
return $("Please try again. e.g. 1.");
case "state_how_treatment_works":
return $("Taking your meds daily stops HIV from making more in your blood " +
"so that your CD4 cells can get strong again.\n");
case "state_short_error":
return $("error");
case "state_treatment_frequency":
return $("Take your meds every day, at the same time " +
"as prescribed by your nurse\n");
case "state_treatment_duration":
return $("You need to take your meds every day for the " +
"rest of your life to stay healthy.\n");
case "state_treatment_side_effect":
return $("Every person feels different after taking meds." +
"If it's making you unwell, speak to your nurse.\n");
case "state_treatment_availability":
return $("It is important that you take the meds that is prescribed " +
"to you by a nurse.\n");
case "state_skip_a_day":
return $("You can still take the meds within 6 hrs of usual time. " +
"Don't double your dose the next day if you missed a day.\n");
case "state_menconnect_info":
return $("We process your info to help you on your health journey. " +
"We collect name, age, cell number, language, channel, " +
"status, clinic dates, & survey answers.");
case "state_menconnect_info_need":
return $("We use your personal info to send you messages that are relevant " +
"to the stage of your health journey. " +
"Your info helps the team improve the service.");
case "state_menconnect_info_visibility":
return $("Your data is protected. It's processed by MTN, Cell C, Telkom, Vodacom, " +
"Praekelt, Genesis, Jembi, Turn, WhatsApp & MenStar partners");
case "state_menconnect_info_duration":
return $("We hold your info while you're registered. " +
"If you opt-out, we'll use your info for historical ," +
"research & statistical reasons with your consent.");
}
};
self.states.add("state_registered", function (name) {
return new MenuState(name, {
question: $(
"What would you like to view?"
),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("HIV")),
new Choice("state_treatment", $("Treatment")),
new Choice("state_reminders", $("Reminders")),
new Choice("state_habit_plan", $("Habit Plan")),
new Choice("state_profile", $("My Profile")),
new Choice("state_processing_info_menu", $("Processing my info")),
new Choice("state_share", $("Share")),
new Choice("state_resources", $("Resources"))
]
});
});
self.states.add("state_registered_zulu", function (name) {
return new MenuState(name, {
question: $(
"Funda kabanzi nge?"
),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("HIV")),
new Choice("state_treatment", $("Amaphilisi")),
new Choice("state_reminders", $("Izikhumbuzo")),
new Choice("state_habit_plan", $("Uhlelo Lwemikhuba")),
new Choice("state_profile", $("Iphrofayela")),
new Choice("state_processing_info_menu", $("Ukucubungula ulwazi lwami")),
new Choice("state_share", $("Ukwabelana")),
new Choice("state_resources", $("Izisetshenziswa"))
]
});
});
self.states.add("state_registered_sotho", function (name) {
return new MenuState(name, {
question: $(
"O lakatsa ho shebang?"
),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("HIV")),
new Choice("state_treatment", $("Kalafo")),
new Choice("state_reminders", $("Dikgopotso")),
new Choice("state_habit_plan", $("Morero wa Tlwaelo")),
new Choice("state_profile", $("Porofaele Ya Ka")),
new Choice("state_processing_info_menu", $("Ho lokisa lesedi la ka")),
new Choice("state_share", $("Ho arolelana")),
new Choice("state_resources", $("Dirisose"))
]
});
});
self.add('state_hiv', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
choices: [
new Choice("state_what_is_hiv", $("What is HIV?")),
new Choice("state_hiv_body", $("What does HIV do to my body?")),
new Choice("state_cure", $("Is there a cure?")),
new Choice("state_viral_load", $("What is viral load?")),
new Choice("state_low_viral_load", $("What is low viral load?")),
new Choice("state_registered", $("Back"))
]
});
});
self.add('state_hiv_zulu', function (name) {
return new MenuState(name, {
question: $(
"Uthini umbuzo wakho?"
),
error: get_content("state_generic_error").context(),
choices: [
new Choice("state_what_is_hiv", $("Yini i-HIV?")),
new Choice("state_hiv_body", $("I-HIV yenzani emzimbeni wami?")),
new Choice("state_cure", $("Likhona ikhambi?")),
new Choice("state_viral_load", $("Yini i-viral load?")),
new Choice("state_low_viral_load", $("Yini i-viral load ephansi?")),
new Choice("state_registered", $("Emuva"))
]
});
});
self.add('state_what_is_hiv', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("Back"))
]
});
});
self.add('state_hiv_body', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("Back"))
]
});
});
self.add('state_cure', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("Back to HIV questions"))
]
});
});
self.add('state_viral_load', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("Back to HIV questions"))
]
});
});
self.add('state_low_viral_load', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_hiv", $("Back to HIV questions"))
]
});
});
self.add('state_treatment', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_how_treatment_works", $("How it works?")),
new Choice("state_treatment_frequency", $("When to take it?")),
new Choice("state_treatment_duration", $("How long to take it?")),
new Choice("state_treatment_side_effect", $("Side effects?")),
new Choice("state_treatment_availability", $("How do I get it?")),
new Choice("state_skip_a_day", $("Can I skip a day?")),
new Choice("state_registered", $("Back"))
]
});
});
self.add('state_how_treatment_works', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_treatment_frequency', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_treatment_duration', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_treatment_side_effect', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_treatment_availability', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_skip_a_day', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_short_error").context(),
accept_labels: true,
choices: [
new Choice("state_treatment", $("Back"))
]
});
});
self.add('state_reminders', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_show_clinic_date", $("Show my next expected clinic date")),
new Choice("state_new_clinic_date", $("Change my next clinic date")),
new Choice("state_plan_clinic_visit", $("Plan for my clinic visit")),
new Choice("state_registered", $("Back to menu"))
]
});
});
self.add('state_show_clinic_date', function (name) {
var contact = self.im.user.answers.contact;
var text = $([
"Based on what you told me, I think your next clinic visit is {{next_clinic_visit}}"
].join("\n")).context({
next_clinic_visit:
_.get(contact, "fields.next_clinic_visit", $("None")),
});
return new MenuState(name, {
question: text,
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_new_clinic_date", $("Change your next clinic date")),
new Choice("state_registered", $("Back to menu")),
new Choice("state_exit", $("Exit"))
]
});
});
self.add('state_new_clinic_date', function (name) {
return new FreeText(name, {
question: get_content(name).context(),
check: function (content) {
var givendate = new Date(content);
var today = new Date();
today.setHours(0, 0, 0, 0);
var date_diff = Math.floor((givendate - today)/(24*3600*1000));
//Set a timestamp 400 days forward. We want to reject clinic dates that are more than 400 days from today
var timestamp = new Date().getTime() + (400 * 24 * 60 * 60 * 1000);
var match = content.match(/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/);
if (!match) {
return $(
"Sorry, I don’t recognise that date. Please try again.");
}
if (givendate > timestamp) {
return $("Hmm, that seems a bit far away. " +
"You should at least be going to the clinic every 2 months. Please try again.");
} if (date_diff < -1) {
return $(
"Oops, that day has already passed. Please try again."
);
}
},
next: "state_clinic_date_display"
});
});
self.add('state_exit', function (name) {
return new EndState(name, {
next: "state_start",
text: get_content(name).context(),
});
});
self.add("state_clinic_date_display", function (name) {
var clinic_date = self.im.user.answers.state_new_clinic_date;
return new MenuState(name, {
question: $("You entered {{clinic_date}}. " +
"I'll send you reminders of your upcoming clinic visits " +
"so that you don't forget.").context({ clinic_date: clinic_date }),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_change_clinic_date", $("Confirm")),
new Choice("state_reminders", $("Back"))
]
});
});
self.add("state_change_clinic_date", function (name, opts) {
var msisdn = utils.normalize_msisdn(self.im.user.addr, "ZA");
var answers = self.im.user.answers;
var clinic_date = answers.state_new_clinic_date;
return self.rapidpro
.start_flow(
self.im.config.change_next_clinic_visit_flow_id, null,
"whatsapp:" + _.trim(msisdn, "+"), {
clinic_date: clinic_date
})
.then(function () {
return self.states.create("state_change_clinic_date_success");
}).catch(function (e) {
// Go to error state after 3 failed HTTP request
opts.http_error_count = _.get(opts, "http_error_count", 0) + 1;
if (opts.http_error_count === 3) {
self.im.log.error(e.message);
return self.states.create("__error__", { return_state: name });
}
return self.states.create(name, opts);
});
});
self.add("state_change_clinic_date_success", function (name) {
var answers = self.im.user.answers;
var clinic_date = answers.state_new_clinic_date;
return new MenuState(name, {
question: $("Your next clinic visit has been " +
"changed to {{clinic_date}}").context({ clinic_date: clinic_date }),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_reminders", $("Back")),
new Choice("state_exit", $("Exit"))
]
});
});
self.add('state_plan_clinic_visit', function (name) {
return new MenuState(name, {
question: $("Tip 1: Set a reminder in your phone" +
"\nTip2: Tell someone you're going" +
"\nTip 3: Plan your trip" +
"\nTip 4: Prepare questions for your nurse"),
error: $(
"Please reply with the number that matches your answer, eg .1."
),
accept_labels: true,
choices: [
new Choice("state_registered", $("Back to menu"))
]
});
});
self.add('state_habit_plan', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_registered", $("Back"))
]
});
});
self.add('state_profile', function (name) {
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_profile_view_info", $("See my info")),
new Choice("state_profile_change_info", $("Change my info")),
new Choice("state_opt_out", $("Opt-out")),
new Choice("state_registered", $("Back to menu"))
]
});
});
self.add('state_profile_view_info', function (name) {
var contact = self.im.user.answers.contact;
var text = $([
"Name: {{name}}",
"Cell number: {{msisdn}}",
"Channel: {{channel}}",
"Age: {{age_group}}",
"Language: {{language}}",
"Estimated treatment start date: {{treatment_start_period}}"
].join("\n")).context({
name: _.get(contact, "name") || $('None'),
msisdn: utils.readable_msisdn(self.im.user.addr, "27"),
channel: _.get(contact, "fields.preferred_channel") || $('None'),
age_group: _.get(contact, "fields.age_group") || $("None"),
language: _.get(contact, "language") || $('None'),
treatment_start_period: _.get(contact, "fields.treatment_start_period") || $("None")
});
return new MenuState(name, {
question: text,
choices: [
new Choice("state_profile_change_info", $("Change info")),
new Choice("state_profile", $("Back"))
]
});
});
self.add('state_profile_change_info', function (name) {
var contact = self.im.user.answers.contact;
return new MenuState(name, {
question: get_content(name).context(),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_new_name", $("Name")),
new Choice("state_target_msisdn", $("Cell number")),
new Choice("state_new_age", $("Age")),
new Choice("state_new_language", $("Language")),
new Choice("state_channel_switch_confirm",
$("Change from {{current_channel}} to {{alternative_channel}}").context({
current_channel: self.contact_current_channel(contact),
alternative_channel: self.contact_alternative_channel(contact),
})),
new Choice("state_new_treatment_start_date", $("Treatment start date")),
new Choice("state_profile", $("Back"))
]
});
});
self.add("state_new_name", function (name) {
return new FreeText(name, {
question: get_content(name).context(),
next: function (content) {
return "state_new_name_display";
}
});
});
self.add("state_new_name_display", function (name) {
var new_name = self.im.user.answers.state_new_name;
return new MenuState(name, {
question: $("You entered {{name}}").context({ name: new_name }),
error: get_content("state_generic_error").context(),
accept_labels: true,
choices: [
new Choice("state_change_name", $("confirm")),
new Choice("state_profile_change_info", $("Back"))
]
});
});
self.add("state_change_name", function (name, opts) {
var msisdn = utils.normalize_msisdn(self.im.user.addr, "ZA");
var answers = self.im.user.answers;
var new_name = answers.state_new_name;
return self.rapidpro
.start_flow(
self.im.config.change_name_flow_id, null,
"whatsapp:" + _.trim(msisdn, "+"), {
new_name: new_name
}
).then(function () {
return self.states.create("state_change_name_success");
}).catch(function (e) {
// Go to error state after 3 failed HTTP request
opts.http_error_count = _.get(opts, "http_error_count", 0) + 1;
if (opts.http_error_count === 3) {
self.im.log.error(e.message);
return self.states.create("__error__", { return_state: name });
}
return self.states.create(name, opts);
});
});
self.add("state_change_name_success", function (name) {
var answers = self.im.user.answers;
var new_name = answers.state_new_name;
return new MenuState(name, {
question: $("Thanks. I'll call you {{name}}" +
"\n\nWhat would you like to do next?").context({ name: new_name }),
accept_labels: true,
choices: [
new Choice("state_registered", $("Back to main menu")),
new Choice("state_exit", $("Exit"))
]
});
});
self.add("state_channel_switch_confirm", function (name) {
var contact = self.im.user.answers.contact;
return new MenuState(name, {
question: $("Are you sure you want to get your MenConnect messages on " +
"{{alternative_channel}}?"
).context({
alternative_channel: self.contact_alternative_channel(contact)
}),
choices: [
new Choice("state_channel_switch", $("Yes")),
new Choice("state_no_channel_switch", $("No")),
],
error: $("Sorry we don't recognise that reply. Please enter the number next to " +
"your answer.")
});
});
self.add("state_no_channel_switch", function (name) {
var contact = self.im.user.answers.contact;
return new MenuState(name, {
question: $(
"You'll keep getting your messages on {{channel}}. If you change your mind, " +
"dial *134*406#. What would you like to do?"
).context({ channel: self.contact_current_channel(contact) }),
choices: [
new Choice("state_start", $("Back to main menu")),
new Choice("state_exit", $("Exit"))
],
error: get_content("state_generic_error").context(),
});
});
self.add("state_channel_switch", function (name, opts) {
var contact = self.im.user.answers.contact, flow_uuid;
if (_.toUpper(_.get(contact, "fields.preferred_channel")) === "WHATSAPP") {
flow_uuid = self.im.config.sms_switch_flow_id;
} else {
flow_uuid = self.im.config.whatsapp_switch_flow_id;
}
var msisdn = utils.normalize_msisdn(self.im.user.addr, "ZA");
return self.rapidpro
.start_flow(flow_uuid, null, "whatsapp:" + _.trim(msisdn, "+"))
.then(function () {
return self.states.create("state_channel_switch_success");
}).catch(function (e) {
// Go to error state after 3 failed HTTP requests
opts.http_error_count = _.get(opts, "http_error_count", 0) + 1;
if (opts.http_error_count === 3) {
self.im.log.error(e.message);
return self.states.create("__error__", { return_state: name });
}
return self.states.create(name, opts);
});
});
self.add("state_channel_switch_success", function (name) {
var contact = self.im.user.answers.contact;