-
Notifications
You must be signed in to change notification settings - Fork 3
/
comm.js
1767 lines (1649 loc) · 68.5 KB
/
comm.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
/*
* -------------------------------------------------------------------------------
* comm.js
*
* Handle the Socket.io interface with the clients, the IPC interface with the
* other cluster worker processes, and the RxJS interface to the other modules
* in this worker process. Expose only RxJS streams to the other modules and
* leave the Socket.io and IPC interfaces private to this module.
*
* There are three communication streams (system, site, and data) that are active
* across each of the three interfaces (Socket.io, IPC, and RxJS). All messages
* created are delivered to all subscribers in the current process, to all
* subscribers in other cluster processes, and to all subscribing clients
* irrespective of which server process they are currently attached to.
*
* All messages are "wrapped" in a wrapper that contains the following fields:
* - msgId - a unique id for the message
* - namespace - one of system, site, or data
* - updatedAt - date/time in milliseconds of creation/update
* - workerId - the process.env.WORKER_ID that created/updated the message
* - scope - if specified, names the worker id that message is limited to
* - data - the payload
*
* The system stream:
* - Purpose: server to client broadcast to subscribers. System messages pertain to
* the server's operations as opposed to application issues. Examples include
* a shutdown notice, shutdown canceled, notification that a worker process is
* dying, messages to administrator's about what users are doing, etc.
* - Characteristics:
* - Client to server system messages are not allowed.
* - Messages are not aggregated on the server like site messages are. Instead
* messages are sent individually to all subscribers.
* - At subscription, the most recent message is not conveyed to the subscriber,
* only new messages after that point are delivered to that subscriber.
*
* The site stream:
* - Purpose: server to server or server to client broadcast to subscribers. Site
* messages generally are for communication about statistics and facts about the
* Midwife-EMR instance itself at the application level. Examples might be the
* number of prenatalExams conducted by today or the number of patients waiting
* to be served.
* - Characteristics:
* - Client to server site messages are not allowed.
* - The stream always conveys an object to subscribers containing all of the
* key/value pairs set up until that point in time. There is not a separate
* message delivered for each key/value pair because all key/values, no matter
* what process/module/function set it, will be aggregated to the object.
* - At subscription, the most recent message will be conveyed to the subscriber.
* - Whenever there is a change or addition of any key/value pair, a new message
* is delivered to subscribers with all of the key/value pairs.
* - Scope is always unspecified for site messages, which are delivered to all
* processes without exception.
*
* The data stream:
* - Purpose: client to server process and server process to client broadcast to
* subscribers. All data management is handled through the data stream, including
* the client retrieving data or the server pushing data to interested clients or
* the client sending changed data, etc.
* - Characteristics:
* - Client to server data messages are allowed.
* - Subscriptions to all data messages are not allowed, only subsets of data.
* - Allowable subscription levels:
* - Generally subscriptions are to the ids of major tables as opposed to
* the more detailed tables.
* - Though there are exceptions, such as an administrator receiving notifications
* about changes to all records in the user table, for example.
* - Sub-categories of data client to server messages.
* - Get data
* - Scope of message is automatically limited to receiving process, other
* processes on the server do not receive the message.
* - Data is returned to client.
* - Message is not broadcast to other clients.
* - Subscribe to changes for specific data
* - Scope of message allows notification of all processes.
* - Update data
* - Update is handled be receiving process.
* - Other processes are notified of change.
*
*
* -------------------------------------------------------------------------------
*/
var rx = require('rx')
, uuid = require('uuid')
, _ = require('underscore')
, fs = require('fs')
, assert = require('assert')
, moment = require('moment')
, cfg = require('./config')
, User = require('./models').User
, getLookupTable = require('./routes/comm/lookupTables').getLookupTable
, getTable2 = require('./routes/comm/lookupTables').getTable2
, saveUser = require('./routes/comm/userRoles').saveUser
, saveClientConsole = require('./routes/comm/clientConsole').saveClientConsole
, checkInOut = require('./routes/comm/checkInOut').checkInOut
, buildChangeObject = require('./changes').buildChangeObject
, socketToUserInfo = require('./commUtils').socketToUserInfo
, sendData = require('./commUtils').sendData
, isInitialized = false
, sessionMiddleware
, rxSite // Stream for site messages
, rxSystem // Stream for system messages
, rxData // Stream for data messages
, cntSystem = 0
, cntSite = 0
, siteSubject
, siteSubjectData
, systemSubject
, dataSubject
, CONST = require('./commUtils').getConstants('CONST')
, DATA_CHANGE = require('./commUtils').getConstants('DATA_CHANGE') // Note: used in old code only.
, SYSTEM_LOG = 'SYSTEM_LOG'
, DATA_TABLE_REQUEST = 'DATA_TABLE_REQUEST'
, DATA_TABLE_SUCCESS = 'DATA_TABLE_SUCCESS'
, DATA_TABLE_FAILURE = 'DATA_TABLE_FAILURE'
, ADD_USER_REQUEST = 'ADD_USER_REQUEST'
, SAVE_PRENATAL_REQUEST = 'SAVE_PRENATAL_REQUEST'
, CHECK_IN_OUT_REQUEST = 'CHECK_IN_OUT_REQUEST'
, DATA_SELECT = 'SELECT' // SELECT event in the data namespace.
, DATA_SELECT_RESPONSE = 'SELECT_RESPONSE' // SELECT_RESPONSE event in the data namespace.
//
// Elm Client stuff - corresponds with comm.js on the client.
//
, ADD_CHG_DELETE = 'ADD_CHG_DELETE' // data notification of a change by another client.
, ADD = 'ADD' // data add request.
, ADD_RESPONSE = 'ADD_RESPONSE' // data add response.
, CHG = 'CHG' // data change request.
, CHG_RESPONSE = 'CHG_RESPONSE' // data change response.
, DEL = 'DEL' // data delete request.
, DEL_RESPONSE = 'DEL_RESPONSE' // data delete response.
, ADHOC = 'ADHOC' // data adhoc request.
, ADHOC_RESPONSE = 'ADHOC_RESPONSE' // data adhoc response.
, ADHOC_LOGIN = 'ADHOC_LOGIN' // adhocType from the client.
, ADHOC_USER_PROFILE = 'ADHOC_USER_PROFILE' // AdhocType from the client.
, ADHOC_USER_PROFILE_UPDATE = 'ADHOC_USER_PROFILE_UPDATE'
, ADHOC_TOUCH_SESSION = 'ADHOC_TOUCH_SESSION' // Used by the Elm medical client
, ADHOC_CLIENT_CONSOLE = 'ADHOC_CLIENT_CONSOLE' // Used by the Elm medical client
, ADHOC_SYSTEM_MODE = 'ADHOC_SYSTEM_MODE' // Elm admin client to change system mode
, TABLE_babyMedication = 'babyMedication'
, TABLE_babyVaccination = 'babyVaccination'
, TABLE_motherMedication = 'motherMedication'
, TABLE_birthCertificate = 'birthCertificate'
, TABLE_babyLab = 'babyLab'
, TABLE_contPostpartumCheck = 'contPostpartumCheck'
, TABLE_postpartumCheck = 'postpartumCheck'
, TABLE_discharge = 'discharge'
, TABLE_keyValue = 'keyValue'
, TABLE_labSuite = 'labSuite'
, TABLE_labTest = 'labTest'
, TABLE_labTestValue = 'labTestValue'
, TABLE_medicationType = 'medicationType'
, TABLE_membrane = 'membrane'
, TABLE_newbornExam = 'newbornExam'
, TABLE_selectData = 'selectData'
, TABLE_vaccinationType = 'vaccinationType'
, TABLE_user = 'user'
, TABLE_labor = 'labor'
, TABLE_laborStage1 = 'laborStage1'
, TABLE_laborStage2 = 'laborStage2'
, TABLE_laborStage3 = 'laborStage3'
, TABLE_apgar = 'apgar'
, TABLE_baby = 'baby'
, updateKeyValue = require('./routes/comm/lookupTables').updateKeyValue
, addBaby = require('./routes/comm/labor').addBaby
, updateBaby = require('./routes/comm/labor').updateBaby
, delBaby = require('./routes/comm/labor').delBaby
, addBabyLab = require('./routes/comm/labor').addBabyLab
, updateBabyLab = require('./routes/comm/labor').updateBabyLab
, delBabyLab = require('./routes/comm/labor').delBabyLab
, addBabyMedication = require('./routes/comm/labor').addBabyMedication
, updateBabyMedication = require('./routes/comm/labor').updateBabyMedication
, delBabyMedication = require('./routes/comm/labor').delBabyMedication
, addBabyVaccination = require('./routes/comm/labor').addBabyVaccination
, updateBabyVaccination = require('./routes/comm/labor').updateBabyVaccination
, delBabyVaccination = require('./routes/comm/labor').delBabyVaccination
, addBirthCertificate = require('./routes/comm/labor').addBirthCertificate
, updateBirthCertificate = require('./routes/comm/labor').updateBirthCertificate
, delBirthCertificate = require('./routes/comm/labor').delBirthCertificate
, addMotherMedication = require('./routes/comm/labor').addMotherMedication
, updateMotherMedication = require('./routes/comm/labor').updateMotherMedication
, delMotherMedication = require('./routes/comm/labor').delMotherMedication
, addContPostpartumCheck = require('./routes/comm/labor').addContPostpartumCheck
, updateContPostpartumCheck = require('./routes/comm/labor').updateContPostpartumCheck
, delContPostpartumCheck = require('./routes/comm/labor').delContPostpartumCheck
, addDischarge = require('./routes/comm/labor').addDischarge
, updateDischarge = require('./routes/comm/labor').updateDischarge
, delDischarge = require('./routes/comm/labor').delDischarge
, addLabor = require('./routes/comm/labor').addLabor
, delLabor = require('./routes/comm/labor').delLabor
, updateLabor = require('./routes/comm/labor').updateLabor
, addLaborStage1 = require('./routes/comm/labor').addLaborStage1
, delLaborStage1 = require('./routes/comm/labor').delLaborStage1
, updateLaborStage1 = require('./routes/comm/labor').updateLaborStage1
, addLaborStage2 = require('./routes/comm/labor').addLaborStage2
, delLaborStage2 = require('./routes/comm/labor').delLaborStage2
, updateLaborStage2 = require('./routes/comm/labor').updateLaborStage2
, addLaborStage3 = require('./routes/comm/labor').addLaborStage3
, delLaborStage3 = require('./routes/comm/labor').delLaborStage3
, updateLaborStage3 = require('./routes/comm/labor').updateLaborStage3
, addLabSuite = require('./routes/comm/lookupTables').addLabSuite
, delLabSuite = require('./routes/comm/lookupTables').delLabSuite
, updateLabSuite = require('./routes/comm/lookupTables').updateLabSuite
, addLabTest = require('./routes/comm/lookupTables').addLabTest
, delLabTest = require('./routes/comm/lookupTables').delLabTest
, updateLabTest = require('./routes/comm/lookupTables').updateLabTest
, addLabTestValue = require('./routes/comm/lookupTables').addLabTestValue
, delLabTestValue = require('./routes/comm/lookupTables').delLabTestValue
, updateLabTestValue = require('./routes/comm/lookupTables').updateLabTestValue
, addMedicationType = require('./routes/comm/lookupTables').addMedicationType
, delMedicationType = require('./routes/comm/lookupTables').delMedicationType
, updateMedicationType = require('./routes/comm/lookupTables').updateMedicationType
, addMembrane = require('./routes/comm/labor').addMembrane
, updateMembrane = require('./routes/comm/labor').updateMembrane
, delMembrane = require('./routes/comm/labor').delMembrane
, addNewbornExam = require('./routes/comm/labor').addNewbornExam
, updateNewbornExam = require('./routes/comm/labor').updateNewbornExam
, delNewbornExam = require('./routes/comm/labor').delNewbornExam
, addPostpartumCheck = require('./routes/comm/labor').addPostpartumCheck
, updatePostpartumCheck = require('./routes/comm/labor').updatePostpartumCheck
, delPostpartumCheck = require('./routes/comm/labor').delPostpartumCheck
, addSelectData = require('./routes/comm/lookupTables').addSelectData
, delSelectData = require('./routes/comm/lookupTables').delSelectData
, updateSelectData = require('./routes/comm/lookupTables').updateSelectData
, addVaccinationType = require('./routes/comm/lookupTables').addVaccinationType
, delVaccinationType = require('./routes/comm/lookupTables').delVaccinationType
, updateVaccinationType = require('./routes/comm/lookupTables').updateVaccinationType
, addUser = require('./routes/comm/userRoles').addUser
, delUser = require('./routes/comm/userRoles').delUser
, updateUser = require('./routes/comm/userRoles').updateUser
, updateUserProfile = require('./routes/comm/userRoles').updateUserProfile
, getUserProfile = require('./routes/comm/userRoles').getUserProfile
, returnLogin = require('./util').returnLogin
, returnUserProfile = require('./util').returnUserProfile
, returnUserProfileUpdate = require('./util').returnUserProfileUpdate
, returnStatusADD = require('./util').returnStatusADD
, returnStatusADD2 = require('./util').returnStatusADD2
, returnStatusCHG2 = require('./util').returnStatusCHG2
, returnStatusCHG = require('./util').returnStatusCHG
, returnStatusDEL = require('./util').returnStatusDEL
, returnStatusDEL2 = require('./util').returnStatusDEL2
, returnStatusSELECT = require('./util').returnStatusSELECT
, LoginFailErrorCode = require('./util').LoginFailErrorCode
, LoginSuccessErrorCode = require('./util').LoginSuccessErrorCode
, LoginSuccessDifferentUserErrorCode = require('./util').LoginSuccessDifferentUserErrorCode
, UserProfileSuccessErrorCode = require('./util').UserProfileSuccessErrorCode
, UserProfileFailErrorCode = require('./util').UserProfileFailErrorCode
, UserProfileUpdateSuccessErrorCode = require('./util').UserProfileUpdateSuccessErrorCode
, UserProfileUpdateFailErrorCode = require('./util').UserProfileUpdateFailErrorCode
, NoErrorCode = require('./util').NoErrorCode
, SessionExpiredErrorCode = require('./util').SessionExpiredErrorCode
, SqlErrorCode = require('./util').SqlErrorCode
, UnknownTableErrorCode = require('./util').UnknownTableErrorCode
, UnknownErrorCode = require('./util').UnknownErrorCode
, getProcessId = require('./util').getProcessId
, assertModule = require('./comm_assert')
, DO_ASSERT = process.env.NODE_ENV? process.env.NODE_ENV === 'development': false
, KEY_VALUE_UPDATE = require('./constants').KEY_VALUE_UPDATE
, SYSTEM_MODE_CHANGE = require('./constants').SYSTEM_MODE_CHANGE
, systemMode = 0 // default until changed
, SYSTEM_MODE_KEY = 'SystemMode'
, SYSTEM_MODE_FILE = 'SystemMode.dat'
;
/* --------------------------------------------------------
* getIsInitialized()
*
* Returns a function that tells the caller if the comm
* module is initialized yet.
* -------------------------------------------------------- */
function getIsInitialized() {return isInitialized;}
// ========================================================
// ========================================================
// Logging functions.
// ========================================================
// ========================================================
/* --------------------------------------------------------
* getFormattedLogMsg()
*
* Returns the message passed in the format expected by
* the logs.
*
* param msg
* return message
* -------------------------------------------------------- */
var getFormattedLogMsg = function(msg) {
var id = process.env.WORKER_ID? process.env.WORKER_ID: 0
, theDate = moment().format('YYYY-MM-DD HH:mm:ss.SSS')
, message = id + '|' + theDate + ': ' + msg
;
return message;
};
/* --------------------------------------------------------
* writeLog()
*
* Writes a log message to the console.
*
* NOTE: WE DO NOT USE THESE FUNCTIONS FROM util.js BECAUSE
* OF CIRCULAR REFERENCES AND BECAUSE THE FUNCTIONS IN util.js
* USE sendSystem() TO DISTRIBUTE MESSAGES TO THE administrators
* AND LOGGING MESSAGES FROM THE comm LIBRARY DO NOT ALWAYS
* NEED THIS.
*
* param msg
* param logType
* return message
* -------------------------------------------------------- */
var INFO = 1
, WARN = 2
, ERROR = 3
;
var writeLog = function(msg, logType) {
var fn = 'info'
, message = getFormattedLogMsg(msg)
;
if (logType === WARN || logType === ERROR) fn = 'error';
console[fn](message);
return message;
};
/* --------------------------------------------------------
* logCommInfo()
*
* Writes an informative message to the console.
*
* NOTE: WE DO NOT USE THESE FUNCTIONS FROM util.js BECAUSE
* OF CIRCULAR REFERENCES AND BECAUSE THE FUNCTIONS IN util.js
* USE sendSystem() TO DISTRIBUTE MESSAGES TO THE administrators
* AND LOGGING MESSAGES FROM THE comm LIBRARY DO NOT ALWAYS
* NEED THIS.
*
* param msg
* param doSysMsg - boolean whether to write to socket SYSTEM_LOG
* return undefined
* -------------------------------------------------------- */
var logCommInfo = function(msg, doSysMsg) {
var message = writeLog(msg, INFO);
if (doSysMsg) sendSystem(SYSTEM_LOG, message);
};
/* --------------------------------------------------------
* logCommWarn()
*
* Writes a warning message to the console.
*
* NOTE: WE DO NOT USE THESE FUNCTIONS FROM util.js BECAUSE
* OF CIRCULAR REFERENCES AND BECAUSE THE FUNCTIONS IN util.js
* USE sendSystem() TO DISTRIBUTE MESSAGES TO THE administrators
* AND LOGGING MESSAGES FROM THE comm LIBRARY DO NOT ALWAYS
* NEED THIS.
*
* param msg
* param doSysMsg - boolean whether to write to socket SYSTEM_LOG
* return undefined
* -------------------------------------------------------- */
var logCommWarn = function(msg, doSysMsg) {
var message = writeLog(msg, WARN);
if (doSysMsg) sendSystem(SYSTEM_LOG, message);
};
/* --------------------------------------------------------
* logCommError()
*
* Writes an error message to the console.
*
* NOTE: WE DO NOT USE THESE FUNCTIONS FROM util.js BECAUSE
* OF CIRCULAR REFERENCES AND BECAUSE THE FUNCTIONS IN util.js
* USE sendSystem() TO DISTRIBUTE MESSAGES TO THE administrators
* AND LOGGING MESSAGES FROM THE comm LIBRARY DO NOT ALWAYS
* NEED THIS.
*
* param msg
* param doSysMsg - boolean whether to write to socket SYSTEM_LOG
* return undefined
* -------------------------------------------------------- */
var logCommError = function(msg, doSysMsg) {
var message = writeLog(msg, ERROR);
if (doSysMsg) sendSystem(SYSTEM_LOG, message);
};
// ========================================================
// ========================================================
// Message handling functions.
// ========================================================
// ========================================================
/* --------------------------------------------------------
* wrap()
*
* Wrap data in a message wrapper per the message namespace. The
* message id, namespace, updatedAt, workerID, and processedBy
* fields are automatically set. This is only done when new
* data is sent into the stream.
*
* The workerId field contains the id of the process that
* initiated the message.
*
* The processedBy field contains the ids of the processes
* that have received the message via IPC or, as is the
* case here, when the message was created. This is used to
* prevent messages from bouncing between processes without
* end.
*
* param namespace
* param data
* param scope - optional, for system messages only
* return message object
* -------------------------------------------------------- */
var wrap = function(namespace, data, scope) {
return {
msgId: uuid.v1()
, namespace: namespace
, updatedAt: Date.now()
, workerId: process.env.WORKER_ID
, processedBy: [process.env.WORKER_ID]
, scope: namespace == CONST.TYPE.SITE? undefined:
namespace == CONST.TYPE.DATA? undefined:
namespace == CONST.TYPE.SYSTEM? scope: undefined
, data: data? data: {}
};
};
// Initialize siteSubjectData with wrapper and the process startTime.
siteSubjectData = wrap(CONST.TYPE.SITE, {processStartTime: Date.now()});
/* --------------------------------------------------------
* makeSend()
*
* Create a function that handles sending a certain namespace
* of message.
*
* param namespace - namespace: SITE, SYSTEM, or DATA
* return function
* -------------------------------------------------------- */
function makeSend(namespace) {
return function(key, val, scope) {
var data = {};
var wrapped;
switch (namespace) {
case CONST.TYPE.SITE:
// --------------------------------------------------------
// For site messages, the most recent copy is stored so
// update the data portion with the key/val pair, refresh
// the wrapper and notify subscribers. Return the unique
// message id to the caller.
// --------------------------------------------------------
data[key] = val;
siteSubjectData = wrap(namespace, _.extendOwn(siteSubjectData.data, data));
siteSubject.onNext(siteSubjectData);
return siteSubjectData.msgId;
case CONST.TYPE.SYSTEM:
// --------------------------------------------------------
// For system messages, there is no aggregation and there
// is an optional scope parameter allowed.
// --------------------------------------------------------
data[key] = val;
wrapped = wrap(namespace, data, scope);
if (isInitialized) systemSubject.onNext(wrapped);
break;
default:
logCommError('Error: makeSend() unimplemented for this namespace: ' + namespace);
}
};
};
/* --------------------------------------------------------
* sendSite()
* sendSystem()
*
* Send a message of a certain namespace.
*
* param key - the key of the key/val pair
* param val - the value of the key/val pair
* param scope - the scope of the message (system only)
* return msgId - the unique message id
* -------------------------------------------------------- */
var sendSite = makeSend(CONST.TYPE.SITE);
var sendSystem = makeSend(CONST.TYPE.SYSTEM);
// Note: sendData() has been refactored into commUtils.js.
//var sendData = makeSend(CONST.TYPE.DATA);
/* --------------------------------------------------------
* wrapByType()
*
* Used for sending messages out to the client.
*
* Wrap a message with a outer object with a field named
* namespace that specifies the course level type of message
* this is, which is one of 'SYSTEM', 'SITE', or 'DATA'.
* Another field named msgType specifies at a more granular
* level the type of message. The field named payload contains
* the data passed.
*
* Return a stringifed object to the caller.
*
* param namespace
* param msgType
* param data
* return stringifed object
* -------------------------------------------------------- */
var wrapByType = function(namespace, msgType, data) {
// We do not allow fields used solely for routing between the
// process and RxJS systems to go to the client.
// Also, namespace is already specified one level up so
// no need to repeat it if it exists.
var payload = _.omit(data, ['namespace', 'msgId', 'workerId', 'processedBy', 'scope']);
// Temporary sanity checks.
if (! msgType) {
console.log('===== wrapByType() discrepancy ======');
console.log('msgType field not passed.');
console.log('namespace: ' + namespace);
console.log(data);
console.log('===== end wrapByType() =====');
} else if (! data) {
console.log('===== wrapByType() discrepancy ======');
console.log('data field not passed.');
console.log('namespace: ' + namespace + ', msgType: ' + msgType);
console.log('===== end wrapByType() =====');
} else if (data.type) {
console.log('===== wrapByType() discrepancy ======');
console.log('data.type field passed.');
console.log('namespace: ' + namespace + ', msgType: ' + msgType);
console.log('===== end wrapByType() =====');
} else if ((data.msgType && data.msgType !== msgType) || data.msgType) {
console.log('----- wrapByType() inner msgType -----');
console.log('data.msgType found and/or does not equal msgType.');
console.log('namespace: ' + namespace + ', msgType: ' + msgType);
if (msgType === CONST.TYPE.SYSTEM) console.log(data);
console.log('----- end wrapByType() -----');
}
var retVal = JSON.stringify({namespace: namespace, msgType: msgType, payload: payload});
//console.log(getProcessId() + ': ' + retVal);
return retVal;
};
var wrapSystem = function(msgType, data) { return wrapByType('SYSTEM', msgType, data); };
var wrapSite = function(msgType, data) { return wrapByType('SITE', msgType, data); };
var wrapData = function(msgType, data) { return wrapByType('DATA', msgType, data); };
/* --------------------------------------------------------
* subscribeSite()
*
* Allows other modules to subscribe to site namespace messages.
*
* param onNext - function to call upon msg
* param onError - function to call upon error
* param onCompleted - function to call when done
* return subscription object
* -------------------------------------------------------- */
var subscribeSite = function(onNext, onError, onCompleted) {
return siteSubject.subscribe(onNext, onError, onCompleted);
};
/* --------------------------------------------------------
* subscribeSystem()
*
* Allows other modules to subscribe to system namespace messages.
*
* param onNext - function to call upon msg
* param onError - function to call upon error
* param onCompleted - function to call when done
* return subscription object
* -------------------------------------------------------- */
var subscribeSystem = function(onNext, onError, onCompleted) {
return systemSubject.subscribe(onNext, onError, onCompleted);
};
/* --------------------------------------------------------
* subscribeData()
*
* Allows other modules to subscribe to data namespace messages.
*
* param onNext - function to call upon msg
* param onError - function to call upon error
* param onCompleted - function to call when done
* return subscription object
* -------------------------------------------------------- */
var subscribeData = function(onNext, onError, onCompleted) {
return dataSubject.subscribe(onNext, onError, onCompleted);
};
// ========================================================
// ========================================================
// Utils for session validity, logins, and profiles.
// ========================================================
// ========================================================
/* --------------------------------------------------------
* isValidSocketSession()
*
* Determine if the socket has a valid session and return
* the boolean answer.
*
* param socket
* return boolean
* -------------------------------------------------------- */
var isValidSocketSession = function(socket) {
if (DO_ASSERT) assertModule.isValidSocketSession(socket);
var notExpired = false;
var isValid = socket &&
socket.request &&
socket.request.session &&
socket.request.session.roleInfo &&
socket.request.session.roleInfo.isAuthenticated? true: false;
if (isValid && socket.request.session.cookie._expires) {
notExpired = moment().isBefore(moment(socket.request.session.cookie._expires, moment.ISO_8601));
}
return !! (isValid && notExpired);
};
/* --------------------------------------------------------
* touchSocketSession()
*
* Touch the session within the socket passed in order to
* extend the expiry timeout accordingly. We call save()
* with a do nothing function in order to have the expires
* field in the sessions table in the database updated as well.
*
* param socket
* return undefined
* -------------------------------------------------------- */
var touchSocketSession = function(socket) {
if (DO_ASSERT) assertModule.touchSocketSession(socket);
socket.request.session.touch();
socket.request.session.save(function() {});
};
/* --------------------------------------------------------
* getSocketSessionId()
*
* Return the socket session id if the session is valid and
* has one, otherwise returns an empty string.
*
* param socket
* return string
* -------------------------------------------------------- */
var getSocketSessionId = function(socket) {
if (! isValidSocketSession(socket)) return '';
return socket.request.sessionID? socket.request.sessionID: '';
};
/* --------------------------------------------------------
* setSystemMode()
*
* Simply sets a new value in SystemMode.dat. Does not reply
* to the caller. Does not inform the module or any other
* module about the change. Allows normal processes to detect
* change in due time.
*
* param payload
* param socker
* return undefined
* -------------------------------------------------------- */
var setSystemMode = function(payload, socket) {
var newSysMode;
if (_.has(payload, 'SystemMode') && _.isNumber(payload.SystemMode)) {
newSysMode = payload.SystemMode;
if (newSysMode !== systemMode) {
fs.writeFileSync(SYSTEM_MODE_FILE, "" + newSysMode, {encoding: 'utf8'});
}
}
};
/* --------------------------------------------------------
* loginUser()
*
* Find the user by username. If there is no user with the
* given username, or the password is not correct, set the
* user to 'false' in order to indicate failure. Otherwise,
* return the authenticated user.
*
* param username
* param password
* param cb
* return undefined
* -------------------------------------------------------- */
var loginUser = function(username, password, cb) {
User.findByUsername(username, function(err, user) {
if (!user) { return cb(null, false, { message: 'Unknown user ' + username }); }
if (user.get('status') != 1) {
return cb(null, false, {
message: username + ' is not an active account.'
});
}
user.checkPassword(password, function(err, same) {
if (err) return cb(err);
if (same) {
return cb(null, user);
} else {
return cb(null, false, {message: 'Invalid password'});
}
});
});
};
var handleLogin = function(json, socket) {
if (DO_ASSERT) assertModule.handleLogin(json, socket);
var username = json.data && json.data.username ? json.data.username: void 0;
var password = json.data && json.data.password ? json.data.password: void 0;
var isDifferentUser = false;
var retAction;
var msg;
if (! username || ! password ) {
msg = 'Username and/or password not supplied.';
retAction = returnLogin(false, LoginFailErrorCode, msg);
return socket.send(wrapData(ADHOC_RESPONSE, retAction));
}
// Check if this is the same user as is possibly in the session now.
if (socket.request.session &&
socket.request.session.user &&
socket.request.session.user.username &&
socket.request.session.user.username !== username) {
isDifferentUser = true;
}
// Login the user.
loginUser(username, password, function(err, user, msgObj) {
if (err) {
// Unknown failure, not just a failed login.
console.log(err);
retAction = returnLogin(false, LoginFailErrorCode, err);
return socket.send(wrapData(ADHOC_RESPONSE, retAction));
}
if (user) {
if (isDifferentUser) {
sendUserProfile(socket, user.toJSON(), LoginSuccessDifferentUserErrorCode);
} else {
sendUserProfile(socket, user.toJSON(), LoginSuccessErrorCode);
}
} else {
// Failed login.
console.log(msgObj);
retAction = returnLogin(false, LoginFailErrorCode, msgObj.message);
return socket.send(wrapData(ADHOC_RESPONSE, retAction));
}
});
};
var handleUserProfile = function(socket, data, userInfo) {
if (DO_ASSERT) assertModule.handleUserProfile(socket, data, userInfo);
var retAction;
var errCode;
if (isValidSocketSession(socket)) {
if (socket.request.session.user) {
if (data && userInfo) {
// User is updating (hopefully) their own profile. updateUserProfile()
// will sanity check that they are only updating their own profile.
updateUserProfile(data, userInfo, function(err, success, id) {
if (err) {
console.log(err);
retAction = returnUserProfileUpdate(false, UserProfileUpdateFailErrorCode);
return socket.send(wrapData(ADHOC_RESPONSE, retAction));
}
errCode = UserProfileUpdateFailErrorCode;
if (success) errCode = UserProfileUpdateSuccessErrorCode;
retAction = returnUserProfileUpdate(!!success, errCode);
socket.send(wrapData(ADHOC_RESPONSE, retAction));
// --------------------------------------------------------
// Write out to the log and SYSTEM_LOG for administrators.
// --------------------------------------------------------
return logCommInfo(userInfo.user.username + ": updated user profile", true);
});
} else {
// Get the user profile information.
getUserProfile(socket.request.session.user.id, function(err, success, userObj) {
if (err || ! success) {
console.log(err);
return sendUserProfile(socket, userObj, UserProfileFailErrorCode);
} else {
return sendUserProfile(socket, userObj, UserProfileSuccessErrorCode);
}
});
}
} else {
// Do not have the user in session, so fail.
sendUserProfile(socket, void 0, UserProfileFailErrorCode);
}
} else {
// Session has expired, so fail.
sendUserProfile(socket, void 0, UserProfileFailErrorCode);
}
};
/* --------------------------------------------------------
* sendUserProfile()
*
* Updates the session with user information, resets the
* session expiry, and sends the user profile to the client.
*
* param socket
* param user - assumes is a simple JSON object.
* param errCode - error code to return to client.
* return undefined
* -------------------------------------------------------- */
var sendUserProfile = function(socket, user, errCode) {
if (DO_ASSERT) assertModule.sendUserProfile(socket, user, errCode);
var retAction;
// Reset session timeout.
touchSocketSession(socket);
// Save user information into the session and return response to client.
if (user) {
socket.request.session.roleInfo = {
isAuthenticated: errCode === LoginSuccessErrorCode ||
errCode === UserProfileSuccessErrorCode ||
errCode === LoginSuccessDifferentUserErrorCode? true: false,
roleName: user.roleName? user.roleName: user.role && user.role.name? user.role.name: ''
};
socket.request.session.save(function(err) {
if (err) {
console.log('ERROR: login successful but unable to save to session.');
console.log(err);
}
switch (errCode) {
case LoginSuccessErrorCode:
retAction = returnLogin(true, errCode);
retAction.isLoggedIn = true;
break;
case LoginSuccessDifferentUserErrorCode:
retAction = returnLogin(true, errCode);
retAction.isLoggedIn = true;
break;
case LoginFailErrorCode:
retAction = returnLogin(false, errCode);
break;
case UserProfileSuccessErrorCode:
retAction = returnUserProfile(true, errCode);
retAction.isLoggedIn = true;
break;
case UserProfileFailErrorCode:
retAction = returnUserProfile(false, errCode);
break;
default:
throw new Error('Unknown errCode of ' + errCode + ' in comm/sendUserProfile().');
}
if (retAction && user) {
_.extendOwn(retAction, _.pick(user,
['id', 'userId', 'username', 'firstname', 'lastname', 'email',
'lang', 'shortName', 'displayName', 'role_id', 'roleName'])
);
// User Profile uses userId instead of id. Massage data into correct format.
if (! retAction.userId && user.id) {
retAction.userId = user.id;
if (retAction.id) delete retAction.id;
}
// Assumes roleName assigned to session earlier in this function.
if (! retAction.roleName) retAction.roleName = socket.request.session.roleInfo.roleName;
socket.send(wrapData(ADHOC_RESPONSE, retAction));
}
});
}
};
// ========================================================
// ========================================================
// High-level data processing functions.
// ========================================================
// ========================================================
/* --------------------------------------------------------
* getFuncForTableOp()
*
* Returns a function for a combination of table and operation
* that will be used for processing. This works for legacy
* messages and version 2 messages.
*
* param table
* param op
* return func
* -------------------------------------------------------- */
var getFuncForTableOp = function(table, op) {
var func = void 0;
switch (table) {
case TABLE_baby:
switch (op) {
case ADD: func = addBaby; break;
case CHG: func = updateBaby; break;
case DEL: func = delBaby; break;
}
break;
case TABLE_babyMedication:
switch (op) {
case ADD: func = addBabyMedication; break;
case CHG: func = updateBabyMedication; break;
case DEL: func = delBabyMedication; break;
}
break;
case TABLE_babyLab:
switch (op) {
case ADD: func = addBabyLab; break;
case CHG: func = updateBabyLab; break;
case DEL: func = delBabyLab; break;
}
break;
case TABLE_babyVaccination:
switch (op) {
case ADD: func = addBabyVaccination; break;
case CHG: func = updateBabyVaccination; break;
case DEL: func = delBabyVaccination; break;
}
break;
case TABLE_birthCertificate:
switch (op) {
case ADD: func = addBirthCertificate; break;
case CHG: func = updateBirthCertificate; break;
case DEL: func = delBirthCertificate; break;
}
break;
case TABLE_contPostpartumCheck:
switch (op) {
case ADD: func = addContPostpartumCheck; break;
case CHG: func = updateContPostpartumCheck; break;
case DEL: func = delContPostpartumCheck; break;
}
break;
case TABLE_discharge:
switch (op) {
case ADD: func = addDischarge; break;
case CHG: func = updateDischarge; break;
case DEL: func = delDischarge; break;
}
break;
case TABLE_keyValue:
switch (op) {
// keyValue table can only be updated.
case CHG: func = updateKeyValue; break;
}
break;
case TABLE_labor:
switch (op) {
case ADD: func = addLabor; break;
case CHG: func = updateLabor; break;
case DEL: func = delLabor; break;
}
break;
case TABLE_laborStage1:
switch (op) {
case ADD: func = addLaborStage1; break;
case CHG: func = updateLaborStage1; break;
case DEL: func = delLaborStage1; break;
}
break;
case TABLE_laborStage2:
switch (op) {
case ADD: func = addLaborStage2; break;
case CHG: func = updateLaborStage2; break;
case DEL: func = delLaborStage2; break;
}
break;
case TABLE_laborStage3:
switch (op) {
case ADD: func = addLaborStage3; break;
case CHG: func = updateLaborStage3; break;
case DEL: func = delLaborStage3; break;
}
break;
case TABLE_labSuite:
switch (op) {
case ADD: func = addLabSuite; break;
case CHG: func = updateLabSuite; break;
case DEL: func = delLabSuite; break;
}
break;
case TABLE_labTest:
switch (op) {
case ADD: func = addLabTest; break;
case CHG: func = updateLabTest; break;
case DEL: func = delLabTest; break;
}
break;
case TABLE_labTestValue:
switch (op) {
case ADD: func = addLabTestValue; break;
case CHG: func = updateLabTestValue; break;
case DEL: func = delLabTestValue; break;
}
break;
case TABLE_medicationType:
switch (op) {
case ADD: func = addMedicationType; break;
case CHG: func = updateMedicationType; break;
case DEL: func = delMedicationType; break;