-
Notifications
You must be signed in to change notification settings - Fork 1
/
adfice.js
1910 lines (1752 loc) · 63.3 KB
/
adfice.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
// SPDX-License-Identifier: GPL-3.0-or-later
// Copyright (C) 2021-2024 Stichting Open Electronics Lab
// vim: set sts=4 shiftwidth=4 expandtab :
"use strict";
const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const autil = require('./adfice-util');
const ae = require('./adfice-evaluator');
const cp = require('./calculate-prediction');
const adb = require('./adfice-db');
const crypto = require('crypto');
async function db_init() {
if (!this.db) {
this.db = await adb.init();
}
return this.db;
}
async function shutdown() {
try {
/* istanbul ignore else */
if (this.db) {
await this.db.close();
}
} finally {
this.db = null;
}
}
function question_marks(num) {
return '?,'.repeat(num - 1) + '?';
}
async function sql_select(sql, params) {
let db = await this.db_init();
return await db.sql_query(sql, params);
}
function split_advice_texts_cdss_ehr_patient(advice_texts) {
for (let j = 0; j < advice_texts.length; ++j) {
let row = advice_texts[j];
row.an_fyi = 'Flat fields "cdss", "ehr", "patient" are for debugging';
row.cdss_split = autil.split_freetext(row.cdss);
/* delete row.cdss; TODO: switch patient-validation to cdss_split */
row.ehr_split = autil.split_freetext(row.ehr);
/* delete row.ehr */
row.patient_split = autil.split_freetext(row.patient);
/* delete row.patient */
}
return advice_texts;
}
async function get_table_sizes() {
let db = await this.db_init();
let params = [await db.schema_name()];
let sql = `/* adfice.get_table_sizes */
SELECT table_name
, table_rows
, ROUND((data_length + index_length)/POWER(1024,2),1) AS size_mb
, (data_length + index_length) AS size_bytes
FROM information_schema.tables
WHERE table_schema=?
ORDER BY size_bytes DESC`;
return await this.sql_select(sql, params);
}
async function write_patient_from_json(etl_patient) {
let db = await this.db_init();
let patient_id = crypto.randomBytes(16).toString('hex');
let list_of_transactions = [];
list_of_transactions.push(...(patientListOfInserts(patient_id, etl_patient)));
list_of_transactions.push(...(medListOfInserts(patient_id, etl_patient.medications)));
list_of_transactions.push(...(probListOfInserts(patient_id, etl_patient.problems)));
list_of_transactions.push(...(labListOfInserts(patient_id, etl_patient.labs)));
list_of_transactions.push(...(measListOfInserts(patient_id, etl_patient.measurements)));
let result = await this.db.as_sql_transaction(list_of_transactions);
let meds = await this.get_meds(patient_id);
let meas_update = measListOfUpdatesMeds(patient_id, meds);
let update_result = await this.db.as_sql_transaction(meas_update);
return patient_id;
}
async function renew_patient(patient_id, etl_patient) {
let params = [patient_id];
let list_of_transactions = [];
list_of_transactions.push(...(patientListOfUpdates(patient_id, etl_patient)));
let sql = "DELETE FROM patient_medication where patient_id = ?"
list_of_transactions.push([sql, params]);
list_of_transactions.push(...(medListOfInserts(patient_id, etl_patient.medications)));
sql = "DELETE FROM patient_problem where patient_id = ?"
list_of_transactions.push([sql, params]);
list_of_transactions.push(...(probListOfInserts(patient_id, etl_patient.problems)));
sql = "DELETE FROM patient_lab where patient_id = ?"
list_of_transactions.push([sql, params]);
list_of_transactions.push(...(labListOfInserts(patient_id, etl_patient.labs)));
sql = "DELETE FROM patient_measurement where patient_id = ?"
list_of_transactions.push([sql, params]);
list_of_transactions.push(...(measListOfInserts(patient_id, etl_patient.measurements)));
sql = "DELETE FROM patient_advice_selection where patient_id = ?"
list_of_transactions.push([sql, params]);
sql = "DELETE FROM patient_advice_freetext where patient_id = ?"
list_of_transactions.push([sql, params]);
await this.db.as_sql_transaction(list_of_transactions);
let meds = await this.get_meds(patient_id);
let meas_update = measListOfUpdatesMeds(patient_id, meds);
let update_result = await this.db.as_sql_transaction(meas_update);
return patient_id;
}
function patientListOfInserts(patient_id, patient) {
let list_of_transactions = [];
let age = calculateAge(patient);
let sql = "INSERT INTO etl_mrn_patient (patient_id, mrn, fhir, refresh_token) VALUES (?,?,?,?)";
list_of_transactions.push([sql, [patient_id, patient['mrn'], patient['ehr_pid'], patient['refresh_token']]]);
let sql1 = '/* adfice.patientListOfInserts */ INSERT INTO patient ' +
'(patient_id, participant_number, birth_date, age, is_final) ' +
'VALUES (?,?,?,?,0)';
let participant_number = patient['participant_number'];
if(participant_number){
participant_number = participant_number.trim();
}
list_of_transactions.push([sql1, [patient_id, participant_number, patient['birth_date'], age]]);
return list_of_transactions;
}
function patientListOfUpdates(patient_id, patient) {
let list_of_transactions = [];
let age = calculateAge(patient);
let sql1 = '/* adfice.patientListOfUpdates */ UPDATE patient ' +
'SET birth_date = ?, age = ?, is_final = 0 ' +
"WHERE patient_id = '" + patient_id + "'";
list_of_transactions.push([sql1, [patient['birth_date'], age]]);
return list_of_transactions;
}
function calculateAge(patient) {
if (patient['birth_date'] == null) {
return null;
}
let today = new Date();
let ageTokens = patient['birth_date'].split('-');
let year = ageTokens[0]
let month = ageTokens[1]
let day = ageTokens[2]
let age = today.getFullYear() - year;
/* istanbul ignore next */
if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) {
age--;
}
return age;
}
function nowString() {
return dateString(new Date());
}
function dateString(date_obj) {
/* istanbul ignore next */
if (date_obj == null) {
return null;
}
let date_str = date_obj.getFullYear() +
'-' + (date_obj.getMonth() + 1) +
'-' + date_obj.getDate() +
' ' + date_obj.getHours() +
":" + date_obj.getMinutes() +
":" + date_obj.getSeconds();
return date_str;
}
function medListOfInserts(patient_id, medications) {
let list_of_inserts = [];
if (!medications || medications.length < 1) {
return list_of_inserts;
}
for (let i = 0; i < medications.length; ++i) {
let medication = medications[i];
let sql = `/* adfice.medListOfInserts */
INSERT INTO patient_medication` +
' (patient_id, date_retrieved';
let values = ") VALUES (?,?";
let params = [patient_id, nowString()];
if (medication['display_name'] != null) {
sql += ", medication_name";
params.push(medication['display_name']);
values += ',?';
}
if (medication['generic_name'] != null) {
sql += ", generic_name";
params.push(medication['generic_name']);
values += ',?';
}
if (medication['ATC'] != null) {
sql += ", ATC_code";
params.push(medication['ATC'].trim());
values += ',?';
}
if (medication['start_date'] != null) {
let start_date = medication['start_date'].toString();
start_date = start_date.replace('T', ' ');
start_date = start_date.replace('Z', '');
sql += ", start_date";
params.push(start_date);
values += ',?';
}
if (medication['dose_text'] != null) {
sql += ", dose";
params.push(medication['dose_text']);
values += ',?';
}
sql = sql + values + ")";
if (params.length > 2) {
list_of_inserts.push([sql, params]);
}
}
return list_of_inserts;
}
function probListOfInserts(patient_id, problems) {
let list_of_inserts = [];
if (!problems || problems.length < 1) {
return list_of_inserts;
}
for (let i = 0; i < problems.length; ++i) {
let sql = `/* adfice.probListOfInserts */
INSERT INTO patient_problem` +
' (patient_id, date_retrieved, name, icd_10';
let values = ") VALUES (?,?,?,?";
let problem = problems[i];
let params = [patient_id, nowString(), problem['name'],
problem['icd_10']
];
if (problem['ehr_text'] != null &&
problem['ehr_text'] != '') {
sql += ", ehr_text";
params.push(problem['ehr_text']);
values += ',?';
}
if (problem['start_date'] != null) {
sql += ", start_date";
params.push(problem['start_date']);
values += ',?';
}
sql = sql + values + ")";
list_of_inserts.push([sql, params]);
}
return list_of_inserts;
}
function labListOfInserts(patient_id, labs) {
let list_of_inserts = [];
if (!labs || labs.length < 1) {
return list_of_inserts;
}
for (let i = 0; i < labs.length; ++i) {
let lab = labs[i];
let sql =
'/* adfice.labListOfInserts */ INSERT INTO patient_lab ' +
'(patient_id, date_retrieved, date_measured, lab_test_name, ' +
'lab_test_code, lab_test_result, lab_test_units) ' +
'VALUES (?,?,?,?,?,?,?)';
let params = [
patient_id,
nowString(),
lab['date_measured'],
lab['name'],
lab['lab_test_code'],
lab['lab_test_result'],
lab['lab_test_units']
];
list_of_inserts.push([sql, params]);
}
return list_of_inserts;
}
function measListOfInserts(patient_id, measurements) {
if (!measurements || Object.keys(measurements).length < 1) {
let sql = '/* adfice.measListOfInserts */ INSERT INTO patient_measurement ' +
'(patient_id, date_retrieved) VALUES (?,?)';
let params = [patient_id, nowString()]
return [
[sql, params]
];
}
let sql =
'/* adfice.measListOfInserts */ INSERT INTO patient_measurement ' +
'(patient_id, date_retrieved,systolic_bp_mmHg,bp_date_measured,' +
'height_cm,height_date_measured,weight_kg,weight_date_measured,' +
'smoking, smoking_date_measured,GDS_score,GDS_date_measured, ' +
'grip_kg, grip_date_measured,walking_speed_m_per_s,walking_date_measured, ' +
'fear0, fear1, fear2, fear_of_falls_date_measured, ' +
'number_of_limitations, functional_limit_date_measured, nr_falls_12m, nr_falls_date_measured) ' +
'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
let height_cm = measurements['height_cm'];
if (typeof height_cm === 'string' || height_cm instanceof String) {
height_cm = height_cm.replace(',', '.');
height_cm = parseFloat(height_cm);
/* istanbul ignore next */
if (isNaN(height_cm)) {
height_cm = measurements['height_cm'];
}
}
let weight_kg = measurements['weight_kg'];
if (typeof weight_kg === 'string' || weight_kg instanceof String) {
weight_kg = weight_kg.replace(',', '.');
weight_kg = parseFloat(weight_kg);
/* istanbul ignore next */
if (isNaN(weight_kg)) {
weight_kg = measurements['weight_kg'];
}
}
let grip_kg = measurements['grip_kg'];
if (typeof grip_kg === 'string' || grip_kg instanceof String) {
grip_kg = grip_kg.replace(',', '.');
grip_kg = parseFloat(grip_kg);
/* istanbul ignore next */
if (isNaN(grip_kg)) {
grip_kg = measurements['grip_kg'];
}
}
let walking_speed_m_per_s = measurements['walking_speed_m_per_s'];
if (typeof walking_speed_m_per_s === 'string' || walking_speed_m_per_s instanceof String) {
walking_speed_m_per_s = walking_speed_m_per_s.replace(',', '.');
walking_speed_m_per_s = parseFloat(walking_speed_m_per_s);
/* istanbul ignore next */
if (isNaN(walking_speed_m_per_s)) {
walking_speed_m_per_s = measurements['walking_speed_m_per_s'];
}
}
let params = [
patient_id,
nowString(),
measurements['systolic_bp_mmHg'],
measurements['bp_date_measured'],
height_cm,
measurements['height_date_measured'],
weight_kg,
measurements['weight_date_measured'],
measurements['smoking'],
measurements['smoking_date_measured'],
measurements['GDS_score'],
measurements['GDS_date_measured'],
grip_kg,
measurements['grip_date_measured'],
walking_speed_m_per_s,
measurements['walking_date_measured'],
measurements['fear0'],
measurements['fear1'],
measurements['fear2'],
measurements['fear_of_falls_date_measured'],
measurements['number_of_limitations'],
measurements['functional_limit_date_measured'],
measurements['nr_falls_12m'],
measurements['nr_falls_date_measured']
];
let list_of_inserts = [
[sql, params]
];
return list_of_inserts;
}
function measListOfUpdatesMeds(patient_id, meds) {
let prediction_meds = checkPredictionMeds(meds);
let list_of_transactions = [];
let sql = '/* adfice.measListOfUpdatesMeds */ UPDATE patient_measurement ' +
'SET has_antiepileptica = ?, has_ca_blocker = ?, has_incont_med = ? ' +
"WHERE patient_id = '" + patient_id + "'";
list_of_transactions.push([sql, [prediction_meds['has_antiepileptica'], prediction_meds['has_ca_blocker'], prediction_meds['has_incont_med']]]);
return list_of_transactions;
}
function checkPredictionMeds(meds) {
let has_antiepileptica = 0;
let has_ca_blocker = 0;
let has_incont_med = 0;
for (let i = 0; i < meds.length; ++i) {
if (meds[i]['ATC_code']) {
if (meds[i]['ATC_code'].startsWith('N03') &&
meds[i]['ATC_code'] != 'N03AX12' &&
meds[i]['ATC_code'] != 'N03AX16') {
has_antiepileptica = 1;
}
if (meds[i]['ATC_code'].startsWith('C08')) {
has_ca_blocker = 1;
}
if (meds[i]['ATC_code'].startsWith('G04BD') ||
meds[i]['ATC_code'] === 'G04CA53') {
has_incont_med = 1;
}
}
}
return {
'has_antiepileptica': has_antiepileptica,
'has_ca_blocker': has_ca_blocker,
'has_incont_med': has_incont_med
}
}
async function remove_med(atc_code, patient_id) {
var sql = `/* adfice.remove_med */
DELETE
FROM patient_medication
WHERE ATC_code = ? AND patient_id = ?;`;
var params = [atc_code, patient_id];
let deleted = await this.db.sql_query(sql, params);
// TODO should also check and update prediction model data
return deleted;
}
async function remove_lab(lab_test_name, patient_id) {
var sql = `/* adfice.remove_lab */
DELETE
FROM patient_lab
WHERE lab_test_name = ? AND patient_id = ?;`;
var params = [lab_test_name, patient_id];
let deleted = await this.db.sql_query(sql, params);
return deleted;
}
async function get_all_advice_texts_checkboxes() {
var sql = `/* adfice.get_all_advice_texts_checkboxes */
SELECT m.medication_criteria_id
, m.select_box_num
, m.select_box_category
, m.cdss
, m.ehr
, m.patient
, p.priority
FROM med_advice_text m
LEFT JOIN select_box_category_priority p
ON (m.select_box_category = p.select_box_category)
WHERE select_box_num IS NOT NULL
ORDER BY p.priority ASC, m.select_box_num ASC, m.id ASC`;
let advice_text = await this.sql_select(sql);
let list = split_advice_texts_cdss_ehr_patient(advice_text);
let all = {};
for (let i = 0; i < list.length; ++i) {
let row = list[i];
let rule_num = row.medication_criteria_id;
all[rule_num] = all[rule_num] || [];
all[rule_num].push(row);
}
return all;
}
// called from adfice-webserver-runner
async function get_advice_texts_checkboxes(rule_numbers, all) {
if ((rule_numbers == null) || (!rule_numbers.length)) {
return [];
}
if (!all) {
all = await this.get_all_advice_texts_checkboxes();
}
let narrowed = [];
for (let i = 0; i < rule_numbers.length; ++i) {
let rule_num = rule_numbers[i];
let subset = all[rule_num];
if (subset) {
Array.prototype.push.apply(narrowed, subset);
}
}
narrowed.sort((a, b) => {
return ((a.priority - b.priority) ||
(a.select_box_num - b.select_box_num) ||
(a.id - b.id));
});
return narrowed;
}
async function get_advice_other_texts_checkboxes() {
var sql = `/* adfice.get_advice_other_texts_checkboxes */
SELECT medication_criteria_id
, select_box_num
, select_box_category
, select_box_designator
, cdss
, ehr
, patient
FROM med_other_text
ORDER BY medication_criteria_id
, select_box_num`;
let advice_text = await this.sql_select(sql);
return split_advice_texts_cdss_ehr_patient(advice_text);
}
async function get_advice_texts_no_checkboxes(rule_numbers) {
if (rule_numbers == null || !rule_numbers.length) {
return [];
}
var sql = `/* adfice.get_advice_texts_no_checkboxes */
SELECT medication_criteria_id
, cdss
FROM med_advice_text
WHERE select_box_num IS NULL
AND medication_criteria_id IN(` +
question_marks(rule_numbers.length) +
`)
ORDER BY id`;
let advice_text = await this.sql_select(sql, rule_numbers);
return split_advice_texts_cdss_ehr_patient(advice_text);
}
async function get_advice_texts_non_med_checkboxes() {
var sql = `/* adfice.get_advice_texts_non_med_checkboxes */
SELECT t.category_id
, h.category_name
, t.select_box_num
, t.preselected
, t.cdss
, t.ehr
, t.patient
FROM nonmed_header AS h
JOIN nonmed_text AS t
ON (h.category_id = t.category_id)
ORDER BY t.category_id
, t.select_box_num
`;
let advice_text = await this.sql_select(sql);
return split_advice_texts_cdss_ehr_patient(advice_text);
}
async function get_reference_numbers(rule_numbers) {
if (rule_numbers == null || !rule_numbers.length) {
return [];
}
var sql = `/* adfice.get_reference_numbers */
SELECT reference
FROM med_rules
WHERE medication_criteria_id IN(` +
question_marks(rule_numbers.length) +
`)
GROUP BY reference
ORDER BY MIN(med_rules.id) ASC`;
return await this.sql_select(sql, rule_numbers);
}
async function get_active_rules() {
var sql = `/* adfice.get_active_rules */
SELECT *
FROM med_rules
WHERE active = 'yes'
ORDER BY id`;
let rules = await this.sql_select(sql);
return rules;
}
async function get_meds(patient_id) {
var sql = `/* adfice.get_meds */
SELECT ATC_code
, medication_name
, generic_name
, start_date
FROM patient_medication
WHERE patient_id=?
ORDER BY ATC_code`;
let params = [patient_id, patient_id];
let meds = await this.sql_select(sql, params);
return meds;
}
/* TODO refactor to make this set-based, rather than loop */
/* (the list is not long, we should read the whole table in to RAM) */
async function get_sql_condition(rule_number) {
var sql = `/* adfice.get_sql_condition */
SELECT sql_condition
FROM med_rules
WHERE medication_criteria_id=?
`;
let params = [rule_number];
let results = await this.sql_select(sql, params);
return results[0]['sql_condition'];
}
async function is_sql_condition_true(patient_id, rule_number) {
let result = await this.evaluate_sql_condition(patient_id, rule_number);
return result;
}
async function evaluate_sql_condition(patient_id, rule_number) {
var sql = await this.get_sql_condition(rule_number);
if (sql == null) {
return true;
} //no conditions === always true
/* count the number of question marks in the string */
return await this.evaluate_sql(sql, patient_id);
}
async function evaluate_sql(sql, patient_id) {
let count;
let matches = sql.match(/\?/g);
/* istanbul ignore else */
if (matches) {
count = matches.length;
} else {
count = 0;
}
let params = [];
for (let i = 0; i < count; ++i) {
params.push(patient_id);
}
let results = await this.sql_select(sql, params);
if (results.length == 0) {
return false;
}
autil.assert((results[0]['TRUE'] == 1), JSON.stringify({
patient_id: patient_id,
sql: sql,
results: results
}, null, 4));
return true;
}
async function get_preselect_rules(rule_number) {
var sql = `/* adfice.get_preselect_rules */
SELECT *
FROM preselect_rules
WHERE medication_criteria_id=?
`;
let results = await this.sql_select(sql, [rule_number]);
return results;
}
async function get_problems(patient_id) {
var sql = `/* adfice.get_problems */
SELECT name
, start_date
, display_name
FROM patient_problem
JOIN problem ON patient_problem.name = problem.problem_name
WHERE patient_id=?
ORDER BY patient_problem.id`;
let params = [patient_id, patient_id];
let probs = await this.sql_select(sql, params);
return probs;
}
async function get_patient_by_id(patient_id) {
var sql = `/* adfice.get_patient_by_id */
SELECT patient.*, etl_mrn_patient.mrn
FROM patient join etl_mrn_patient on patient.patient_id = etl_mrn_patient.patient_id
WHERE patient.patient_id=?`;
let params = [patient_id];
let results = await this.sql_select(sql, params);
let patient;
if (results.length > 0) {
patient = results[0];
} else {
patient = {};
}
return patient;
}
async function get_labs(patient_id) {
var sql = `/* adfice.get_labs */
SELECT lab_test_name
, lab_test_result
, date_measured
FROM patient_lab
WHERE patient_id=?
ORDER BY id`;
let params = [patient_id];
let result = await this.sql_select(sql, params);
return result;
}
async function get_patient_measurements(patient_id) {
var sql = `/* adfice.get_patient_measurements */
SELECT *
FROM patient_measurement
WHERE patient_id=?`
let params = [patient_id];
let results = await this.sql_select(sql, params);
if (results.length > 0) {
return results;
}
return null;
}
async function get_bsn(patient_id) {
var sql = `/* adfice.get_bsn */
SELECT bsn
FROM etl_bsn_patient
WHERE patient_id=?`
let params = [patient_id];
let results = await this.sql_select(sql, params);
if (results.length == 1) {
return results[0]['bsn'];
}
return null;
}
async function get_prediction_result(patient_id) {
let measurements = await this.get_patient_measurements(patient_id);
if (!measurements || !measurements.length) {
return null;
}
let measurement = measurements[0];
if (measurement.prediction_result == null) {
measurement = await this.calculate_store_prediction_result(patient_id);
}
return measurement.prediction_result;
}
async function update_prediction_result(row_id, prediction_result) {
let sql = `/* adfice.update_prediction_result */
UPDATE patient_measurement
SET prediction_result = ?
WHERE id = ?`;
let params = [prediction_result, row_id];
let results = await this.sql_select(sql, params);
}
async function calculate_store_prediction_result(patient_id) {
let measurement = await this.calculate_prediction_result(patient_id);
autil.assert(measurement);
await this.update_prediction_result(
measurement.id,
measurement.prediction_result);
let measurements = await this.get_patient_measurements(patient_id);
autil.assert(measurements);
autil.assert(measurements.length > 0);
return measurements[0];
}
async function calculate_prediction_result(patient_id) {
let measurements = await this.get_patient_measurements(patient_id);
if (measurements == null || !measurements.length) {
return null;
}
let measurement = measurements[0];
measurement = calculate_prediction_result_meas(measurement);
return measurement;
}
async function calculate_prediction_result_meas(measurement) {
//any value that can be = 0 cannot use the || syntax
let GDS_score = measurement['user_GDS_score'];
if (GDS_score == null) {
GDS_score = measurement['GDS_score'];
}
let grip_kg = measurement['user_grip_kg'] || measurement['grip_kg'];
let walking_speed_m_per_s = measurement['user_walking_speed_m_per_s'] ||
measurement['walking_speed_m_per_s'];
// prefer BMI from user-entered values, then from EHR, then from EHR height/weight
let BMI = null;
if (measurement['user_height_cm'] != null) {
if (measurement['user_weight_kg'] != null) {
BMI = measurement['user_weight_kg'] /
((measurement['user_height_cm'] / 100) * (measurement['user_height_cm'] / 100));
} else
/* istanbul ignore else */
if (measurement['weight_kg'] != null) {
BMI = measurement['weight_kg'] /
((measurement['user_height_cm'] / 100) * (measurement['user_height_cm'] / 100));
}
} else if (measurement['user_weight_kg'] != null) {
/* istanbul ignore else */
if (measurement['height_cm'] != null) {
BMI = measurement['user_weight_kg'] /
((measurement['height_cm'] / 100) * (measurement['height_cm'] / 100));
}
}
/* istanbul ignore else */
if (!BMI) {
BMI = measurement['BMI'];
} // else BMI stays at the value set previously
/* istanbul ignore else */
if (!BMI) {
/* istanbul ignore else */
if (measurement['height_cm'] != null &&
measurement['weight_kg'] != null) {
BMI = measurement['weight_kg'] /
((measurement['height_cm'] / 100) * (measurement['height_cm'] / 100));
} // else BMI stays null
} // else BMI stays at the value set previously
let systolic_bp_mmHg = measurement['user_systolic_bp_mmHg'] ||
measurement['systolic_bp_mmHg'];
let number_of_limitations = measurement['user_number_of_limitations'];
if (number_of_limitations == null) {
number_of_limitations = measurement['number_of_limitations'];
}
let nr_falls_12m = measurement['user_nr_falls_12m'];
if (nr_falls_12m == null) {
nr_falls_12m = measurement['nr_falls_12m'];
}
let smoking = measurement['user_smoking'];
if (smoking == null) {
smoking = measurement['smoking'];
}
let education_hml = measurement['user_education_hml'] ||
measurement['education_hml'];
let fear1 = 0;
let fear2 = 0;
if (measurement['user_fear0'] || measurement['user_fear1'] || measurement['user_fear2']) {
/* istanbul ignore else */
if (measurement['user_fear1'] == 1) {
fear1 = 1;
} // else do not change it
/* istanbul ignore else */
if (measurement['user_fear2'] == 1) {
fear2 = 1;
} // else do not change it
} else
/* istanbul ignore else */
if (measurement['fear0'] || measurement['fear1'] || measurement['fear2']) {
/* istanbul ignore else */
if (measurement['fear1'] == 1) {
fear1 = 1;
} // else do not change it
/* istanbul ignore else */
if (measurement['fear2'] == 1) {
fear2 = 1;
} // else do not change it
} // else do not change it
let has_antiepileptica = measurement['has_antiepileptica'] || 0;
let has_ca_blocker = measurement['has_ca_blocker'] || 0;
let has_incont_med = measurement['has_incont_med'] || 0;
let prediction = cp.calculate_prediction_db(
GDS_score,
grip_kg,
walking_speed_m_per_s,
BMI,
systolic_bp_mmHg,
number_of_limitations,
nr_falls_12m,
smoking,
has_antiepileptica,
has_ca_blocker,
has_incont_med,
education_hml,
fear1,
fear2);
measurement['prediction_result'] = prediction;
return measurement;
}
async function set_sql_selections(sqls_and_params, patient_id, doctor_id,
cb_states) {
let insert_sql = `/* adfice.set_advice_for_patient */
INSERT INTO patient_advice_selection
( patient_id
, doctor_id
, ATC_code
, medication_criteria_id
, select_box_num
, selected
)
VALUES (?,?,?,?,?,?)
ON DUPLICATE KEY
UPDATE doctor_id=VALUES(doctor_id)
, selected=VALUES(selected)
`;
let params = box_states_to_selection_states(patient_id, doctor_id,
cb_states);
for (let i = 0; i < params.length; ++i) {
sqls_and_params.push([insert_sql, params[i]]);
}
}
async function set_sql_freetexts(sqls_and_params, patient_id, doctor_id,
freetexts) {
let insert_sql = `/* adfice.set_advice_for_patient */
INSERT INTO patient_advice_freetext
( patient_id
, doctor_id
, ATC_code
, medication_criteria_id
, select_box_num
, freetext_num
, freetext
)
VALUES (?,?,?,?,?,?,?)
ON DUPLICATE KEY
UPDATE doctor_id=VALUES(doctor_id)
, freetext=VALUES(freetext)
`;
let params = freetexts_to_rows(patient_id, doctor_id, freetexts);
for (let i = 0; i < params.length; ++i) {
sqls_and_params.push([insert_sql, params[i]]);
}
}
// called from adfice-webserver-runner
async function set_advice_for_patient(patient_id, doctor,
cb_states, freetexts) {
const doctor_id = doctor;
let sqls_and_params = [];
if (cb_states) {
set_sql_selections(sqls_and_params, patient_id, doctor_id,
cb_states);
}
if (freetexts) {
set_sql_freetexts(sqls_and_params, patient_id, doctor_id, freetexts);
}
let db = await this.db_init();
let rs = await db.as_sql_transaction(sqls_and_params);
return rs;
}
async function update_prediction_with_user_values(patient_id, form_data) {
let fields = Object.keys(form_data);
let sql = `/* adfice.update_prediction_with_user_values */
UPDATE patient_measurement
SET `
let params = [];
for (let i = 0; i < fields.length; ++i) {
if (form_data[fields[i]] != "") {
if (fields[i] == "fear_dropdown") {
sql += 'user_fear0=' + '?,';
sql += 'user_fear1=' + '?,';
sql += 'user_fear2=' + '?,';
if (form_data[fields[i]] == 0) {
params.push(1, 0, 0);
}
if (form_data[fields[i]] == 1) {
params.push(0, 1, 0);
}
if (form_data[fields[i]] == 2) {
params.push(0, 0, 1);
}
} else {
sql += fields[i] + '=' + '?,';
params.push(form_data[fields[i]]);
}
}
}
if (params.length > 0) {
sql += 'user_values_updated = (select now())';
sql += " WHERE patient_id = ? ";
params.push(patient_id);
let sql_and_params = [sql, params];
let list_of_updates = [sql_and_params];
let db = await this.db_init();
let rs = await db.as_sql_transaction(list_of_updates);
await this.calculate_store_prediction_result(patient_id);
return rs;
} else {
return null;
}
}
async function update_birthdate(patient_id, form_data){
let patient = {birth_date: form_data['age_birthdate']}
let age = calculateAge(patient);
let sql = `/* adfice.update_birthdate */
UPDATE patient SET birth_date = ?, age = ?
WHERE patient_id = ?`;
let params = [form_data['age_birthdate'], age, patient_id];
let db = await this.db_init();
await db.sql_query(sql, params);
}
async function add_single_med(patient_id, form_data) {
let atc = form_data['single_med_atc'].toUpperCase().trim();
let sql = `/* adfice.add_single_med */
INSERT INTO patient_medication (id, patient_id, ATC_code, medication_name, generic_name, start_date)
VALUES(null,?,?,?,?,?)`;
let params = [];
params.push(patient_id, atc, form_data['single_med_name'], form_data['single_med_name'], form_data['single_med_startdate']);
let db = await this.db_init();
await db.sql_query(sql, params);
// if med changes a variable in the prediction model, add this info to the patient_measurements table
let meds = [{
'ATC_code': atc
}];
let prediction_meds = checkPredictionMeds(meds);
let sql_pmeds = "/* adfice.add_single_med */ UPDATE patient_measurement ";
let params_pmeds = [];
if (prediction_meds['has_antiepileptica'] != 0) {
sql_pmeds += "SET has_antiepileptica = ? ";
params_pmeds.push(prediction_meds['has_antiepileptica']);
}