forked from LibreHealthIO/lh-ehr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclinical_rules.php
2554 lines (2276 loc) · 100 KB
/
clinical_rules.php
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
<?php
/**
* Clinical Decision Rules(CDR) engine functions.
*
* These functions should not ever attempt to write to
* session variables, because the session_write_close() function
* is typically called before utilizing these functions.
*
* Copyright (C) 2010-2012 Brady Miller <[email protected]>
* Copyright (C) 2011 Medical Information Integration, LLC
* Copyright (C) 2011 Ensofttek, LLC
* Copyright (C) 2016 SunCoast Connection Inc.
*
* LICENSE: This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
*
* @package LibreEHR
* @author Art Eaton <[email protected]> (MIPS/MACRA Refactor)
* @author Bryan Lee <[email protected]>
* @author Brady Miller <[email protected]>
* @author Medical Information Integration, LLC
* @author Ensofttek, LLC
* @link http://librehealth.io
*/
require_once(dirname(__FILE__) . "/patient.inc");
require_once(dirname(__FILE__) . "/forms.inc");
require_once(dirname(__FILE__) . "/formdata.inc.php");
require_once(dirname(__FILE__) . "/options.inc.php");
require_once(dirname(__FILE__) . "/report_database.inc");
/**
* Return listing of CDR reminders in log.
*
* @param string $begin_date begin date (optional)
* @param string $end_date end date (optional)
* @return sqlret sql return query
*/
function listingCDRReminderLog($begin_date='',$end_date='') {
if (empty($end_date)) {
$end_date=date('Y-m-d H:i:s');
}
$sqlArray = array();
$sql = "SELECT `date`, `pid`, `uid`, `category`, `value`, `new_value` FROM `clinical_rules_log` WHERE `date` <= ?";
array_push($sqlArray,$end_date);
if (!empty($begin_date)) {
$sql .= " AND `date` >= ?";
array_push($sqlArray,$begin_date);
}
$sql .= " ORDER BY `date` DESC";
return sqlStatement($sql,$sqlArray);
}
/**
* Display the clinical summary widget.
*
* @param integer $patient_id pid of selected patient
* @param string $mode choose either 'reminders-all' or 'reminders-due' (required)
* @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
* @param string $organize_mode Way to organize the results (default or plans)
* @param string $user If a user is set, then will only show rules that user has permission to see.
*/
function clinical_summary_widget($patient_id,$mode,$dateTarget='',$organize_mode='default',$user='') {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect active actions
$actions = test_rules_clinic('','passive_alert',$dateTarget,$mode,$patient_id,'',$organize_mode, array(),'primary',NULL,NULL,$user);
// Display the actions
$current_targets = array();
foreach ($actions as $action) {
// Deal with plan names first
if (isset($action['is_plan']) && $action['is_plan']) {
echo "<br><b>";
echo htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
echo generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
echo "</b><br>";
continue;
}
// Collect the Rule Title, Rule Developer, Rule Funding Source, and Rule Release and show it when hover over the item.
$tooltip = '';
if (!empty($action['rule_id'])) {
$rule_title = getListItemTitle("clinical_rules",$action['rule_id']);
$ruleData = sqlQuery("SELECT `developer`, `funding_source`, `release_version`, `web_reference` " .
"FROM `clinical_rules` " .
"WHERE `id`=? AND `pid`=0", array($action['rule_id']) );
$developer = $ruleData['developer'];
$funding_source = $ruleData['funding_source'];
$release = $ruleData['release_version'];
$web_reference = $ruleData['web_reference'];
if (!empty($rule_title)) {
$tooltip = xla('Rule Title') . ": " . attr($rule_title) . "
";
}
if (!empty($developer)) {
$tooltip .= xla('Rule Developer') . ": " . attr($developer) . "
";
}
if (!empty($funding_source)) {
$tooltip .= xla('Rule Funding Source') . ": " . attr($funding_source) . "
";
}
if (!empty($release)) {
$tooltip .= xla('Rule Release') . ": " . attr($release);
}
if ( (!empty($tooltip)) || (!empty($web_reference)) ) {
if (!empty($web_reference)) {
$tooltip = "<a href='".attr($web_reference)."' target='_blank' style='white-space: pre-line;' title='".$tooltip."'>?</a>";
}
else {
$tooltip = "<span style='white-space: pre-line;' title='".$tooltip."'>?</span>";
}
}
}
if ($action['custom_flag']) {
// Start link for reminders that use the custom rules input screen
$url = "../rules/patient_data.php?category=".htmlspecialchars( $action['category'], ENT_QUOTES);
$url .= "&item=".htmlspecialchars( $action['item'], ENT_QUOTES);
echo "<a href='".$url."' class='iframe medium_modal' onclick='top.restoreSession()'>";
}
else if ($action['clin_rem_link']) {
// Start link for reminders that use the custom rules input screen
$pieces_url = parse_url($action['clin_rem_link']);
$url_prefix = $pieces_url['scheme'];
if($url_prefix == 'https' || $url_prefix == 'http'){
echo "<a href='" . $action['clin_rem_link'] .
"' class='iframe medium_modal' onclick='top.restoreSession()'>";
}else{
echo "<a href='../../../" . $action['clin_rem_link'] .
"' class='iframe medium_modal' onclick='top.restoreSession()'>";
}
}
else {
// continue since no link is needed
}
// Display Reminder Details
echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
if ($action['custom_flag'] || $action['clin_rem_link']) {
// End link for reminders that use an html link
echo "</a>";
}
// Display due status
if ($action['due_status']) {
// Color code the status (red for past due, purple for due, green for not due and black for soon due)
if ($action['due_status'] == "past_due") {
echo " (<span style='color:red'>";
}
else if ($action['due_status'] == "due") {
echo " (<span style='color:purple'>";
}
else if ($action['due_status'] == "not_due") {
echo " (<span style='color:green'>";
}
else {
echo " (<span>";
}
echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)";
}
// Display the tooltip
if (!empty($tooltip)) {
echo " ".$tooltip."<br>";
}
else {
echo "<br>";
}
// Add the target(and rule id and room for future elements as needed) to the $current_targets array.
// Only when $mode is reminders-due
if ($mode == "reminders-due" && $GLOBALS['enable_alert_log']) {
$target_temp = $action['category'].":".$action['item'];
$current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
}
}
// Compare the current with most recent action log (this function will also log the current actions)
// Only when $mode is reminders-due
if ($mode == "reminders-due" && $GLOBALS['enable_alert_log'] ) {
$new_targets = compare_log_alerts($patient_id,$current_targets,'clinical_reminder_widget',$_SESSION['authId']);
if (!empty($new_targets) && $GLOBALS['enable_cdr_new_crp']) {
// If there are new action(s), then throw a popup (if the enable_cdr_new_crp global is turned on)
// Note I am taking advantage of a slight hack in order to run javascript within code that
// is being passed via an ajax call by using a dummy image.
echo '<img src="../../pic/empty.gif" onload="alert(\''.xls('New Due Clinical Reminders').'\n\n';
foreach ($new_targets as $key => $value) {
$category_item = explode(":",$key);
$category = $category_item[0];
$item = $category_item[1];
echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$category) .
': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$item). '\n';
}
echo '\n' . '('. xls('See the Clinical Reminders widget for more details'). ')';
echo '\');this.parentNode.removeChild(this);" />';
}
}
}
/**
* Display the active screen reminder.
*
* @param integer $patient_id pid of selected patient
* @param string $mode choose either 'reminders-all' or 'reminders-due' (required)
* @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
* @param string $organize_mode Way to organize the results (default or plans)
* @param string $user If a user is set, then will only show rules that user has permission to see
* @param string $test Set to true when only checking if there are alerts (skips the logging then)
* @return string html display output.
*/
function active_alert_summary($patient_id,$mode,$dateTarget='',$organize_mode='default',$user='',$test=FALSE) {
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Collect active actions
$actions = test_rules_clinic('','active_alert',$dateTarget,$mode,$patient_id,'',$organize_mode, array(),'primary',NULL,NULL,$user);
if (empty($actions)) {
return false;
}
$returnOutput = "";
$current_targets = array();
// Display the actions
foreach ($actions as $action) {
// Deal with plan names first
if ($action['is_plan']) {
$returnOutput .= "<br><b>";
$returnOutput .= htmlspecialchars( xl("Plan"), ENT_NOQUOTES) . ": ";
$returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'clinical_plans'),$action['id']);
$returnOutput .= "</b><br>";
continue;
}
// Display Reminder Details
$returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$action['category']) .
": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$action['item']);
// Display due status
if ($action['due_status']) {
// Color code the status (red for past due, purple for due, green for not due and black for soon due)
if ($action['due_status'] == "past_due") {
$returnOutput .= " (<span style='color:red'>";
}
else if ($action['due_status'] == "due") {
$returnOutput .= " (<span style='color:purple'>";
}
else if ($action['due_status'] == "not_due") {
$returnOutput .= " (<span style='color:green'>";
}
else {
$returnOutput .= " (<span>";
}
$returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$action['due_status']) . "</span>)<br>";
}
else {
$returnOutput .= "<br>";
}
// Add the target(and rule id and room for future elements as needed) to the $current_targets array.
// Only when $mode is reminders-due and $test is FALSE
if (($mode == "reminders-due") && ($test === FALSE) && ($GLOBALS['enable_alert_log'])) {
$target_temp = $action['category'].":".$action['item'];
$current_targets[$target_temp] = array('rule_id'=>$action['rule_id'],'due_status'=>$action['due_status']);
}
}
// Compare the current with most recent action log (this function will also log the current actions)
// Only when $mode is reminders-due and $test is FALSE
if (($mode == "reminders-due") && ($test === FALSE) && ($GLOBALS['enable_alert_log'])) {
$new_targets = compare_log_alerts($patient_id,$current_targets,'active_reminder_popup',$_SESSION['authId']);
if (!empty($new_targets)) {
$returnOutput .="<br>" . xlt('New Items (see above for details)') . ":<br>";
foreach ($new_targets as $key => $value) {
$category_item = explode(":",$key);
$category = $category_item[0];
$item = $category_item[1];
$returnOutput .= generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$category) .
': ' . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$item). '<br>';
}
}
}
return $returnOutput;
}
/**
* Process and return allergy conflicts (when a active medication or presciption is on allergy list).
*
* @param integer $patient_id pid of selected patient
* @param string $mode either 'all' or 'new' (required)
* @param string $user If a user is set, then will only show rules that user has permission to see
* @param string $test Set to true when only checking if there are alerts (skips the logging then)
* @return array/boolean Array of allergy alerts or FALSE is empty.
*/
function allergy_conflict($patient_id,$mode,$user,$test=FALSE) {
// Collect allergies
$res_allergies = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='allergy' " .
"AND `activity`=1 " .
"AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
"AND `pid`=?", array($patient_id));
$allergies = array();
for($iter=0; $row=sqlFetchArray($res_allergies); $iter++) {
$allergies[$iter]=$row['title'];
}
// Build sql element of IN for below queries
$sqlParam = array();
$sqlIN = '';
$firstFlag = TRUE;
foreach ($allergies as $allergy) {
array_push($sqlParam,$allergy);
if ($firstFlag) {
$sqlIN .= "?";
$firstFlag = FALSE;
}
else {
$sqlIN .= ",?";
}
}
// Check if allergies conflict with medications or prescriptions
$conflicts_unique = array();
if (!empty($sqlParam)) {
$conflicts = array();
array_push($sqlParam,$patient_id);
$res_meds = sqlStatement("SELECT `title` FROM `lists` WHERE `type`='medication' " .
"AND `activity`=1 " .
"AND ( `enddate` IS NULL OR `enddate`='' OR `enddate` > NOW() ) " .
"AND `title` IN (" . $sqlIN . ") AND `pid`=?", $sqlParam);
while ($urow = sqlFetchArray($res_meds)) {
array_push($conflicts, $urow['title']);
}
$res_rx = sqlStatement("SELECT `drug` FROM `prescriptions` WHERE `active`=1 " .
"AND `drug` IN (" . $sqlIN . ") AND `patient_id`=?", $sqlParam);
while ($urow = sqlFetchArray($res_rx)) {
array_push($conflicts, $urow['drug']);
}
if (!empty($conflicts)) {
$conflicts_unique = array_unique($conflicts);
}
}
// If there are conflicts, $test is FALSE, and alert logging is on, then run through compare_log_alerts
$new_conflicts = array();
if ( (!empty($conflicts_unique)) && $GLOBALS['enable_alert_log'] && ($test===FALSE) ) {
$new_conflicts = compare_log_alerts($patient_id,$conflicts_unique,'allergy_alert',$_SESSION['authId'],$mode);
}
if ($mode == 'all') {
if (!empty($conflicts_unique)) {
return $conflicts_unique;
}
else {
return FALSE;
}
}
else { // $mode = 'new'
if (!empty($new_conflicts)) {
return $new_conflicts;
}
else {
return FALSE;
}
}
}
/**
* Compare current alerts with prior (in order to find new actions)
* Also functions to log the actions.
*
* @param integer $patient_id pid of selected patient
* @param array $current_targets array of targets
* @param string $category clinical_reminder_widget, active_reminder_popup, or allergy_alert
* @param integer $userid user id of user.
* @param string $log_trigger if 'all', then always log. If 'new', then only trigger log when a new item noted.
* @return array array with targets with associated rule.
*/
function compare_log_alerts($patient_id,$current_targets,$category='clinical_reminder_widget',$userid='',$log_trigger='all') {
if (empty($userid)) {
$userid = $_SESSION['authId'];
}
if (empty($current_targets)) {
$current_targets = array();
}
// Collect most recent action_log
$prior_targets_sql = sqlQuery("SELECT `value` FROM `clinical_rules_log` " .
"WHERE `category` = ? AND `pid` = ? AND `uid` = ? " .
"ORDER BY `id` DESC LIMIT 1", array($category,$patient_id,$userid) );
$prior_targets = array();
if (!empty($prior_targets_sql['value'])) {
$prior_targets = json_decode($prior_targets_sql['value'], true);
}
// Compare the current with most recent log
if ( ($category == 'clinical_reminder_widget') || ($category == 'active_reminder_popup') ) {
//using fancy structure to store multiple elements
$new_targets = array_diff_key($current_targets,$prior_targets);
}
else { // $category == 'allergy_alert'
//using simple array
$new_targets = array_diff($current_targets,$prior_targets);
}
// Store current action_log and the new items
// If $log_trigger=='all'
// or If $log_trigger=='new' and there are new items
if ( ($log_trigger=='all') || (($log_trigger=='new') && (!empty($new_targets))) ) {
$current_targets_json = json_encode($current_targets);
$new_targets_json = '';
if (!empty($new_targets)) {
$new_targets_json = json_encode($new_targets);
}
sqlInsert("INSERT INTO `clinical_rules_log` " .
"(`date`,`pid`,`uid`,`category`,`value`,`new_value`) " .
"VALUES (NOW(),?,?,?,?,?)", array($patient_id,$userid,$category,$current_targets_json,$new_targets_json) );
}
// Return new actions (if there are any)
return $new_targets;
}
/**
* Process clinic rules via a batching method to improve performance and decrease memory overhead.
*
* Test the clinic rules of entire clinic and create a report or patient reminders (can also test
* on one patient or patients of one provider). The structure of the returned results is dependent on the
* $organize_mode and $mode parameters.
* <pre>The results are dependent on the $organize_mode parameter settings
* 'default' organize_mode:
* Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
* 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
* 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
* 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
* 'plans' organize_mode:
* Returns similar to default, but organizes by the active plans
* </pre>
*
* @param integer $provider id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or 'collate_inner', then will test each provider in entire clinic; outer will nest plans inside collated providers, while inner will nest the providers inside the plans (note inner and outer are only different if organize_mode is set to plans).
* @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2014,amc,amc_2011,amc_2014,patient_reminder). If blank then will test all rules.
* @param string/array $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target. If an array, then is holding two dates ('dateBegin' and 'dateTarget').
* @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
* @param string $plan test for specific plan only
* @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
* @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
* @param string $pat_prov_rel How to choose patients that are related to a chosen provider. 'primary' selects patients that the provider is set as primary provider. 'encounter' selectes patients that the provider has seen. This parameter is only applicable if the $provider parameter is set to a provider or collation setting.
* @param integer $batchSize number of patients to batch (default is 100; plan to optimize this default setting in the future)
* @param integer $report_id id of report in database (if already bookmarked)
* @return array See above for organization structure of the results.
*/
function test_rules_clinic_batch_method($provider='',$type='',$dateTarget='',$mode='',$plan='',$organize_mode='default',$options=array(),$pat_prov_rel='primary',$batchSize='',$report_id=NULL) {
// Default to a batchsize, if empty
$batchSize = (empty($batchSize) ? 100 : $batchSize);
// Collect total number of pertinent patients (to calculate batching parameters)
$totalNumPatients = buildPatientArray('',$provider,$pat_prov_rel,NULL,NULL,TRUE);
// Cycle through the batches and collect/combine results
$totalNumberBatches = floor($totalNumPatients / $batchSize)
+ ($totalNumPatients % $batchSize > 0 ?
1 : // not perfectly divisible
0 // perfectly divisible
);
// Fix things in the $options array(). This now stores the number of labs to be used in the denominator in the AMC report.
// The problem with this variable is that is is added in every batch. So need to fix it by dividing this number by the number
// of planned batches(note the fixed array will go into the test_rules_clinic function, however the original will be used
// in the report storing/tracking engine.
$options_modified=$options;
if (!empty($options_modified['labs_manual'])) {
$options_modified['labs_manual'] = $options_modified['labs_manual'] / $totalNumberBatches;
}
// Prepare the database to track/store results
$fields = array(
'provider' => $provider,
'mode' => $mode,
'plan' => $plan,
'organize_mode' => $organize_mode,
'pat_prov_rel' => $pat_prov_rel
);
$fields = array_merge(
$fields,
(is_array($dateTarget) ?
array(
'date_target' => $dateTarget['dateTarget'],
'date_begin' => $dateTarget['dateBegin']
) :
array(
'date_target' => (
empty($dateTarget) ?
date('Y-m-d H:i:s') :
$dateTarget
)
)
)
);
if (!empty($options)) {
$fields = array_merge($fields, $options);
}
$report_id = beginReportDatabase($type,$fields,$report_id);
setTotalItemsReportDatabase($report_id,$totalNumPatients);
// Set ability to itemize report if this feature is turned on
$GLOBALS['report_itemizing_temp_flag_and_id'] = (
($GLOBALS['report_itemizing_pqrs'] && in_array($type, array('pqrs_individual_2015', 'pqrs_individual_2016', 'mips_2017', 'mips'))) ?
$report_id :
0
);
for ($i=0;$i<$totalNumberBatches;$i++) {
// If itemization is turned on, then reset the rule id iterator
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$GLOBALS['report_itemized_test_id_iterator'] = 1;
}
$dataSheet_batch = test_rules_clinic($provider, $type, $dateTarget, $mode, '', $plan, $organize_mode, $options_modified, $pat_prov_rel, ($batchSize * $i) + 1, $batchSize);
if ($i == 0) {
// For first cycle, simply copy it to dataSheet
$dataSheet = $dataSheet_batch;
$total_patients = 0;
} else {
//debug
//error_log("CDR: ".print_r($dataSheet,TRUE),0);
//error_log("CDR: ".($batchSize*$i)." records",0);
// Integrate batch results into main dataSheet
foreach ($dataSheet_batch as $key => $row) {
if (!$row['is_sub']) {
//skip this stuff for the sub entries (and use previous main entry in percentage calculation)
$total_patients = $dataSheet[$key]['total_patients'] + $row['total_patients'];
$dataSheet[$key]['total_patients'] = $total_patients;
$excluded = $dataSheet[$key]['excluded'] + $row['excluded'];
$dataSheet[$key]['excluded'] = $excluded;
$pass_filter = $dataSheet[$key]['pass_filter'] + $row['pass_filter'];
$dataSheet[$key]['pass_filter'] = $pass_filter;
}
$pass_target = $dataSheet[$key]['pass_target'] + $row['pass_target'];
$dataSheet[$key]['pass_target'] = $pass_target;
$dataSheet[$key]['percentage'] = calculate_percentage($pass_filter,$excluded,$pass_target);
}
}
//Update database to track results
updateReportDatabase($report_id,$total_patients);
}
// Record results in database and send to screen, if applicable.
finishReportDatabase($report_id,json_encode($dataSheet));
return $dataSheet;
}
/**
* Process clinic rules.
*
* Test the clinic rules of entire clinic and create a report or patient reminders (can also test
* on one patient or patients of one provider). The structure of the returned results is dependent on the
* $organize_mode and $mode parameters.
* <pre>The results are dependent on the $organize_mode parameter settings
* 'default' organize_mode:
* Returns a two-dimensional array of results organized by rules (dependent on the following $mode settings):
* 'reminders-due' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
* 'reminders-all' mode - returns an array of reminders (action array elements plus a 'pid' and 'due_status')
* 'report' mode - returns an array of rows for the Clinical Quality Measures (CQM) report
* 'plans' organize_mode:
* Returns similar to default, but organizes by the active plans
* </pre>
*
* @param integer $provider id of a selected provider. If blank, then will test entire clinic. If 'collate_outer' or 'collate_inner', then will test each provider in entire clinic; outer will nest plans inside collated providers, while inner will nest the providers inside the plans (note inner and outer are only different if organize_mode is set to plans).
* @param string $type rule filter (active_alert,passive_alert,cqm,cqm_2011,cqm_2104,amc,amc_2011,amc_2014,patient_reminder). If blank then will test all rules.
* @param string/array $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target. If an array, then is holding two dates ('dateBegin' and 'dateTarget').
* @param string $mode choose either 'report' or 'reminders-all' or 'reminders-due' (required)
* @param integer $patient_id pid of patient. If blank then will check all patients.
* @param string $plan test for specific plan only
* @param string $organize_mode Way to organize the results (default, plans). See above for organization structure of the results.
* @param array $options can hold various option (for now, used to hold the manual number of labs for the AMC report)
* @param string $pat_prov_rel How to choose patients that are related to a chosen provider. 'primary' selects patients that the provider is set as primary provider. 'encounter' selectes patients that the provider has seen. This parameter is only applicable if the $provider parameter is set to a provider or collation setting.
* @param integer $start applicable patient to start at (when batching process)
* @param integer $batchSize number of patients to batch (when batching process)
* @param string $user If a user is set, then will only show rules that user has permission to see(only applicable for per patient and not when do reports).
* @return array See above for organization structure of the results.
*/
function test_rules_clinic($provider='',$type='',$dateTarget='',$mode='',$patient_id='',$plan='',$organize_mode='default',$options=array(),$pat_prov_rel='primary',$start=NULL,$batchSize=NULL,$user='') {
// If dateTarget is an array, then organize them.
if (is_array($dateTarget)) {
$dateArray = $dateTarget;
$dateTarget = $dateTarget['dateTarget'];
}
// Set date to current if not set
$dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
// Prepare the results array
$results = array();
// If set the $provider to collate_outer (or collate_inner without plans organize mode),
// then run through this function recursively and return results.
if (($provider == "collate_outer") || ($provider == "collate_inner" && $organize_mode != 'plans')) {
// First, collect an array of all providers
$query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
$ures = sqlStatementCdrEngine($query);
// Second, run through each provider recursively
while ($urow = sqlFetchArray($ures)) {
$newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan,$organize_mode,$options,$pat_prov_rel,$start,$batchSize,$user);
if (!empty($newResults)) {
$provider_item['is_provider'] = TRUE;
$provider_item['prov_lname'] = $urow['lname'];
$provider_item['prov_fname'] = $urow['fname'];
$provider_item['npi'] = $urow['npi'];
$provider_item['federaltaxid'] = $urow['federaltaxid'];
array_push($results,$provider_item);
$results = array_merge($results,$newResults);
}
}
// done, so now can return results
return $results;
}
// If set organize-mode to plans, then collects active plans and run through this
// function recursively and return results.
if ($organize_mode == "plans") {
// First, collect active plans
$plans_resolve = resolve_plans_sql($plan,$patient_id);
// Second, run through function recursively
foreach ($plans_resolve as $plan_item) {
// (if collate_inner, then nest a collation of providers within each plan)
if ($provider == "collate_inner") {
// First, collect an array of all providers
$query = "SELECT id, lname, fname, npi, federaltaxid FROM users WHERE authorized = 1 ORDER BY lname, fname";
$ures = sqlStatementCdrEngine($query);
// Second, run through each provider recursively
$provider_results = array();
while ($urow = sqlFetchArray($ures)) {
$newResults = test_rules_clinic($urow['id'],$type,$dateTarget,$mode,$patient_id,$plan_item['id'],'default',$options,$pat_prov_rel,$start,$batchSize,$user);
if (!empty($newResults)) {
$provider_item['is_provider'] = TRUE;
$provider_item['prov_lname'] = $urow['lname'];
$provider_item['prov_fname'] = $urow['fname'];
$provider_item['npi'] = $urow['npi'];
$provider_item['federaltaxid'] = $urow['federaltaxid'];
array_push($provider_results,$provider_item);
$provider_results = array_merge($provider_results,$newResults);
}
}
if (!empty($provider_results)) {
$plan_item['is_plan'] = TRUE;
array_push($results,$plan_item);
$results = array_merge($results,$provider_results);
}
}
else {
// (not collate_inner, so do not nest providers within each plan)
$newResults = test_rules_clinic($provider,$type,$dateTarget,$mode,$patient_id,$plan_item['id'],'default',$options,$pat_prov_rel,$start,$batchSize,$user);
if (!empty($newResults)) {
$plan_item['is_plan'] = TRUE;
array_push($results,$plan_item);
$results = array_merge($results,$newResults);
}
}
}
// done, so now can return results
return $results;
}
// Collect applicable patient pids in only medicare
if (strpos($type, 'pqrs_individual') !== false ) {
$onlyMedicarePatients=true;
} else {
$onlyMedicarePatients=false;
}
$patientData = array();
$patientData = buildPatientArray($patient_id,$provider,$pat_prov_rel,$start,$batchSize, false, $onlyMedicarePatients);
// Go through each patient(s)
//
// If in report mode, then tabulate for each rule:
// Total Patients
// Patients that pass the filter
// Patients that pass the target
// If in reminders mode, then create reminders for each rule:
// Reminder that action is due soon
// Reminder that action is due
// Reminder that action is post-due
//Collect applicable rules
// Note that due to a limitation in the this function, the patient_id is explicitly
// for grouping items when not being done in real-time or for official reporting.
// So for cases such as patient reminders on a clinic scale, the calling function
// will actually need rather than pass in a explicit patient_id for each patient in
// a separate call to this function.
if ($mode != "report") {
// Use per patient custom rules (if exist)
// Note as discussed above, this only works for single patient instances.
$rules = resolve_rules_sql($type,$patient_id,FALSE,$plan,$user);
}
else { // $mode = "report"
// Only use default rules (do not use patient custom rules)
$rules = resolve_rules_sql($type,$patient_id,FALSE,$plan,$user);
}
foreach( $rules as $rowRule ) {
// If using cqm or amc type, then use the hard-coded rules set.
// Note these rules are only used in report mode.
if ( $rowRule['pqrs_individual_2016_flag'] ) {
require_once( dirname(__FILE__)."/classes/rulesets/ReportManager.php");
$manager = new ReportManager();
if ($rowRule['pqrs_individual_2016_flag'] ) {
error_log("*DEBUG*: clinical_rules: Site: ".$_SESSION['site_id']." About to runReport for ".$rowRule['id']);
// Send array of dates ('dateBegin' and 'dateTarget')
$tempResults = $manager->runReport( $rowRule, $patientData, $dateArray, $options );
}
else {
// Send target date
$tempResults = $manager->runReport( $rowRule, $patientData, $dateTarget );
}
if (!empty($tempResults)) {
foreach ($tempResults as $tempResult) {
array_push($results,$tempResult);
}
}
// Go on to the next rule
continue;
}
// If in reminder mode then need to collect the measurement dates
// from rule_reminder table
$target_dates = array();
if ($mode != "report") {
// Calculate the dates to check for
if ($type == "patient_reminder") {
$reminder_interval_type = "patient_reminder";
}
else { // $type == "passive_alert" or $type == "active_alert"
$reminder_interval_type = "clinical_reminder";
}
$target_dates = calculate_reminder_dates($rowRule['id'], $dateTarget, $reminder_interval_type);
}
else { // $mode == "report"
// Only use the target date in the report
$target_dates[0] = $dateTarget;
}
//Reset the counters
$total_patients = 0;
$pass_filter = 0;
$exclude_filter = 0;
$pass_target = 0;
// Find the number of target groups
$targetGroups = returnTargetGroups($rowRule['id']);
if ( (count($targetGroups) == 1) || ($mode == "report") ) {
// If report itemization is turned on, then iterate the rule id iterator
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$GLOBALS['report_itemized_test_id_iterator']++;
}
//skip this section if not report and more than one target group
foreach( $patientData as $rowPatient ) {
// First, deal with deceased patients
// (for now will simply skip the patient)
// If want to support rules for deceased patients then will need to migrate this below
// in target_dates foreach(guessing won't ever need to do this, though).
// Note using the dateTarget rather than dateFocus
if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
continue;
}
// Count the total patients
$total_patients++;
$dateCounter = 1; // for reminder mode to keep track of which date checking
// If report itemization is turned on, reset flag.
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$temp_track_pass = 1;
}
foreach ( $target_dates as $dateFocus ) {
//Skip if date is set to SKIP
if ($dateFocus == "SKIP") {
$dateCounter++;
continue;
}
//Set date counter and reminder token (applicable for reminders only)
if ($dateCounter == 1) {
$reminder_due = "soon_due";
}
else if ($dateCounter == 2) {
$reminder_due = "due";
}
else { // $dateCounter == 3
$reminder_due = "past_due";
}
// Check if pass filter
$passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
if ($passFilter === "EXCLUDED") {
// increment EXCLUDED and pass_filter counters
// and set as FALSE for reminder functionality.
$pass_filter++;
$exclude_filter++;
$passFilter = FALSE;
}
if ($passFilter) {
// increment pass filter counter
$pass_filter++;
// If report itemization is turned on, trigger flag.
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$temp_track_pass = 0;
}
}
else {
$dateCounter++;
continue;
}
// Check if pass target
$passTarget = test_targets($rowPatient['pid'],$rowRule['id'],'',$dateFocus);
if ($passTarget) {
// increment pass target counter
$pass_target++;
// If report itemization is turned on, then record the "passed" item and set the flag
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
$temp_track_pass = 1;
}
// send to reminder results
if ($mode == "reminders-all") {
// place the completed actions into the reminder return array
$actionArray = resolve_action_sql($rowRule['id'],'1');
foreach ($actionArray as $action) {
$action_plus = $action;
$action_plus['due_status'] = "not_due";
$action_plus['pid'] = $rowPatient['pid'];
$action_plus['rule_id'] = $rowRule['id'];
$results = reminder_results_integrate($results, $action_plus);
}
}
break;
}
else {
// send to reminder results
if ($mode != "report") {
// place the uncompleted actions into the reminder return array
$actionArray = resolve_action_sql($rowRule['id'],'1');
foreach ($actionArray as $action) {
$action_plus = $action;
$action_plus['due_status'] = $reminder_due;
$action_plus['pid'] = $rowPatient['pid'];
$action_plus['rule_id'] = $rowRule['id'];
$results = reminder_results_integrate($results, $action_plus);
}
}
}
$dateCounter++;
}
// If report itemization is turned on, then record the "failed" item if it did not pass
if ($GLOBALS['report_itemizing_temp_flag_and_id'] && !($temp_track_pass)) {
insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 0, $rowPatient['pid']);
}
}
}
// Calculate and save the data for the rule
$percentage = calculate_percentage($pass_filter,$exclude_filter,$pass_target);
if ($mode == "report") {
$newRow=array('is_main'=>TRUE,'total_patients'=>$total_patients,'excluded'=>$exclude_filter,'pass_filter'=>$pass_filter,'pass_target'=>$pass_target,'percentage'=>$percentage);
$newRow=array_merge($newRow,$rowRule);
// If itemization is turned on, then record the itemized_test_id
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$newRow=array_merge($newRow,array('itemized_test_id'=>$GLOBALS['report_itemized_test_id_iterator']));
}
array_push($results, $newRow);
}
// Now run through the target groups if more than one
if (count($targetGroups) > 1) {
foreach ($targetGroups as $i) {
// If report itemization is turned on, then iterate the rule id iterator
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$GLOBALS['report_itemized_test_id_iterator']++;
}
//Reset the target counter
$pass_target = 0;
foreach( $patientData as $rowPatient ) {
// First, deal with deceased patients
// (for now will simply skip the patient)
// If want to support rules for deceased patients then will need to migrate this below
// in target_dates foreach(guessing won't ever need to do this, though).
// Note using the dateTarget rather than dateFocus
if (is_patient_deceased($rowPatient['pid'],$dateTarget)) {
continue;
}
$dateCounter = 1; // for reminder mode to keep track of which date checking
// If report itemization is turned on, reset flag.
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$temp_track_pass = 1;
}
foreach ( $target_dates as $dateFocus ) {
//Skip if date is set to SKIP
if ($dateFocus == "SKIP") {
$dateCounter++;
continue;
}
//Set date counter and reminder token (applicable for reminders only)
if ($dateCounter == 1) {
$reminder_due = "soon_due";
}
else if ($dateCounter == 2) {
$reminder_due = "due";
}
else { // $dateCounter == 3
$reminder_due = "past_due";
}
// Check if pass filter
$passFilter = test_filter($rowPatient['pid'],$rowRule['id'],$dateFocus);
if ($passFilter === "EXCLUDED") {
$passFilter = FALSE;
}
if (!$passFilter) {
$dateCounter++;
continue;
}
else {
// If report itemization is turned on, trigger flag.
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
$temp_track_pass = 0;
}
}
//Check if pass target
$passTarget = test_targets($rowPatient['pid'],$rowRule['id'],$i,$dateFocus);
if ($passTarget) {
// increment pass target counter
$pass_target++;
// If report itemization is turned on, then record the "passed" item and set the flag
if ($GLOBALS['report_itemizing_temp_flag_and_id']) {
insertItemReportTracker($GLOBALS['report_itemizing_temp_flag_and_id'], $GLOBALS['report_itemized_test_id_iterator'], 1, $rowPatient['pid']);
$temp_track_pass = 1;
}
// send to reminder results
if ($mode == "reminders-all") {
// place the completed actions into the reminder return array
$actionArray = resolve_action_sql($rowRule['id'],$i);
foreach ($actionArray as $action) {
$action_plus = $action;
$action_plus['due_status'] = "not_due";
$action_plus['pid'] = $rowPatient['pid'];
$action_plus['rule_id'] = $rowRule['id'];