forked from openemr/openemr
-
Notifications
You must be signed in to change notification settings - Fork 4
/
common.php
1584 lines (1488 loc) · 80.8 KB
/
common.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
/**
* Encounter form for entering procedure orders.
*
* @package OpenEMR
* @link http://www.open-emr.org
* @author Rod Roark <rod@sunsetsystems.com>
* @author Brady Miller <brady.g.miller@gmail.com>
* @author Sherwin Gaddis <sherwingaddis@gmail.com>
* @author Jerry Padgett <sjpadgett@gmail.com>
* @author Ranganath Pathak <pathak@scrs1.org>
* @copyright Copyright (c) 2010-2017 Rod Roark <rod@sunsetsystems.com>
* @copyright Copyright (c) 2017-2019 Brady Miller <brady.g.miller@gmail.com>
* @copyright Copyright (c) 2019 Ranganath Pathak <pathak@scrs1.org>
* @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
*/
require_once(__DIR__ . "/../../globals.php");
require_once("$srcdir/api.inc.php");
require_once("$srcdir/forms.inc.php");
require_once("$srcdir/options.inc.php");
require_once(__DIR__ . "/../../orders/qoe.inc.php");
require_once(__DIR__ . "/../../../custom/code_types.inc.php");
use OpenEMR\Common\Csrf\CsrfUtils;
use OpenEMR\Common\Forms\ReasonStatusCodes;
use OpenEMR\Core\Header;
use OpenEMR\Events\Services\QuestLabTransmitEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
if (!$encounter) { // comes from globals.php
die("Internal error: we do not seem to be in an encounter!");
}
/**
* @var EventDispatcher
*/
$ed = $GLOBALS['kernel']->getEventDispatcher();
// Defaults for new orders.
$provider_id = getProviderIdOfEncounter($encounter);
$row = array(
'provider_id' => $provider_id,
'date_ordered' => date('Y-m-d'),
//'date_collected' => date('Y-m-d H:i'),
);
if ($_POST['bn_save_ereq'] ?? null) { //labcorp
$_POST['bn_xmit'] = "transmit";
}
$patient = sqlQueryNoLog("SELECT * FROM `patient_data` WHERE `pid` = ?", array($pid));
global $gbl_lab, $gbl_lab_title, $gbl_client_acct;
function get_lab_name($id): string
{
global $gbl_lab_title, $gbl_lab, $gbl_client_acct, $gbl_use_codes;
$tmp = sqlQuery("SELECT name, send_fac_id as clientid, npi FROM procedure_providers Where ppid = ?", array($id));
$gbl_lab = stripos($tmp['name'] ?? '', 'quest') !== false ? 'quest' : 'ammon';
$gbl_lab = stripos($tmp['name'] ?? '', 'labcorp') !== false ? 'labcorp' : $gbl_lab;
$gbl_lab = stripos($tmp['name'] ?? '', 'clarity') !== false ? 'clarity' : $gbl_lab;
$gbl_lab_title = trim($tmp['name'] ?? '');
$gbl_client_acct = trim($tmp['clientid'] ?? '');
return $gbl_lab;
}
if (!function_exists('ucname')) {
function ucname($string): string
{
$string = ucwords(strtolower($string));
foreach (array('-', '\'') as $delimiter) {
if (strpos($string, $delimiter) !== false) {
$string = implode($delimiter, array_map('ucfirst', explode($delimiter, $string)));
}
}
return $string;
}
}
function cbvalue($cbname): string
{
return $_POST[$cbname] ? '1' : '0';
}
function cbinput($name, $colname)
{
global $row;
$ret = "<input type='checkbox' name='" . attr($name) . "' value='1'";
if ($row[$colname]) {
$ret .= " checked";
}
$ret .= " />";
return $ret;
}
function cbcell($name, $desc, $colname): string
{
return "<td width='25%' nowrap>" . cbinput($name, $colname) . text($desc) . "</td>\n";
}
function QuotedOrNull($fld)
{
if (empty($fld)) {
return null;
}
return $fld;
}
function getListOptions($list_id, $fieldnames = array('option_id', 'title', 'seq')): array
{
$output = array();
$query = sqlStatement("SELECT " . implode(',', $fieldnames) . " FROM list_options where list_id = ? AND activity = 1 order by seq", array($list_id));
while ($ll = sqlFetchArray($query)) {
foreach ($fieldnames as $val) {
$output[$ll['option_id']][$val] = $ll[$val];
}
}
return $output;
}
// do not change from $_REQUEST.
$formid = (int)($_REQUEST['id'] ?? 0);
$reload_url = $rootdir . '/patient_file/encounter/view_form.php?formname=procedure_order&id=' . urlencode($formid);
$req_url = $GLOBALS['web_root'] . '/controller.php?document&retrieve&patient_id=' . urlencode($pid) . '&document_id=';
$reqStr = "";
// If Save or Transmit was clicked, save the info.
//
if (($_POST['bn_save'] ?? null) || !empty($_POST['bn_xmit']) || !empty($_POST['bn_save_exit'])) {
if (!CsrfUtils::verifyCsrfToken($_POST["csrf_token_form"])) {
CsrfUtils::csrfNotVerified();
}
$ppid = (int)$_POST['form_lab_id'];
if (get_lab_name($ppid) === 'labcorp') {
if (!empty($_POST['form_account_facility'])) {
$location = sqlQueryNoLog("SELECT f.id, f.facility_code, f.name FROM facility as f " .
"WHERE f.id = ?", array($_POST['form_account_facility']));
$_POST['form_account'] = $location['facility_code'];
} else {
$_POST['form_account'] = '';
}
}
$sets =
"date_ordered = ?, " .
"provider_id = ?, " .
"lab_id = ?, " .
"date_collected = ?, " .
"order_priority = ?, " .
"order_status = ?, " .
"billing_type = ?, " .
"order_psc = ?, " .
"specimen_fasting = ?, " .
"specimen_volume = ?, " .
"clinical_hx = ?, " .
"patient_instructions = ?, " .
"patient_id = ?, " .
"encounter_id = ?, " .
"history_order = ?, " .
"order_abn = ?, " .
"order_diagnosis = ?, " .
"account = ?, " .
"account_facility = ?, " .
"collector_id = ?, " .
"procedure_order_type = ?";
$set_array = array(
QuotedOrNull($_POST['form_date_ordered']),
(int)$_POST['form_provider_id'],
$ppid,
QuotedOrNull($_POST['form_date_collected']),
$_POST['form_order_priority'],
$_POST['form_order_status'],
$_POST['form_billing_type'],
$_POST['form_order_psc'],
$_POST['form_specimen_fasting'] ?? '',
$_POST['form_specimen_volume'] ?? '',
trim($_POST['form_clinical_hx']),
trim($_POST['form_patient_instructions']),
$pid,
$encounter,
trim($_POST['form_history_order']),
trim($_POST['form_order_abn']),
trim($_POST['form_order_diagnosis']),
trim($_POST['form_account']),
(int)$_POST['form_account_facility'],
(int)$_POST['form_collector_id'],
trim($_POST['procedure_type_names']),
);
// If updating an existing form...
//
if ($formid) {
$query = "UPDATE procedure_order SET $sets WHERE procedure_order_id = ?";
$set_array_temp = $set_array;
$set_array_temp[] = $formid;
sqlStatement($query, $set_array_temp);
$gbl_lab = get_lab_name($ppid);
$tmp = $_POST['procedure_type_names'] ?: $formid;
$lab_title = $gbl_lab_title . "-$tmp";
$query = "UPDATE forms SET form_name = ? WHERE encounter = ? AND form_id = ? AND formdir = ?";
sqlStatement($query, array($lab_title, $encounter, $formid, 'procedure_order'));
} else {
$query = "INSERT INTO procedure_order SET $sets";
$formid = sqlInsert($query, $set_array);
$gbl_lab = get_lab_name($ppid);
$tmp = $_POST['procedure_type_names'] ?: $formid;
$lab_title = $gbl_lab_title . "-$tmp";
addForm($encounter, $lab_title, $formid, "procedure_order", $pid, $userauthorized);
$mode = 'update';
$viewmode = true;
}
$log_file = $GLOBALS["OE_SITE_DIR"] . "/documents/labs/" . check_file_dir_name(get_lab_name($ppid)) . "/logs/" . check_file_dir_name($formid) . "_order_log.log";
$order_log = $_POST['order_log'] ?? '';
if ($order_log) {
file_put_contents($log_file, $order_log);
}
// Remove any existing procedures and their answers for this order and
// replace them from the form.
sqlStatement(
"DELETE FROM procedure_answers WHERE procedure_order_id = ?",
array($formid)
);
sqlStatement(
"DELETE FROM procedure_order_code WHERE procedure_order_id = ?",
array($formid)
);
for ($i = 0; isset($_POST['form_proc_type'][$i]); ++$i) {
$ptid = (int)$_POST['form_proc_type'][$i];
if ($ptid <= 0 && $ptid !== -2) {
continue;
}
if ($ptid === -2) {
// insert a compendium type for new code from picker.
$query_select_pt = 'SELECT * FROM procedure_type WHERE procedure_code = ? AND lab_id = ?';
$result_types = sqlQuery($query_select_pt, array($_POST['form_proc_code'][$i], $_POST['form_lab_id']));
$ptid = (int)($result_types['procedure_type_id'] ?? 0);
if ($ptid === 0) {
//procedure_type
$query_insert = 'INSERT INTO procedure_type(name,lab_id,procedure_code,procedure_type,activity,procedure_type_name) VALUES (?,?,?,?,?,?)';
$ptid = sqlInsert(
$query_insert,
array(
$_POST['form_proc_type_desc'][$i], $_POST['form_lab_id'], $_POST['form_proc_code'][$i], 'ord', 1, $_POST['procedure_type_names'])
);
$query_update_pt = 'UPDATE procedure_type SET parent = ? WHERE procedure_type_id = ?';
sqlQuery($query_update_pt, array($ptid, $ptid));
}
}
$prefix = "ans$i" . "_";
sqlBeginTrans();
$procedure_order_seq = sqlQuery("SELECT IFNULL(MAX(procedure_order_seq),0) + 1 AS increment FROM procedure_order_code WHERE procedure_order_id = ? ", array($formid));
$reason_code = trim($_POST['form_proc_reason_code'][$i] ?? '');
$reason_description = trim($_POST['form_proc_reason_description'][$i] ?? '');
$reason_date_low = trim($_POST['form_proc_reason_date_low'][$i] ?? '');
$reason_date_high = trim($_POST['form_proc_reason_date_high'][$i] ?? '');
$reason_status = trim($_POST['form_proc_reason_status'][$i] ?? '');
if (empty($reason_code)) {
$reason_description = null;
$reason_date_low = null;
$reason_date_high = null;
$reason_status = null;
}
// set these values to null if they are empty as we don't want it to use 0000-00-00 00:00:00 for the datetime
if (empty($reason_date_low)) {
$reason_date_low = null;
}
if (empty($reason_date_high)) {
$reason_date_high = null;
}
$poseq = sqlInsert(
"INSERT INTO procedure_order_code SET " .
"procedure_order_id = ?, " .
"diagnoses = ?, " .
"procedure_order_title = ?, " .
"transport = ?, " .
"procedure_code = (SELECT procedure_code FROM procedure_type WHERE procedure_type_id = ?), " .
"procedure_name = (SELECT name FROM procedure_type WHERE procedure_type_id = ?)," .
"procedure_type = ?, " .
"reason_code = ?, " .
"reason_description = ?, " .
"reason_date_low = ?, " .
"reason_date_high = ?, " .
"reason_status = ?, " .
"procedure_order_seq = ? ",
array(
$formid,
trim($_POST['form_proc_type_diag'][$i]),
trim($_POST['form_proc_order_title'][$i]),
trim($_POST['form_transport'][$i]),
$ptid,
$ptid,
trim($_POST['form_procedure_type'][$i] ?: $_POST['procedure_type_names'] ?? ''),
$reason_code,
$reason_description,
$reason_date_low,
$reason_date_high,
$reason_status,
$procedure_order_seq['increment']
)
);
sqlCommitTrans();
$poseq = $procedure_order_seq['increment'];
$qres = sqlStatement("SELECT " .
"q.procedure_code, q.question_code, q.options, q.fldtype " .
"FROM procedure_type AS t " .
"JOIN procedure_questions AS q ON q.lab_id = t.lab_id " .
"AND q.procedure_code = t.procedure_code AND q.activity = 1 " .
"WHERE t.procedure_type_id = ? " .
"ORDER BY q.seq, q.question_text", array($ptid));
while ($qrow = sqlFetchArray($qres)) {
$options = trim($qrow['options']);
$qcode = trim($qrow['question_code']);
$pcode = trim($qrow['procedure_code']);
$fldtype = $qrow['fldtype'];
$data = '';
if ($fldtype == 'G') {
if ($_POST["G1_$prefix$qcode"]) {
$data = $_POST["G1_$prefix$qcode"] * 7 + $_POST["G2_$prefix$qcode"];
}
} else {
$data = $_POST["$prefix$qcode"];
}
if (!isset($data) || $data === '') {
continue;
}
if (!is_array($data)) {
$data = array($data);
}
foreach ($data as $datum) {
// Note this will auto-assign the seq value.
sqlBeginTrans();
$answer_seq = sqlQuery("SELECT IFNULL(MAX(answer_seq),0) + 1 AS increment FROM procedure_answers WHERE procedure_order_id = ? AND procedure_order_seq = ? AND question_code = ? ", array($formid, $poseq, $qcode));
sqlStatement(
"INSERT INTO procedure_answers SET " .
"procedure_order_id = ?, " .
"procedure_order_seq = ?, " .
"question_code = ?, " .
"answer_seq = ?, " .
"answer = ?, " .
"procedure_code = ?",
array($formid, $poseq, $qcode, $answer_seq['increment'], trim($datum), $pcode)
);
sqlCommitTrans();
}
}
}
if (isset($_POST['bn_save_exit'])) {
formHeader("Redirecting....");
if ($alertmsg ?? '') {
$msg = xl('Transmit failed') . ': ' . $alertmsg;
echo "\n<script>alert(" . js_escape($msg) . ")</script>\n";
}
formJump();
formFooter();
exit;
}
$alertmsg = '';
if (!empty($_POST['bn_xmit'])) {
// Validate, log and send order. Sets up documents and requisition buttons
$gbl_lab = get_lab_name($ppid);
$hl7 = '';
$order_data = '';
if ($_POST['form_provider_id'] + 0 < 1) {
$order_data .= "\n" . xlt("Ordering Provider is required but not selected!");
}
$diag_flag = 0;
foreach ($_POST['form_proc_type_diag'] as $diag) {
$diag_flag = (!empty($diag) || !empty($_POST['form_order_diagnosis'])) ? (++$diag_flag) : $diag_flag;
}
if ($diag_flag === 0) {
$order_data .= "\n" . xlt("At least one diagnosis is required! Please add a diagnosis for this order.");
}
if ($_POST['form_order_abn'] === 'required') {
$order_data .= "\n" . xlt("ABN is required but not signed!");
}
if (!$_POST['form_date_collected'] && !$_POST['form_order_psc']) {
$order_data .= "\n" . xlt("Specimen Collections date has not been entered and this is not a PSC Hold Order!");
}
if ($order_data) {
$alertmsg = date('Y-m-d H:i') . " " . xlt("Prior Validations Errors") . $order_data;
$order_data .= "\n<span class='text-danger'>" . "- " .
xlt("Please resolve errors and resubmit order.") .
"</span>";
$order_data = nl2br($order_data);
if ($order_log) {
$alertmsg = $order_log . "\n" . $alertmsg;
$order_log = $alertmsg; // persist log
} else {
$order_log = $alertmsg;
$alertmsg = '';
}
file_put_contents($log_file, $order_log);
} else { // drop through if no errors..
if ($gbl_lab === 'ammon' || $gbl_lab === 'clarity') {
require_once(__DIR__ . "/../../procedure_tools/gen_universal_hl7/gen_hl7_order.inc.php");
$alertmsg = gen_hl7_order($formid, $hl7);
} elseif ($gbl_lab === 'labcorp') {
require_once(__DIR__ . "/../../procedure_tools/labcorp/ereq_form.php");
require_once(__DIR__ . "/../../procedure_tools/labcorp/gen_hl7_order.inc.php");
$alertmsg = gen_hl7_order($formid, $hl7, $reqStr);
} elseif ($gbl_lab === 'quest') {
require_once(__DIR__ . "/../../procedure_tools/quest/gen_hl7_order.inc.php");
$alertmsg = gen_hl7_order($formid, $hl7, $reqStr);
} else { // Default lab. Add more labs here.
require_once(__DIR__ . "/../../orders/gen_hl7_order.inc.php");
$alertmsg = gen_hl7_order($formid, $hl7);
}
if (empty($alertmsg)) {
if (empty($_POST['bn_save_ereq'])) {
$alertmsg = send_hl7_order($ppid, $hl7);
}
} else {
$order_data .= $alertmsg;
}
if (empty($alertmsg)) {
$savereq = true;
if (empty($_POST['bn_save_ereq'])) {
sqlStatement("UPDATE procedure_order SET date_transmitted = NOW() WHERE procedure_order_id = ?", array($formid));
$order_log .= "\n" . date('Y-m-d H:i') . " " .
xlt("Order Successfully Sent") . "...\n" .
xlt("Order HL7 Content") .
":\n" . $hl7 . "\n";
if ($gbl_lab === 'quest') {
$order_log .= xlt("Transmitting order to Quest");
$ed->dispatch(new QuestLabTransmitEvent($hl7), QuestLabTransmitEvent::EVENT_LAB_TRANSMIT, 10);
$ed->dispatch(new QuestLabTransmitEvent($pid), QuestLabTransmitEvent::EVENT_LAB_POST_ORDER_LOAD, 10);
}
if ($_POST['form_order_psc']) {
if ($gbl_lab === 'labcorp') {
$order_log .= "\n" . date('Y-m-d H:i') . " " .
xlt("Generating and charting requisition for PSC Hold Order") . "...\n";
ereqForm($pid, $encounter, $formid, $reqStr, $savereq);
}
}
} else {
if (isset($_POST['bn_save_ereq'])) {
$savereq = false;
}
if ($gbl_lab === 'labcorp') {
// Manual requisition
$order_log .= "\n" . date('Y-m-d H:i') . " " .
xlt("Generating requisition based on order HL7 content") . "...\n" . $hl7 . "\n";
ereqForm($pid, $encounter, $formid, $reqStr, $savereq);
}
}
file_put_contents($log_file, $order_log);
} else {
if ($order_log) {
$alertmsg = $order_log . "\n" . $alertmsg;
$order_log = $alertmsg; // persist log
} else {
$order_log = $alertmsg;
}
file_put_contents($log_file, $order_log);
}
}
unset($_POST['bn_xmit']);
}
unset($_POST['bn_save']);
$reload_url = $rootdir . '/patient_file/encounter/view_form.php?formname=procedure_order&id=' . attr($formid);
if (empty($order_data)) {
header('Location:' . $reload_url);
}
}
if (!empty($formid)) {
$row = sqlQuery("SELECT * FROM procedure_order WHERE procedure_order_id = ?", array($formid));
}
$enrow = sqlQuery(
"SELECT p.fname, p.mname, p.lname, fe.date FROM " .
"form_encounter AS fe, forms AS f, patient_data AS p WHERE " .
"p.pid = ? AND f.pid = p.pid AND f.encounter = ? AND " .
"f.formdir = 'newpatient' AND f.deleted = 0 AND " .
"fe.id = f.form_id LIMIT 1",
array($pid, $encounter)
);
$bill_type = $row['billing_type'] ?? '';
$gbl_lab = get_lab_name($row['lab_id'] ?? '');
if ($formid) {
$location = sqlQueryNoLog("SELECT f.id, f.facility_code, f.name FROM facility as f " .
"WHERE f.id = ?", array($row['account_facility']));
} else {
$location = sqlQueryNoLog("SELECT f.id, f.facility_code, f.name FROM users as u " .
"INNER JOIN facility as f ON u.facility_id = f.id WHERE u.id = ?", array($row['provider_id']));
}
$account = $location['facility_code'] ?? '';
$account_name = $location['name'] ?? '';
$account_facility = $location['id'] ?? '';
if (!empty($row['lab_id'])) {
$log_file = $GLOBALS["OE_SITE_DIR"] . "/documents/labs/" . check_file_dir_name(get_lab_name($row['lab_id'])) . "/logs/";
if (!is_dir($log_file)) {
if (!mkdir($log_file, 0755, true) && !is_dir($log_file)) {
throw new Exception(sprintf('Directory "%s" was not created', $log_file));
}
}
// filename
$log_file .= check_file_dir_name($formid) . '_order_log.log';
if (file_exists($log_file)) {
$order_log = file_get_contents($log_file);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<?php Header::setupHeader(['datetime-picker', 'reason-code-widget']); ?>
<script>
// Some JS Globals that will be useful.
var gbl_formseq;
var currentLabId = <?php echo js_escape($row['lab_id'] ?? ''); ?>;
var currentLab = <?php echo js_escape($gbl_lab); ?>;
var currentLabTitle = <?php echo js_escape($gbl_lab_title); ?>;
var viewmode = <?php echo !empty($viewmode) ? 1 : 0 ?>;
var refreshForm = <?php echo js_escape($reload_url); ?>;
// we want to setup our reason code widgets
window.addEventListener('DOMContentLoaded', function() {
if (oeUI.reasonCodeWidget) {
oeUI.reasonCodeWidget.init(<?php echo js_url($GLOBALS['webroot']); ?>, <?php echo js_url(collect_codetypes("problem", "csv")) ?>);
} else {
console.error("Missing required dependency reasonCodeWidget");
return;
}
});
function processSubmit(od) { // not used yet
$("#form_order_abn").val(od.order_abn);
$("#bn_save").click();
}
function initCalendars() {
var datepicker = {
<?php $datetimepicker_timepicker = true; ?>
<?php $datetimepicker_showseconds = false; ?>
<?php $datetimepicker_formatInput = false; ?>
<?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?>
};
var datetimepicker = {
<?php $datetimepicker_timepicker = true; ?>
<?php $datetimepicker_showseconds = false; ?>
<?php $datetimepicker_formatInput = false; ?>
<?php require($GLOBALS['srcdir'] . '/js/xl/jquery-datetimepicker-2-5-4.js.php'); ?>
};
$('.datepicker').datetimepicker(datepicker);
$('.datetimepicker').datetimepicker(datetimepicker);
}
function initDeletes() {
$(".itemDelete").on("click", function (event) {
deleteRow(event);
});
}
function deleteRow(event) {
event.preventDefault();
event.stopPropagation();
let target = $(event.currentTarget).closest('tr').find("input[name^='form_proc_type_desc']").val();
let yn = true;
if (target)
yn = confirm(<?php echo xlj("Confirm to remove item") ?> +"\n" + target);
if (yn)
$(event.currentTarget).closest(".proc-table").remove();
}
// This invokes the find-procedure-type popup.
// formseq = 0-relative index in the form.
function sel_proc_type(formseq) {
let f = document.forms[0];
gbl_formseq = formseq;
let ptvarname = 'form_proc_type[' + formseq + ']';
let title = <?php echo xlj("Find Procedure Order"); ?>;
// This replaces the previous search for an easier/faster order picker tool.
dlgopen('../../orders/find_order_popup.php' +
'?labid=' + encodeURIComponent(f.form_lab_id.value) +
'&order=' + encodeURIComponent(f[ptvarname].value) +
'&formid=' + <?php echo js_url($formid); ?> +
'&formseq=' + encodeURIComponent(formseq),
'_blank', 850, 500, '', title);
}
// This is for callback by the find-procedure-type popup.
// Sets both the selected type ID and its descriptive name.
// Also set diagnosis if supplied in configuration and custom test groups.
function set_proc_type(typeid, typename, diagcodes = '', temptype, typetitle, testid, newCnt = 0) {
let f = document.forms[0];
let ptvarname = 'form_proc_type[' + gbl_formseq + ']';
let ptdescname = 'form_proc_type_desc[' + gbl_formseq + ']';
let ptcodes = 'form_proc_type_diag[' + gbl_formseq + ']';
let pttransport = 'form_transport[' + gbl_formseq + ']';
let ptproccode = 'form_proc_code[' + gbl_formseq + ']';
let ptproctypename = 'form_proc_order_title[' + gbl_formseq + ']';
let psc = '';
f[pttransport].value = temptype;
f[ptvarname].value = typeid;
f[ptdescname].value = typename;
f[ptproccode].value = testid;
f[ptproctypename].value = typetitle ? typetitle : 'procedure';
if (diagcodes)
f[ptcodes].value = diagcodes;
if (newCnt > 1) {
gbl_formseq = addProcLine(true);
}
}
// This is also for callback by the find-procedure-type popup.
// Sets the contents of the table containing the form fields for questions.
function set_proc_html(s, js) {
document.getElementById('qoetable[' + gbl_formseq + ']').innerHTML = s;
initCalendars();
}
// New lab selected so clear all procedures and questions from the form.
function lab_id_changed(el) {
if (viewmode) {
let msg = "Changing Labs will clear this order. Are you sure you want to continue?";
if (!confirm(msg)) {
$("#form_lab_id").val(currentLabId);
return false;
}
}
top.restoreSession();
let lab = $("#form_lab_id option:selected").text();
if (lab.toLowerCase().indexOf('quest') !== -1) currentLab = 'quest';
if (lab.toLowerCase().indexOf('ammon') !== -1) currentLab = 'ammon';
if (lab.toLowerCase().indexOf('labcorp') !== -1) currentLab = 'labcorp';
if (lab.toLowerCase().indexOf('clarity') !== -1) currentLab = 'clarity';
let f = document.forms[0];
for (let i = 0; true; ++i) {
let ix = '[' + i + ']';
if (!f['form_proc_type' + ix]) break;
let target = '#procedures_item_' + i;
$(target).closest(".proc-table").remove();
}
if (viewmode) {
$("#bn_save").click();
} else {
addProcLine(false);
}
}
function addProcedure() {
$(".procedure-order-container").append($(".procedure-order").clone());
let newOrder = $(".procedure-order-container .procedure-order:last");
$(newOrder + " label:first").append("1");
}
function addProcLine(flag = false) {
if (!('content' in document.createElement('template'))) {
console.error("Old browser detected as template content property is not supported");
return;
}
let template = document.getElementById('procedure_order_code_template');
if (!template) {
console.error("Cannot add procedure line due to missing template node with id procedure_order_code_template");
return;
}
// grab our content, update all our ids, setup any event listeners and add the item in
let node = template.content.cloneNode(true);
// now we need to update our procedure key names here
let lineCountNodes = document.querySelectorAll(".procedure-order-container .proc-table-main");
let lineCount = 0;
if (lineCountNodes && lineCountNodes.length) {
lineCount = lineCountNodes.length;
}
// now we are going to rename all of our templated nodes to be our newest index.
let remapArrayIndex = function(value) {
if (value && value.indexOf("[")) {
let parts = value.split("[");
return parts[0] + "[" + lineCount + "]";
} else {
return value;
}
};
let remapNames = function(node) {
node.name = remapArrayIndex(node.name);
};
// wierdly all of our mapped ids use array indexes as part of the id.
let remapIds = function(node) {
node.id= remapArrayIndex(node.id);
};
let remapSelectors = function(selector, map)
{
let mapNodes = node.querySelectorAll(selector);
if (mapNodes && mapNodes.length) {
mapNodes.forEach(map);
}
};
remapSelectors('input,select', remapNames);
remapSelectors('.qoe-table-sel-procedure', remapIds);
remapSelectors('[data-toggle-container]', function(node) {
node.dataset.toggleContainer = "reason_code_" + lineCount;
});
remapSelectors('.reasonCodeContainer', function(node) {
node.id = "reason_code_" + lineCount;
});
// now we need to add our events
let nullableFunction = function(selector, event, callback) {
let nodeForCallback = node.querySelector(selector);
if (nodeForCallback) {
nodeForCallback.addEventListener(event, callback);
} else {
console.error("Failed to find node with selector ", selector);
}
};
// once our node is in the DOM, we need to add event listeners to it.
nullableFunction('.itemTransport', 'click', function(event) {
// we have to bind to our lineCount at the time of instantiation in case addProcLine is called again
// and we curry against the outer lineCount
var boundLineCount = lineCount + 0; // should be copy by value, but some JS contexts are wierd
getDetails(event, boundLineCount);
});
nullableFunction('.btn-secondary.btn-search', 'click', function(event) {
// we have to bind to our lineCount at the time of instantiation in case addProcLine is called again
// and we curry against the outer lineCount
var boundLineCount = lineCount + 0; // should be copy by value, but some JS contexts are wierd
selectProcedureCode(boundLineCount);
});
nullableFunction('.search-current-diagnoses', 'click', function(event) {
current_diagnoses(event.currentTarget); // use the bound target
});
nullableFunction('.add-diagnosis-sel-related', 'click', function(event) {
sel_related(event.currentTarget.name);
});
nullableFunction('.add-diagnosis-sel-related', 'focus', function(event) {
event.currentTarget.blur();
});
nullableFunction('.sel-proc-type', 'click', function(event) {
var boundLineCount = lineCount + 0; // should be copy by value, but some JS contexts are wierd
sel_proc_type(boundLineCount);
});
nullableFunction('.sel-proc-type', 'focus', function(event) {
event.currentTarget.blur();
});
nullableFunction('.itemDelete', 'click', deleteRow);
// now we will take all the children of the doc fragment and stuff it into the DOM
$(".procedure-order-container").append(node);
initForm();
if (!flag) {// flag true indicates add procedure item from custom group callback with current index.
// note the proc type order id is -1 for a new row... this makes the popup happy, not sure why this was originally set to -1.
sel_proc_type(lineCount);
return false;
} else {
return lineCount;
}
}
// The name of the form field for find-code popup results.
var rcvarname, targetElement, targetProcedure, promiseData;
/*
* I could have used a callback like set_related_target but I wanted
* to show an example of a dialog promise. Handy for cleanup or showing
* an dialog.alert etc..
*
* */
function selectProcedureCode(offset) {
let f = document.forms[0];
rcvarname = f.elements['form_proc_code[' + offset + ']'].name;
codes = f.elements['form_proc_code[' + offset + ']'].value;
targetProcedure = f.elements['form_proc_code[' + offset + ']'];
targetElement = f.elements['form_proc_type_desc[' + offset + ']'];
let title = <?php echo xlj('Select Procedure Code'); ?>;
let url = top.webroot_url + '/interface/patient_file/encounter/find_code_dynamic.php?codetype=LOINC,SNOMED-CT,SNOMED,RXCUI,CPT4,VALUESET,OID&singleCodeSelection=1';
dlgopen(url, '_blank', 985, 750, '', title, {
resolvePromiseOn: 'close'
}).then(dialogObject => {
let codeData = JSON.parse(promiseData);
let codes = codeData.codetype + ':' + codeData.code;
targetProcedure.value = codes;
targetElement.value = codeData.codedesc;
let type = f.elements['procedure_type_names'].value ?? '';
if (type !== '') {
f.elements['form_procedure_type[' + offset + ']'].value = type;
}
f.elements['form_proc_type[' + offset + ']'].value = -2; // lookup type id on save.
});
}
function current_diagnoses(whereElement) {
targetProcedure = whereElement.parentElement.parentElement.parentElement.previousElementSibling;
targetElement = whereElement.parentElement.parentElement.nextElementSibling;
let title = <?php echo xlj("Diagnosis Codes History"); ?>;
dlgopen('find_code_history.php', 'dxDialog', 'modal-mlg', 450, '', title, {
buttons: [
{text: '<?php echo xla('Save'); ?>', id: 'saveDx', style: 'primary btn-save'},
{text: '<?php echo xla('Help'); ?>', id: 'showTips', style: 'primary btn-show'},
{text: '<?php echo xla('Cancel'); ?>', close: true, style: 'secondary btn-cancel'},
],
type: 'iframe'
});
}
// This is for callback by the find-code popup.
// Appends to or erases the current list of related codes.
function set_related(codetype, code, selector, codedesc) {
let f = document.forms[0];
let s = f[rcvarname].value;
if (code) {
if (s.length > 0) s += ';';
s += codetype + ':' + code;
} else {
s = '';
}
f[rcvarname].value = s;
}
// This invokes the find-code popup.
function sel_related(varname) {
rcvarname = varname;
// codetype is just to make things easier and avoid mistakes.
// Might be nice to have a lab parameter for acceptable code types.
// Also note the controlling script here runs from interface/patient_file/encounter/.
let title = '<?php echo xla("Select Diagnosis Codes"); ?>';
<?php /*echo attr(collect_codetypes("diagnosis", "csv")); */?>
dlgopen(top.webroot_url + '/interface/patient_file/encounter/find_code_dynamic.php', '_blank', 985, 750, '', title);
}
// This is for callback by the find-code popup.
// Returns the array of currently selected codes with each element in codetype:code format.
function get_related() {
return document.forms[0][rcvarname].value.split(';');
}
// This is for callback by the find-code popup.
// Deletes the specified codetype:code from the currently selected list.
function del_related(s) {
my_del_related(s, document.forms[0][rcvarname], false);
if (targetElement != '') {
targetElement.value = '';
}
}
var transmitting = false;
// Issue a Cancel/OK warning if a previously transmitted order is being transmitted again.
function validate(f, e) {
<?php if (!empty($row['date_transmitted'])) { ?>
if (transmitting) {
if (!confirm(<?php echo xlj('This order was already transmitted on') ?> +' ' +
<?php echo js_escape($row['date_transmitted']) ?> +'. ' +
<?php echo xlj('Are you sure you want to transmit it again?'); ?>)) {
return false;
}
}
<?php } ?>
$(".wait").removeClass('d-none');
top.restoreSession();
return true;
}
$(function () {
// calendars need to be available to init dynamically for procedure item adds.
initCalendars();
initDeletes();
initForm();
$(function () {
$.ajaxSetup({
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connected to network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
})
return false;
});
<?php if ($row['date_transmitted'] ?? '') { ?>
$("#summary").collapse("toggle");
<?php } ?>
});
function getDetails(e, id) {
top.restoreSession();
let f = document.forms[0];
let codeattr = 'form_proc_code[' + id + ']';
let codetitle = 'form_proc_type_desc[' + id + ']';
let code = f[codeattr].value;
let url = top.webroot_url + "/interface/procedure_tools/libs/labs_ajax.php";
url += "?action=code_detail)&code=" + encodeURIComponent(code) +
"&csrf_token_form=" + <?php echo js_url(CsrfUtils::collectCsrfToken()); ?>;
let title = <?php echo xlj("Test") ?> +": " + code + " " + f[codetitle].value;
dlgopen(url, 'details', 'modal-md', 200, '', title, {
buttons: [
{text: '<?php echo xla('Got It'); ?>', close: true, style: 'secondary btn-sm'}
]
});
}
function initForm(reload = false) {
if (reload) {
location.reload();
}
$(".ammon").hide();
$(".quest").hide();
$(".labcorp").hide();
$(".clarity").hide();
$(".defaultProcedure").hide();
if (currentLab === 'ammon') {
$(".ammon").show();
} else if (currentLab === 'quest') {
$(".quest").show();
} else if (currentLab === 'labcorp') {
$(".labcorp").show();
} else if (currentLab === 'clarity') {
$(".clarity").show();
} else if (currentLab === '') {
$(".defaultProcedure").show();
}
if (oeUI.reasonCodeWidget) {
oeUI.reasonCodeWidget.reload();
}
}
function createLabels(e) {
e.preventDefault();
let prmt = <?php echo js_escape(xla("How many sets of specimen labels to create?") .
"\n" . xla("Each test in order gets a label.")); ?>;
let count = prompt(prmt, '1');
if (!count) return false;
let tarray = "";
let f = document.forms[0];
let transport = '';
let i = 0;
for (; f['form_transport[' + i + ']']; ++i) {
transport = f['form_transport[' + i + ']'].value;
transport = transport > '' ? transport : 'none';
tarray += transport + ";";
}
let printer = 'file';
let acctid = <?php echo js_escape($gbl_client_acct); ?>;
let order = f.id.value;
let patient = <?php echo js_escape($patient['lname'] . ', ' . $patient['fname'] . ' ' . $patient['mname']); ?>;
let dob = <?php echo js_escape($patient['DOB']); ?>;
let pid = <?php echo js_escape($patient['pid']); ?>;
let url = top.webroot_url + "/interface/procedure_tools/libs/labs_ajax.php";
// this escapes above
let uri = "?action=print_labels&count=" + encodeURIComponent(count) + "&order=" + encodeURIComponent(order) + "&pid=" + encodeURIComponent(pid) +
"&acctid=" + encodeURIComponent(acctid) + "&patient=" + encodeURIComponent(patient) + "&specimen=" + encodeURIComponent(tarray) +
"&dob=" + encodeURIComponent(dob) +
"&csrf_token_form=" + <?php echo js_url(CsrfUtils::collectCsrfToken()); ?>;
// retrieve the labels
dlgopen(url + uri, 'pdf', 'modal-md', 750, '');
}
function doWait(e) {
$(".wait").removeClass('d-none');