fix: send lists.pid into allergy Service for dashboard allergies (#6725)
[openemr.git] / interface / patient_file / summary / demographics.php
blobb5ef5d91fe6e17dd9c1d4d8ac78e76bf1fdd13b4
1 <?php
3 /**
5 * Patient summary screen.
7 * @package OpenEMR
8 * @link http://www.open-emr.org
9 * @author Brady Miller <brady.g.miller@gmail.com>
10 * @author Sharon Cohen <sharonco@matrix.co.il>
11 * @author Stephen Waite <stephen.waite@cmsvt.com>
12 * @author Ranganath Pathak <pathak@scrs1.org>
13 * @author Tyler Wrenn <tyler@tylerwrenn.com>
14 * @author Robert Down <robertdown@live.com>
15 * @copyright Copyright (c) 2017-2020 Brady Miller <brady.g.miller@gmail.com>
16 * @copyright Copyright (c) 2017 Sharon Cohen <sharonco@matrix.co.il>
17 * @copyright Copyright (c) 2018-2020 Stephen Waite <stephen.waite@cmsvt.com>
18 * @copyright Copyright (c) 2018 Ranganath Pathak <pathak@scrs1.org>
19 * @copyright Copyright (c) 2020 Tyler Wrenn <tyler@tylerwrenn.com>
20 * @copyright Copyright (c) 2021-2022 Robert Down <robertdown@live.com
21 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
24 require_once("../../globals.php");
25 require_once("$srcdir/patient.inc.php");
26 require_once("$srcdir/options.inc.php");
27 require_once("../history/history.inc.php");
28 require_once("$srcdir/clinical_rules.php");
29 require_once("$srcdir/group.inc.php");
30 require_once(__DIR__ . "/../../../library/appointments.inc.php");
32 use OpenEMR\Billing\EDI270;
33 use OpenEMR\Common\Acl\AclMain;
34 use OpenEMR\Common\Csrf\CsrfUtils;
35 use OpenEMR\Common\Session\SessionUtil;
36 use OpenEMR\Common\Twig\TwigContainer;
37 use OpenEMR\Core\Header;
38 use OpenEMR\Events\Patient\Summary\Card\RenderEvent as CardRenderEvent;
39 use OpenEMR\Events\Patient\Summary\Card\SectionEvent;
40 use OpenEMR\Events\Patient\Summary\Card\RenderModel;
41 use OpenEMR\Events\Patient\Summary\Card\CardInterface;
42 use OpenEMR\Events\PatientDemographics\ViewEvent;
43 use OpenEMR\Events\PatientDemographics\RenderEvent;
44 use OpenEMR\FHIR\SMART\SmartLaunchController;
45 use OpenEMR\Menu\PatientMenuRole;
46 use OpenEMR\OeUI\OemrUI;
47 use OpenEMR\Patient\Cards\PortalCard;
48 use OpenEMR\Reminder\BirthdayReminder;
49 use OpenEMR\Services\AllergyIntoleranceService;
50 use OpenEMR\Services\ConditionService;
51 use OpenEMR\Services\ImmunizationService;
52 use OpenEMR\Services\PatientIssuesService;
53 use OpenEMR\Services\PatientService;
54 use Symfony\Component\EventDispatcher\EventDispatcher;
56 $twig = new TwigContainer(null, $GLOBALS['kernel']);
58 // Set session for pid (via setpid). Also set session for encounter (if applicable)
59 if (isset($_GET['set_pid'])) {
60 require_once("$srcdir/pid.inc.php");
61 setpid($_GET['set_pid']);
62 $ptService = new PatientService();
63 $newPatient = $ptService->findByPid($pid);
64 $ptService->touchRecentPatientList($newPatient);
65 if (isset($_GET['set_encounterid']) && ((int)$_GET['set_encounterid'] > 0)) {
66 $encounter = (int)$_GET['set_encounterid'];
67 SessionUtil::setSession('encounter', $encounter);
71 // Note: it would eventually be a good idea to move this into
72 // it's own module that people can remove / add if they don't
73 // want smart support in their system.
74 $smartLaunchController = new SMARTLaunchController($GLOBALS["kernel"]->getEventDispatcher());
75 $smartLaunchController->registerContextEvents();
77 /**
78 * @var EventDispatcher
80 $ed = $GLOBALS['kernel']->getEventDispatcher();
82 $active_reminders = false;
83 $all_allergy_alerts = false;
84 if ($GLOBALS['enable_cdr']) {
85 //CDR Engine stuff
86 if ($GLOBALS['enable_allergy_check'] && $GLOBALS['enable_alert_log']) {
87 //Check for new allergies conflicts and throw popup if any exist(note need alert logging to support this)
88 $new_allergy_alerts = allergy_conflict($pid, 'new', $_SESSION['authUser']);
89 if (!empty($new_allergy_alerts)) {
90 $pod_warnings = '';
91 foreach ($new_allergy_alerts as $new_allergy_alert) {
92 $pod_warnings .= js_escape($new_allergy_alert) . ' + "\n"';
94 $allergyWarningMessage = '<script>alert(' . xlj('WARNING - FOLLOWING ACTIVE MEDICATIONS ARE ALLERGIES') . ' + "\n" + ' . $pod_warnings . ')</script>';
98 if ((empty($_SESSION['alert_notify_pid']) || ($_SESSION['alert_notify_pid'] != $pid)) && isset($_GET['set_pid']) && $GLOBALS['enable_cdr_crp']) {
99 // showing a new patient, so check for active reminders and allergy conflicts, which use in active reminder popup
100 $active_reminders = active_alert_summary($pid, "reminders-due", '', 'default', $_SESSION['authUser'], true);
101 if ($GLOBALS['enable_allergy_check']) {
102 $all_allergy_alerts = allergy_conflict($pid, 'all', $_SESSION['authUser'], true);
105 SessionUtil::setSession('alert_notify_pid', $pid);
106 // can not output html until after above setSession call
107 if (!empty($allergyWarningMessage)) {
108 echo $allergyWarningMessage;
111 //Check to see is only one insurance is allowed
112 if ($GLOBALS['insurance_only_one']) {
113 $insurance_array = array('primary');
114 } else {
115 $insurance_array = array('primary', 'secondary', 'tertiary');
118 function print_as_money($money)
120 preg_match("/(\d*)\.?(\d*)/", $money, $moneymatches);
121 $tmp = wordwrap(strrev($moneymatches[1]), 3, ",", 1);
122 $ccheck = strrev($tmp);
123 if ($ccheck[0] == ",") {
124 $tmp = substr($ccheck, 1, strlen($ccheck) - 1);
127 if ($moneymatches[2] != "") {
128 return "$ " . strrev($tmp) . "." . $moneymatches[2];
129 } else {
130 return "$ " . strrev($tmp);
134 // get an array from Photos category
135 function pic_array($pid, $picture_directory)
137 $pics = array();
138 $sql_query = "select documents.id from documents join categories_to_documents " .
139 "on documents.id = categories_to_documents.document_id " .
140 "join categories on categories.id = categories_to_documents.category_id " .
141 "where categories.name like ? and documents.foreign_id = ? and documents.deleted = 0";
142 if ($query = sqlStatement($sql_query, array($picture_directory, $pid))) {
143 while ($results = sqlFetchArray($query)) {
144 array_push($pics, $results['id']);
148 return ($pics);
151 // Get the document ID's in a specific catg.
152 // this is only used in one place, here for id photos
153 function get_document_by_catg($pid, $doc_catg, $limit = 1)
155 $results = null;
157 if ($pid and $doc_catg) {
158 $query = sqlStatement("SELECT d.id, d.date, d.url
159 FROM documents AS d, categories_to_documents AS cd, categories AS c
160 WHERE d.foreign_id = ?
161 AND cd.document_id = d.id
162 AND c.id = cd.category_id
163 AND c.name LIKE ?
164 ORDER BY d.date DESC LIMIT " . escape_limit($limit), array($pid, $doc_catg));
166 while ($result = sqlFetchArray($query)) {
167 $results[] = $result['id'];
169 return ($results ?? false);
172 function isPortalEnabled(): bool
174 if (
175 !$GLOBALS['portal_onsite_two_enable']
177 return false;
180 return true;
183 function isPortalSiteAddressValid(): bool
185 if (
186 // maybe can use filter_var() someday but the default value in GLOBALS
187 // fails with FILTER_VALIDATE_URL
188 !isset($GLOBALS['portal_onsite_two_address'])
190 return false;
193 return true;
196 function isPortalAllowed($pid): bool
198 $return = false;
200 $portalStatus = sqlQuery("SELECT allow_patient_portal FROM patient_data WHERE pid = ?", [$pid]);
201 if ($portalStatus['allow_patient_portal'] == 'YES') {
202 $return = true;
204 return $return;
207 function isApiAllowed($pid): bool
209 $return = false;
211 $apiStatus = sqlQuery("SELECT prevent_portal_apps FROM patient_data WHERE pid = ?", [$pid]);
212 if (strtoupper($apiStatus['prevent_portal_apps'] ?? '') != 'YES') {
213 $return = true;
215 return $return;
218 function areCredentialsCreated($pid): bool
220 $return = false;
221 $credentialsCreated = sqlQuery("SELECT date_created FROM `patient_access_onsite` WHERE `pid`=?", [$pid]);
222 if ($credentialsCreated['date_created'] ?? null) {
223 $return = true;
226 return $return;
229 function isContactEmail($pid): bool
231 $return = false;
233 $email = sqlQuery("SELECT email, email_direct FROM patient_data WHERE pid = ?", [$pid]);
234 if (!empty($email['email']) || !empty($email['email_direct'])) {
235 $return = true;
237 return $return;
240 function isEnforceSigninEmailPortal(): bool
242 if (
243 $GLOBALS['enforce_signin_email']
245 return true;
248 return false;
251 function deceasedDays($days_deceased)
253 $deceased_days = intval($days_deceased['days_deceased'] ?? '');
254 if ($deceased_days == 0) {
255 $num_of_days = xl("Today");
256 } elseif ($deceased_days == 1) {
257 $num_of_days = $deceased_days . " " . xl("day ago");
258 } elseif ($deceased_days > 1 && $deceased_days < 90) {
259 $num_of_days = $deceased_days . " " . xl("days ago");
260 } elseif ($deceased_days >= 90 && $deceased_days < 731) {
261 $num_of_days = "~" . round($deceased_days / 30) . " " . xl("months ago"); // function intdiv available only in php7
262 } elseif ($deceased_days >= 731) {
263 $num_of_days = xl("More than") . " " . round($deceased_days / 365) . " " . xl("years ago");
266 if (strlen($days_deceased['date_deceased'] ?? '') > 10 && $GLOBALS['date_display_format'] < 1) {
267 $deceased_date = substr($days_deceased['date_deceased'], 0, 10);
268 } else {
269 $deceased_date = oeFormatShortDate($days_deceased['date_deceased'] ?? '');
272 return xlt("Deceased") . " - " . text($deceased_date) . " (" . text($num_of_days) . ")";
275 $deceased = is_patient_deceased($pid);
278 // Display image in 'widget style'
279 function image_widget($doc_id, $doc_catg)
281 global $pid, $web_root;
282 $docobj = new Document($doc_id);
283 $image_file = $docobj->get_url_file();
284 $image_file_name = $docobj->get_name();
285 $image_width = $GLOBALS['generate_doc_thumb'] == 1 ? '' : 'width=100';
286 $extension = substr($image_file_name, strrpos($image_file_name, "."));
287 $viewable_types = array('.png', '.jpg', '.jpeg', '.png', '.bmp', '.PNG', '.JPG', '.JPEG', '.PNG', '.BMP');
288 if (in_array($extension, $viewable_types)) { // extension matches list
289 $to_url = "<td> <a href = '$web_root" .
290 "/controller.php?document&retrieve&patient_id=" . attr_url($pid) . "&document_id=" . attr_url($doc_id) . "&as_file=false&original_file=true&disable_exit=false&show_original=true'" .
291 " onclick='top.restoreSession();' class='image_modal'>" .
292 " <img src = '$web_root" .
293 "/controller.php?document&retrieve&patient_id=" . attr_url($pid) . "&document_id=" . attr_url($doc_id) . "&as_file=false'" .
294 " $image_width alt='" . attr($doc_catg) . ":" . attr($image_file_name) . "'> </a> </td> <td class='align-middle'>" .
295 text($doc_catg) . '<br />&nbsp;' . text($image_file_name) . "</td>";
296 } else {
297 $to_url = "<td> <a href='" . $web_root . "/controller.php?document&retrieve" .
298 "&patient_id=" . attr_url($pid) . "&document_id=" . attr_url($doc_id) . "'" .
299 " onclick='top.restoreSession()' class='btn btn-primary btn-sm'>" .
300 "<span>" .
301 xlt("View") . "</a> &nbsp;" .
302 text("$doc_catg - $image_file_name") .
303 "</span> </td>";
306 echo "<table><tr>";
307 echo $to_url;
308 echo "</tr></table>";
311 // Determine if the Vitals form is in use for this site.
312 $tmp = sqlQuery("SELECT count(*) AS count FROM registry WHERE directory = 'vitals' AND state = 1");
313 $vitals_is_registered = $tmp['count'];
315 // Get patient/employer/insurance information.
317 $result = getPatientData($pid, "*, DATE_FORMAT(DOB,'%Y-%m-%d') as DOB_YMD");
318 $result2 = getEmployerData($pid);
319 $result3 = getInsuranceData(
320 $pid,
321 "primary",
322 "copay,
323 provider,
324 DATE_FORMAT(`date`,'%Y-%m-%d') as effdate,
325 DATE_FORMAT(`date_end`,'%Y-%m-%d') as effdate_end"
327 $insco_name = "";
328 if (!empty($result3['provider'])) { // Use provider in case there is an ins record w/ unassigned insco
329 $insco_name = getInsuranceProvider($result3['provider']);
332 $arrOeUiSettings = array(
333 'page_id' => 'core.mrd',
334 'heading_title' => xl('Medical Record Dashboard'),
335 'include_patient_name' => true,
336 'expandable' => true,
337 'expandable_files' => array(), //all file names need suffix _xpd
338 'action' => "", //conceal, reveal, search, reset, link or back
339 'action_title' => "",
340 'action_href' => "", //only for actions - reset, link or back
341 'show_help_icon' => true,
342 'help_file_name' => "medical_dashboard_help.php"
344 $oemr_ui = new OemrUI($arrOeUiSettings);
346 <!DOCTYPE html>
347 <html>
349 <head>
350 <?php
351 Header::setupHeader(['common']);
352 require_once("$srcdir/options.js.php");
354 <script>
355 // Process click on diagnosis for referential cds popup.
356 function referentialCdsClick(codetype, codevalue) {
357 top.restoreSession();
358 // Force a new window instead of iframe to address cross site scripting potential
359 dlgopen('../education.php?type=' + encodeURIComponent(codetype) + '&code=' + encodeURIComponent(codevalue), '_blank', 1024, 750,true);
362 function oldEvt(apptdate, eventid) {
363 let title = <?php echo xlj('Appointments'); ?>;
364 dlgopen('../../main/calendar/add_edit_event.php?date=' + encodeURIComponent(apptdate) + '&eid=' + encodeURIComponent(eventid), '_blank', 800, 500, '', title);
367 function advdirconfigure() {
368 dlgopen('advancedirectives.php', '_blank', 400, 500);
371 function refreshme() {
372 top.restoreSession();
373 location.reload();
376 // Process click on Delete link.
377 function deleteme() { // @todo don't think this is used any longer!!
378 dlgopen('../deleter.php?patient=' + <?php echo js_url($pid); ?> + '&csrf_token_form=' + <?php echo js_url(CsrfUtils::collectCsrfToken()); ?>, '_blank', 500, 450, '', '', {
379 allowResize: false,
380 allowDrag: false,
381 dialogId: 'patdel',
382 type: 'iframe'
384 return false;
387 // Called by the deleteme.php window on a successful delete.
388 function imdeleted() {
389 top.clearPatient();
392 function newEvt() {
393 let title = <?php echo xlj('Appointments'); ?>;
394 let url = '../../main/calendar/add_edit_event.php?patientid=' + <?php echo js_url($pid); ?>;
395 dlgopen(url, '_blank', 800, 500, '', title);
396 return false;
399 function getWeno() {
400 top.restoreSession();
401 location.href = '../../weno/indexrx.php'
404 function toggleIndicator(target, div) {
405 // <i id="show_hide" class="fa fa-lg small fa-eye-slash" title="Click to Hide"></i>
406 $mode = $(target).find(".indicator").text();
407 if ($mode == <?php echo xlj('collapse'); ?>) {
408 $(target).find(".indicator").text(<?php echo xlj('expand'); ?>);
409 $("#" + div).hide();
410 $.post("../../../library/ajax/user_settings.php", {
411 target: div,
412 mode: 0,
413 csrf_token_form: <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>
415 } else {
416 $(target).find(".indicator").text(<?php echo xlj('collapse'); ?>);
417 $("#" + div).show();
418 $.post("../../../library/ajax/user_settings.php", {
419 target: div,
420 mode: 1,
421 csrf_token_form: <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>
426 // edit prescriptions dialog.
427 // called from stats.php.
429 function editScripts(url) {
430 var AddScript = function() {
431 var __this = $(this);
432 __this.find("#clearButton").css("display", "");
433 __this.find("#backButton").css("display", "");
434 __this.find("#addButton").css("display", "none");
436 var iam = top.frames.editScripts;
437 iam.location.href = '<?php echo $GLOBALS['webroot'] ?>/controller.php?prescription&edit&id=0&pid=' + <?php echo js_url($pid); ?>;
439 var ListScripts = function() {
440 var __this = $(this);
441 __this.find("#clearButton").css("display", "none");
442 __this.find("#backButton").css("display", "none");
443 __this.find("#addButton").css("display", "");
444 var iam = top.frames.editScripts
445 iam.location.href = '<?php echo $GLOBALS['webroot'] ?>/controller.php?prescription&list&id=' + <?php echo js_url($pid); ?>;
448 let title = <?php echo xlj('Prescriptions'); ?>;
449 let w = 960; // for weno width
451 dlgopen(url, 'editScripts', w, 400, '', '', {
452 buttons: [{
453 text: <?php echo xlj('Add'); ?>,
454 close: false,
455 id: 'addButton',
456 class: 'btn-primary btn-sm',
457 click: AddScript
460 text: <?php echo xlj('Clear'); ?>,
461 close: false,
462 id: 'clearButton',
463 style: 'display:none;',
464 class: 'btn-primary btn-sm',
465 click: AddScript
468 text: <?php echo xlj('Back'); ?>,
469 close: false,
470 id: 'backButton',
471 style: 'display:none;',
472 class: 'btn-primary btn-sm',
473 click: ListScripts
476 text: <?php echo xlj('Quit'); ?>,
477 close: true,
478 id: 'doneButton',
479 class: 'btn-secondary btn-sm'
482 onClosed: 'refreshme',
483 allowResize: true,
484 allowDrag: true,
485 dialogId: 'editscripts',
486 type: 'iframe'
488 return false;
492 * async function fetchHtml(...)
494 * @param {*} url
495 * @param {boolean} embedded
496 * @param {boolean} sessionRestore
497 * @returns {text}
499 async function fetchHtml(url, embedded = false, sessionRestore = false) {
500 if (sessionRestore === true) {
501 // restore cookie before fetch.
502 top.restoreSession();
504 let csrf = new FormData;
505 // a security given.
506 csrf.append("csrf_token_form", <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>);
507 if (embedded === true) {
508 // special formatting in certain widgets.
509 csrf.append("embeddedScreen", true);
512 const response = await fetch(url, {
513 method: 'POST',
514 credentials: 'same-origin',
515 body: csrf
517 return await response.text();
521 * async function placeHtml(...) will await fetch of html then place in divId.
522 * This function will return a promise for use to init various items regarding
523 * inserted HTML if needed.
524 * If divId does not exist, then will skip.
525 * Example
527 * @param {*} url
528 * @param {string} divId id
529 * @param {boolean} embedded
530 * @param {boolean} sessionRestore
531 * @returns {object} promise
533 async function placeHtml(url, divId, embedded = false, sessionRestore = false) {
534 const contentDiv = document.getElementById(divId);
535 if (contentDiv) {
536 await fetchHtml(url, embedded, sessionRestore).then(fragment => {
537 contentDiv.innerHTML = fragment;
542 if (typeof load_location === 'undefined') {
543 function load_location(location) {
544 top.restoreSession();
545 document.location = location;
549 $(function() {
550 var msg_updation = '';
551 <?php
552 if ($GLOBALS['erx_enable']) {
553 $soap_status = sqlStatement("select soap_import_status,pid from patient_data where pid=? and soap_import_status in ('1','3')", array($pid));
554 while ($row_soapstatus = sqlFetchArray($soap_status)) { ?>
555 top.restoreSession();
556 $.ajax({
557 type: "POST",
558 url: "../../soap_functions/soap_patientfullmedication.php",
559 dataType: "html",
560 data: {
561 patient: <?php echo js_escape($row_soapstatus['pid']); ?>,
563 async: false,
564 success: function(thedata) {
565 //alert(thedata);
566 msg_updation += thedata;
568 error: function() {
569 alert('ajax error');
573 top.restoreSession();
574 $.ajax({
575 type: "POST",
576 url: "../../soap_functions/soap_allergy.php",
577 dataType: "html",
578 data: {
579 patient: <?php echo js_escape($row_soapstatus['pid']); ?>,
581 async: false,
582 success: function(thedata) {
583 //alert(thedata);
584 msg_updation += thedata;
586 error: function() {
587 alert('ajax error');
590 <?php
591 if ($GLOBALS['erx_import_status_message']) { ?>
592 if (msg_updation)
593 alert(msg_updation);
594 <?php
600 // load divs
601 placeHtml("stats.php", "stats_div", true);
602 placeHtml("pnotes_fragment.php", 'pnotes_ps_expand').then(() => {
603 // must be delegated event!
604 $(this).on("click", ".complete_btn", function() {
605 let btn = $(this);
606 let csrf = new FormData;
607 csrf.append("csrf_token_form", <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>);
608 fetch("pnotes_fragment.php?docUpdateId=" + encodeURIComponent(btn.attr('data-id')), {
609 method: "POST",
610 credentials: 'same-origin',
611 body: csrf
613 .then(function() {
614 placeHtml("pnotes_fragment.php", 'pnotes_ps_expand');
618 placeHtml("disc_fragment.php", "disclosures_ps_expand");
619 placeHtml("labdata_fragment.php", "labdata_ps_expand");
620 placeHtml("track_anything_fragment.php", "track_anything_ps_expand");
621 <?php if ($vitals_is_registered && AclMain::aclCheckCore('patients', 'med')) { ?>
622 // Initialize the Vitals form if it is registered and user is authorized.
623 placeHtml("vitals_fragment.php", "vitals_ps_expand");
624 <?php } ?>
626 <?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_crw']) { ?>
627 placeHtml("clinical_reminders_fragment.php", "clinical_reminders_ps_expand", true, true).then(() => {
628 // (note need to place javascript code here also to get the dynamic link to work)
629 $(".medium_modal").on('click', function(e) {
630 e.preventDefault();
631 e.stopPropagation();
632 dlgopen('', '', 800, 200, '', '', {
633 buttons: [{
634 text: <?php echo xlj('Close'); ?>,
635 close: true,
636 style: 'secondary btn-sm'
638 onClosed: 'refreshme',
639 allowResize: false,
640 allowDrag: true,
641 dialogId: 'demreminder',
642 type: 'iframe',
643 url: $(this).attr('href')
647 <?php } // end crw
650 <?php if ($GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_prw']) { ?>
651 placeHtml("patient_reminders_fragment.php", "patient_reminders_ps_expand", false, true);
652 <?php } // end prw
655 <?php
656 // Initialize for each applicable LBF form.
657 $gfres = sqlStatement("SELECT grp_form_id
658 FROM layout_group_properties
659 WHERE grp_form_id LIKE 'LBF%'
660 AND grp_group_id = ''
661 AND grp_repeats > 0
662 AND grp_activity = 1
663 ORDER BY grp_seq, grp_title");
664 while ($gfrow = sqlFetchArray($gfres)) { ?>
665 $(<?php echo js_escape("#" . $gfrow['grp_form_id'] . "_ps_expand"); ?>).load("lbf_fragment.php?formname=" + <?php echo js_url($gfrow['grp_form_id']); ?>, {
666 csrf_token_form: <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>
668 <?php } ?>
669 tabbify();
671 // modal for dialog boxes
672 $(".large_modal").on('click', function(e) {
673 e.preventDefault();
674 e.stopPropagation();
675 dlgopen('', '', 1000, 600, '', '', {
676 buttons: [{
677 text: <?php echo xlj('Close'); ?>,
678 close: true,
679 style: 'secondary btn-sm'
681 allowResize: true,
682 allowDrag: true,
683 dialogId: '',
684 type: 'iframe',
685 url: $(this).attr('href')
689 $(".rx_modal").on('click', function(e) {
690 e.preventDefault();
691 e.stopPropagation();
692 var title = <?php echo xlj('Amendments'); ?>;
693 dlgopen('', 'editAmendments', 800, 300, '', title, {
694 onClosed: 'refreshme',
695 allowResize: true,
696 allowDrag: true,
697 dialogId: '',
698 type: 'iframe',
699 url: $(this).attr('href')
703 // modal for image viewer
704 $(".image_modal").on('click', function(e) {
705 e.preventDefault();
706 e.stopPropagation();
707 dlgopen('', '', 400, 300, '', <?php echo xlj('Patient Images'); ?>, {
708 allowResize: true,
709 allowDrag: true,
710 dialogId: '',
711 type: 'iframe',
712 url: $(this).attr('href')
716 $(".deleter").on('click', function(e) {
717 e.preventDefault();
718 e.stopPropagation();
719 dlgopen('', '', 600, 360, '', '', {
720 buttons: [{
721 text: <?php echo xlj('Close'); ?>,
722 close: true,
723 style: 'secondary btn-sm'
725 //onClosed: 'imdeleted',
726 allowResize: false,
727 allowDrag: false,
728 dialogId: 'patdel',
729 type: 'iframe',
730 url: $(this).attr('href')
734 $(".iframe1").on('click', function(e) {
735 e.preventDefault();
736 e.stopPropagation();
737 dlgopen('', '', 350, 300, '', '', {
738 buttons: [{
739 text: <?php echo xlj('Close'); ?>,
740 close: true,
741 style: 'secondary btn-sm'
743 allowResize: true,
744 allowDrag: true,
745 dialogId: '',
746 type: 'iframe',
747 url: $(this).attr('href')
750 // for patient portal
751 $(".small_modal").on('click', function(e) {
752 e.preventDefault();
753 e.stopPropagation();
754 dlgopen('', '', 550, 550, '', '', {
755 buttons: [{
756 text: <?php echo xlj('Close'); ?>,
757 close: true,
758 style: 'secondary btn-sm'
760 allowResize: true,
761 allowDrag: true,
762 dialogId: '',
763 type: 'iframe',
764 url: $(this).attr('href')
768 function openReminderPopup() {
769 top.restoreSession()
770 dlgopen('', 'reminders', 500, 250, '', '', {
771 buttons: [{
772 text: <?php echo xlj('Close'); ?>,
773 close: true,
774 style: 'secondary btn-sm'
776 allowResize: true,
777 allowDrag: true,
778 dialogId: '',
779 type: 'iframe',
780 url: $("#reminder_popup_link").attr('href')
784 <?php if ($GLOBALS['patient_birthday_alert']) {
785 // To display the birthday alert:
786 // 1. The patient is not deceased
787 // 2. The birthday is today (or in the past depending on global selection)
788 // 3. The notification has not been turned off (or shown depending on global selection) for this year
789 $birthdayAlert = new BirthdayReminder($pid, $_SESSION['authUserID']);
790 if ($birthdayAlert->isDisplayBirthdayAlert()) {
792 // show the active reminder modal
793 dlgopen('', 'bdayreminder', 300, 170, '', false, {
794 allowResize: false,
795 allowDrag: true,
796 dialogId: '',
797 type: 'iframe',
798 url: $("#birthday_popup").attr('href')
801 <?php } elseif ($active_reminders || $all_allergy_alerts) { ?>
802 openReminderPopup();
803 <?php } ?>
804 <?php } elseif ($active_reminders || $all_allergy_alerts) { ?>
805 openReminderPopup();
806 <?php } ?>
808 // $(".card-title").on('click', "button", (e) => {
809 // console.debug("click");
810 // updateUserVisibilitySetting(e);
811 // });
815 * Change the preference to expand/collapse a given card.
817 * For the given e element, find the corresponding card body, determine if it is collapsed
818 * or shown, and then save the state to the user preferences via an async fetch call POST'ing
819 * the updated setting.
821 * @var e element The Button that was clicked to collapse/expand the card
823 async function updateUserVisibilitySetting(e) {
824 const targetID = e.target.getAttribute("data-target");
825 const target = document.querySelector(targetID);
826 const targetStr = targetID.substring(1);
828 let formData = new FormData();
829 formData.append("csrf_token_form", <?php echo js_escape(CsrfUtils::collectCsrfToken()); ?>);
830 formData.append("target", targetStr);
831 formData.append("mode", (target.classList.contains("show")) ? 0 : 1);
833 const response = await fetch("../../../library/ajax/user_settings.php", {
834 method: "POST",
835 credentials: 'same-origin',
836 body: formData,
839 const update = await response.text();
840 return update;
843 // Update the User's visibility setting when the card header is clicked
844 function cardTitleButtonClickListener() {
845 const buttons = document.querySelectorAll(".card-title a[data-toggle='collapse']");
846 buttons.forEach((b) => {
847 b.addEventListener("click", (e) => {
848 updateUserVisibilitySetting(e);
853 // JavaScript stuff to do when a new patient is set.
855 function setMyPatient() {
856 <?php
857 if (isset($_GET['set_pid'])) {
858 $date_of_death = is_patient_deceased($pid);
859 if (!empty($date_of_death)) {
860 $date_of_death = $date_of_death['date_deceased'];
863 parent.left_nav.setPatient(<?php echo js_escape($result['fname'] . " " . $result['lname']) .
864 "," . js_escape($pid) . "," . js_escape($result['pubpid']) . ",'',";
865 if (empty($date_of_death)) {
866 echo js_escape(" " . xl('DOB') . ": " . oeFormatShortDate($result['DOB_YMD']) . " " . xl('Age') . ": " . getPatientAgeDisplay($result['DOB_YMD']));
867 } else {
868 echo js_escape(" " . xl('DOB') . ": " . oeFormatShortDate($result['DOB_YMD']) . " " . xl('Age at death') . ": " . oeFormatAge($result['DOB_YMD'], $date_of_death));
869 } ?>);
870 var EncounterDateArray = new Array;
871 var CalendarCategoryArray = new Array;
872 var EncounterIdArray = new Array;
873 var Count = 0;
874 <?php
875 //Encounter details are stored to javacript as array.
876 $result4 = sqlStatement("SELECT fe.encounter,fe.date,openemr_postcalendar_categories.pc_catname FROM form_encounter AS fe " .
877 " left join openemr_postcalendar_categories on fe.pc_catid=openemr_postcalendar_categories.pc_catid WHERE fe.pid = ? order by fe.date desc", array($pid));
878 if (sqlNumRows($result4) > 0) {
879 while ($rowresult4 = sqlFetchArray($result4)) { ?>
880 EncounterIdArray[Count] = <?php echo js_escape($rowresult4['encounter']); ?>;
881 EncounterDateArray[Count] = <?php echo js_escape(oeFormatShortDate(date("Y-m-d", strtotime($rowresult4['date'])))); ?>;
882 CalendarCategoryArray[Count] = <?php echo js_escape(xl_appt_category($rowresult4['pc_catname'])); ?>;
883 Count++;
884 <?php
888 parent.left_nav.setPatientEncounter(EncounterIdArray, EncounterDateArray, CalendarCategoryArray);
889 <?php
890 } // end setting new pid
892 parent.left_nav.syncRadios();
893 <?php if ((isset($_GET['set_pid'])) && (isset($_GET['set_encounterid'])) && (intval($_GET['set_encounterid']) > 0)) {
894 $query_result = sqlQuery("SELECT `date` FROM `form_encounter` WHERE `encounter` = ?", array($encounter)); ?>
895 encurl = 'encounter/encounter_top.php?set_encounter=' + <?php echo js_url($encounter); ?> + '&pid=' + <?php echo js_url($pid); ?>;
896 parent.left_nav.setEncounter(<?php echo js_escape(oeFormatShortDate(date("Y-m-d", strtotime($query_result['date'])))); ?>, <?php echo js_escape($encounter); ?>, 'enc');
897 top.restoreSession();
898 parent.left_nav.loadFrame('enc2', 'enc', 'patient_file/' + encurl);
899 <?php } // end setting new encounter id (only if new pid is also set)
903 $(window).on('load', function() {
904 setMyPatient();
907 document.addEventListener("DOMContentLoaded", () => {
908 cardTitleButtonClickListener();
910 </script>
912 <style>
913 /* Bad practice to override here, will get moved to base style theme */
914 .card {
915 box-shadow: 1px 1px 1px hsl(0 0% 0% / .2);
916 border-radius: 0;
919 /* Short term fix. This ensures the problem list, allergies, medications, and immunization cards handle long lists without interuppting
920 the UI. This should be configurable and should go in a more appropriate place */
921 .pami-list {
922 max-height: 200px;
923 overflow-y: scroll;
926 <?php
927 if (!empty($GLOBALS['right_justify_labels_demographics']) && ($_SESSION['language_direction'] == 'ltr')) { ?>
928 div.tab td.label_custom, div.label_custom {
929 text-align: right !important;
932 div.tab td.data, div.data {
933 padding-left: 0.5em;
934 padding-right: 2em;
936 <?php
937 } ?>
939 <?php
940 // This is for layout font size override.
941 $grparr = array();
942 getLayoutProperties('DEM', $grparr, 'grp_size');
943 if (!empty($grparr['']['grp_size'])) {
944 $FONTSIZE = round($grparr['']['grp_size'] * 1.333333);
945 $FONTSIZE = round($FONTSIZE * 0.0625, 2);
948 /* Override font sizes in the theme. */
949 #DEM .groupname {
950 font-size: <?php echo attr($FONTSIZE); ?>rem;
953 #DEM .label {
954 font-size: <?php echo attr($FONTSIZE); ?>rem;
957 #DEM .data {
958 font-size: <?php echo attr($FONTSIZE); ?>rem;
961 #DEM .data td {
962 font-size: <?php echo attr($FONTSIZE); ?>rem;
965 <?php } ?> :root {
966 --white: #fff;
967 --bg: hsl(0 0% 90%);
970 body {
971 background: var(--bg) !important;
974 section {
975 background: var(--white);
976 margin-top: .25em;
977 padding: .25em;
980 .section-header-dynamic {
981 border-bottom: none;
983 </style>
984 <title><?php echo xlt("Dashboard{{patient file}}"); ?></title>
985 </head>
987 <body class="mt-1 patient-demographic bg-light">
989 <?php
990 // Create and fire the patient demographics view event
991 $viewEvent = new ViewEvent($pid);
992 $viewEvent = $GLOBALS["kernel"]->getEventDispatcher()->dispatch($viewEvent, ViewEvent::EVENT_HANDLE, 10);
993 $thisauth = AclMain::aclCheckCore('patients', 'demo');
995 if (!$thisauth || !$viewEvent->authorized()) {
996 echo $twig->getTwig()->render('core/unauthorized-partial.html.twig', ['pageTitle' => xl("Medical Dashboard")]);
997 exit();
1001 <div id="container_div" class="<?php echo $oemr_ui->oeContainer(); ?> mb-2">
1002 <a href='../reminder/active_reminder_popup.php' id='reminder_popup_link' style='display: none' onclick='top.restoreSession()'></a>
1003 <a href='../birthday_alert/birthday_pop.php?pid=<?php echo attr_url($pid); ?>&user_id=<?php echo attr_url($_SESSION['authUserID']); ?>' id='birthday_popup' style='display: none;' onclick='top.restoreSession()'></a>
1004 <?php
1006 if ($thisauth) {
1007 if ($result['squad'] && !AclMain::aclCheckCore('squads', $result['squad'])) {
1008 $thisauth = 0;
1012 if ($thisauth) :
1013 require_once("$include_root/patient_file/summary/dashboard_header.php");
1014 endif;
1016 $list_id = "dashboard"; // to indicate nav item is active, count and give correct id
1017 // Collect the patient menu then build it
1018 $menuPatient = new PatientMenuRole($twig);
1019 $menuPatient->displayHorizNavBarMenu();
1020 // Get the document ID of the patient ID card if access to it is wanted here.
1021 $idcard_doc_id = false;
1022 if ($GLOBALS['patient_id_category_name']) {
1023 $idcard_doc_id = get_document_by_catg($pid, $GLOBALS['patient_id_category_name'], 3);
1026 <div class="main mb-1">
1027 <!-- start main content div -->
1028 <div class="row">
1029 <?php
1030 $t = $twig->getTwig();
1032 $allergy = (AclMain::aclCheckIssue('allergy')) ? 1 : 0;
1033 $pl = (AclMain::aclCheckIssue('medical_problem')) ? 1 : 0;
1034 $meds = (AclMain::aclCheckIssue('medication')) ? 1 : 0;
1035 $cards = $allergy + $pl + $meds;
1036 $col = "p-1 ";
1038 switch ($cards) {
1039 case '1':
1040 $col .= "col-12";
1041 break;
1043 case '2':
1044 $col .= "col-6";
1045 break;
1047 case '3':
1048 $col .= "col-4";
1049 break;
1051 default:
1052 $col .= "col";
1053 break;
1057 * Helper function to return only issues with an outcome not equal to resolved
1059 * @param array $i An array of issues
1060 * @return array
1062 function filterActiveIssues(array $i): array
1064 return array_filter($i, function ($_i) {
1065 return $_i['outcome'] != 1;
1069 // ALLERGY CARD
1070 if (AclMain::aclCheckIssue('allergy')) {
1071 $allergyService = new AllergyIntoleranceService();
1072 $_rawAllergies = filterActiveIssues($allergyService->getAll(['lists.pid' => $pid])->getData());
1073 $_priority = [];
1074 $_standard = [];
1075 foreach ($_rawAllergies as $_) {
1076 if (in_array($_['severity_al'], ['severe', 'life_threatening_severity', 'fatal'])) {
1077 $_priority[] = $_;
1078 } else {
1079 $_standard[] = $_;
1083 $viewArgs = [
1084 'title' => xl('Allergies'),
1085 'card_container_class_list' => ['flex-fill', 'mx-1'],
1086 'id' => 'allergies_ps_expand',
1087 'forceAlwaysOpen' => false,
1088 'linkMethod' => "javascript",
1089 'list' => ['priority' => $_priority, 'standard' => $_standard],
1090 'auth' => true,
1091 'btnLabel' => 'Edit',
1092 'btnLink' => "return load_location('{$GLOBALS['webroot']}/interface/patient_file/summary/stats_full.php?active=all&category=allergy')"
1094 echo "<div class=\"$col\">";
1095 echo $t->render('patient/card/allergies.html.twig', $viewArgs);
1096 echo "</div>";
1099 $patIssueService = new PatientIssuesService();
1101 // MEDICAL PROBLEMS CARD
1102 if (AclMain::aclCheckIssue('medical_problem')) {
1103 $_rawPL = $patIssueService->search(['lists.pid' => $pid, 'lists.type' => 'medical_problem'])->getData();
1104 $viewArgs = [
1105 'title' => xl('Medical Problems'),
1106 'card_container_class_list' => ['flex-fill', 'mx-1'],
1107 'id' => 'medical_problem_ps_expand',
1108 'forceAlwaysOpen' => false,
1109 'linkMethod' => "javascript",
1110 'list' => filterActiveIssues($_rawPL),
1111 'auth' => true,
1112 'btnLabel' => 'Edit',
1113 'btnLink' => "return load_location('{$GLOBALS['webroot']}/interface/patient_file/summary/stats_full.php?active=all&category=medical_problem')"
1115 echo "<div class=\"$col\">";
1116 echo $t->render('patient/card/medical_problems.html.twig', $viewArgs);
1117 echo "</div>";
1120 // MEDICATION CARD
1121 if (AclMain::aclCheckIssue('medication')) {
1122 $_rawMedList = $patIssueService->search(['lists.pid' => $pid, 'lists.type' => 'medication'])->getData();
1123 $viewArgs = [
1124 'title' => xl('Medications'),
1125 'card_container_class_list' => ['flex-fill', 'mx-1'],
1126 'id' => 'medications_ps_expand',
1127 'forceAlwaysOpen' => false,
1128 'linkMethod' => "javascript",
1129 'list' => filterActiveIssues($_rawMedList),
1130 'auth' => true,
1131 'btnLabel' => 'Edit',
1132 'btnLink' => "return load_location('{$GLOBALS['webroot']}/interface/patient_file/summary/stats_full.php?active=all&category=medication')"
1134 echo "<div class=\"$col\">";
1135 echo $t->render('patient/card/medication.html.twig', $viewArgs);
1136 echo "</div>";
1139 // Render the Prescriptions card if turned on
1140 if (!$GLOBALS['disable_prescriptions'] && AclMain::aclCheckCore('patients', 'rx')) :
1141 if ($GLOBALS['erx_enable'] && $display_current_medications_below == 1) {
1142 $sql = "SELECT * FROM prescriptions WHERE patient_id = ? AND active = '1'";
1143 $res = sqlStatement($sql, [$pid]);
1145 $rxArr = [];
1146 while ($row = sqlFetchArray($res)) {
1147 $row['unit'] = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_units'), $row['unit']);
1148 $row['form'] = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_form'), $row['form']);
1149 $row['route'] = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_route'), $row['route']);
1150 $row['interval'] = generate_display_field(array('data_type' => '1', 'list_id' => 'drug_interval'), $row['interval']);
1151 $rxArr[] = $row;
1153 $id = "current_prescriptions_ps_expand";
1154 $viewArgs = [
1155 'title' => xl('Current Medications'),
1156 'id' => $id,
1157 'forceAlwaysOpen' => (getUserSetting($id) == 0) ? false : true,
1158 'auth' => false,
1159 'rxList' => $rxArr,
1162 echo $t->render('patient/card/erx.html.twig', $viewArgs);
1165 $id = "prescriptions_ps_expand";
1166 $viewArgs = [
1167 'title' => xl("Prescriptions"),
1168 'card_container_class_list' => ['flex-fill', 'mx-1'],
1169 'id' => $id,
1170 'forceAlwaysOpen' => (getUserSetting($id) == 0) ? false : true,
1171 'btnLabel' => "Edit",
1172 'auth' => AclMain::aclCheckCore('patients', 'rx', '', ['write', 'addonly']),
1175 if ($GLOBALS['erx_enable']) {
1176 $viewArgs['title'] = 'Prescription History';
1177 $viewArgs['btnLabel'] = 'Add';
1178 $viewArgs['btnLink'] = "{$GLOBALS['webroot']}/interface/eRx.php?page=compose";
1179 } elseif ($GLOBALS['weno_rx_enable']) {
1180 // weno plus button which opens their iframe
1181 $viewArgs['weno'] = true;
1182 $viewArgs['title'] = "WENO ComposeRx";
1183 $viewArgs['btnLabel'] = 'Add';
1184 $viewArgs['btnLink'] = "{$GLOBALS['webroot']}/interface/weno/indexrx.php";
1185 $viewArgs['btnClass'] = "iframe";
1186 $viewArgs['linkMethod'] = "javascript";
1187 $viewArgs['btnLink'] = "editScripts('{$GLOBALS['webroot']}/controller.php?prescription&list&id=" . attr_url($pid) . "')";
1188 } else {
1189 $viewArgs['btnLink'] = "editScripts('{$GLOBALS['webroot']}/controller.php?prescription&list&id=" . attr_url($pid) . "')";
1190 $viewArgs['linkMethod'] = "javascript";
1191 $viewArgs['btnClass'] = "iframe";
1194 $cwd = getcwd();
1195 chdir("../../../");
1196 $c = new Controller();
1197 // This is a hacky way to get a Smarty template from the controller and injecting it into
1198 // a Twig template. This reduces the amount of refactoring that is required but ideally the
1199 // Smarty template should be upgraded to Twig
1200 ob_start();
1201 echo $c->act(['prescription' => '', 'fragment' => '', 'patient_id' => $pid]);
1202 $viewArgs['content'] = ob_get_contents();
1203 ob_end_clean();
1205 echo $t->render('patient/card/rx.html.twig', $viewArgs);
1206 endif;
1208 </div>
1209 </div>
1210 <div class="row">
1211 <div class="col-md-8">
1212 <?php
1213 if ($deceased > 0) :
1214 echo $twig->getTwig()->render('patient/partials/deceased.html.twig', [
1215 'deceasedDays' => deceasedDays($deceased),
1217 endif;
1219 $sectionRenderEvents = $ed->dispatch(new SectionEvent('primary'), SectionEvent::EVENT_HANDLE);
1220 $sectionCards = $sectionRenderEvents->getCards();
1222 foreach ($sectionCards as $card) {
1223 $_auth = $card->getAcl();
1224 if (!AclMain::aclCheckCore($_auth[0], $_auth[1])) {
1225 continue;
1228 $btnLabel = false;
1229 if ($card->canAdd()) {
1230 $btnLabel = 'Add';
1231 } elseif ($card->canEdit()) {
1232 $btnLabel = 'Edit';
1235 $viewArgs = [
1236 'title' => $card->getTitle(),
1237 'id' => $card->getIdentifier(),
1238 'initiallyCollapsed' => !$card->isInitiallyCollapsed(),
1239 'card_bg_color' => $card->getBackgroundColorClass(),
1240 'card_text_color' => $card->getTextColorClass(),
1241 'forceAlwaysOpen' => !$card->canCollapse(),
1242 'btnLabel' => $btnLabel,
1243 'btnLink' => 'test',
1246 echo $t->render($card->getTemplateFile(), array_merge($card->getTemplateVariables(), $viewArgs));
1249 if (!$GLOBALS['hide_billing_widget']) :
1250 $forceBillingExpandAlways = ($GLOBALS['force_billing_widget_open']) ? true : false;
1251 $patientbalance = get_patient_balance($pid, false);
1252 $insurancebalance = get_patient_balance($pid, true) - $patientbalance;
1253 $totalbalance = $patientbalance + $insurancebalance;
1254 $unallocated_amt = get_unallocated_patient_balance($pid);
1256 $id = "billing_ps_expand";
1257 $dispatchResult = $ed->dispatch(new CardRenderEvent('billing'), CardRenderEvent::EVENT_HANDLE);
1259 $viewArgs = [
1260 'title' => xl('Billing'),
1261 'id' => $id,
1262 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1263 'hideBtn' => true,
1264 'patientBalance' => $patientbalance,
1265 'insuranceBalance' => $insurancebalance,
1266 'totalBalance' => $totalbalance,
1267 'unallocated' => $unallocated_amt,
1268 'forceAlwaysOpen' => $forceBillingExpandAlways,
1269 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1270 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1273 if (!empty($result['billing_note'])) {
1274 $viewArgs['billingNote'] = $result['billing_note'];
1277 if (!empty($result3['provider'])) {
1278 $viewArgs['provider'] = true;
1279 $viewArgs['insName'] = $insco_name;
1280 $viewArgs['copay'] = $result3['copay'];
1281 $viewArgs['effDate'] = $result3['effdate'];
1282 $viewArgs['effDateEnd'] = $result3['effdate_end'];
1285 echo $twig->getTwig()->render('patient/card/billing.html.twig', $viewArgs);
1286 endif; // End the hide_billing_widget
1288 // if anyone wants to render anything before the patient demographic list
1289 $GLOBALS["kernel"]->getEventDispatcher()->dispatch(new RenderEvent($pid), RenderEvent::EVENT_SECTION_LIST_RENDER_BEFORE, 10);
1291 if (AclMain::aclCheckCore('patients', 'demo')) :
1292 $dispatchResult = $ed->dispatch(new CardRenderEvent('demographic'), CardRenderEvent::EVENT_HANDLE);
1293 // Render the Demographics box
1294 $viewArgs = [
1295 'title' => xl("Demographics"),
1296 'id' => "demographics_ps_expand",
1297 'btnLabel' => "Edit",
1298 'btnLink' => "demographics_full.php",
1299 'linkMethod' => "html",
1300 'auth' => ACLMain::aclCheckCore('patients', 'demo', '', 'write'),
1301 'requireRestore' => (!isset($_SESSION['patient_portal_onsite_two'])) ? true : false,
1302 'initiallyCollapsed' => getUserSetting("demographics_ps_expand") == true ? true : false,
1303 'tabID' => "DEM",
1304 'result' => $result,
1305 'result2' => $result2,
1306 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1307 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1309 echo $twig->getTwig()->render('patient/card/tab_base.html.twig', $viewArgs);
1311 // Insurance
1312 $insArr = [];
1313 $insInBinder = '?';
1314 for ($y = 1; count($insurance_array) > $y; $y++) {
1315 $insInBinder .= ',?';
1317 $sql = "SELECT * FROM insurance_data WHERE pid = ? AND type IN(" . $insInBinder . ") ORDER BY type, date DESC";
1318 $params[] = $pid;
1319 $params = array_merge($params, $insurance_array);
1320 $res = sqlStatement($sql, $params);
1321 $prior_ins_type = '';
1323 while ($row = sqlFetchArray($res)) {
1324 if ($row['provider']) {
1325 // since the query is sorted by DATE DESC can use prior ins type to identify
1326 // unless insurance date_end is applicable
1327 $row['isOld'] = (!empty($row['date_end']) && $row['date_end'] <= date("Y-m-d")) ? true : false;
1328 if (!$row['isOld']) {
1329 $row['isOld'] = (strcmp($row['type'], $prior_ins_type) == 0) ? true : false;
1331 $icobj = new InsuranceCompany($row['provider']);
1332 $adobj = $icobj->get_address();
1333 $insco_name = trim($icobj->get_name());
1334 $row['insco'] = [
1335 'name' => trim($icobj->get_name()),
1336 'address' => [
1337 'line1' => $adobj->get_line1(),
1338 'line2' => $adobj->get_line2(),
1339 'city' => $adobj->get_city(),
1340 'state' => $adobj->get_state(),
1341 'postal' => $adobj->get_zip(),
1342 'country' => $adobj->get_country()
1345 $row['policy_type'] = (!empty($row['policy_type'])) ? $policy_types[$row['policy_type']] : false;
1346 $row['dispFromDate'] = $row['date'] ? true : false;
1347 $mname = ($row['subscriber_mname'] != "") ? $row['subscriber_mname'] : "";
1348 $row['subscriber_full_name'] = str_replace("%mname%", $mname, "{$row['subscriber_fname']} %mname% {$row['subscriber_lname']}");
1349 $row['until_date'] = $row['isOld'] ? $row['isOld'] : xlt('Present');
1350 $insArr[] = $row;
1351 $prior_ins_type = $row['type'];
1352 } else {
1353 $row['isOld'] = (strcmp($row['type'], $prior_ins_type) == 0) ? true : false;
1354 $row['dispFromDate'] = $row['date'] ? true : false;
1355 $row['insco'] = [
1356 'name' => 'Self-Pay',
1357 'address' => [
1358 'line1' => '',
1359 'line2' => '',
1360 'city' => '',
1361 'state' => '',
1362 'postal' => '',
1363 'country' => ''
1366 $row['policy_type'] = false;
1367 $mname = ''; //($row['subscriber_mname'] != "") ? $row['subscriber_mname'] : "";
1368 $row['subscriber_full_name'] = ' '; // str_replace("%mname%", $mname, "{$row['subscriber_fname']} %mname% {$row['subscriber_lname']}");
1369 $row['until_date'] = ($row['isOld']) ? $row['isOld'] : xlt("Present");
1370 $prior_ins_type = $row['type'];
1371 if ($row['type'] != 'primary') {
1372 continue;
1374 $insArr[] = $row;
1378 if ($GLOBALS["enable_oa"]) {
1379 if (($_POST['status_update'] ?? '') === 'true') {
1380 unset($_POST['status_update']);
1381 $showEligibility = true;
1382 $ok = EDI270::requestEligibleTransaction($pid);
1383 if ($ok === true) {
1384 ob_start();
1385 EDI270::showEligibilityInformation($pid, false);
1386 $output = ob_get_contents();
1387 ob_end_clean();
1388 } else {
1389 $output = $ok;
1391 } else {
1392 ob_start();
1393 EDI270::showEligibilityInformation($pid, true);
1394 $output = ob_get_contents();
1395 ob_end_clean();
1397 } else {
1398 ob_start();
1399 EDI270::showEligibilityInformation($pid, true);
1400 $output = ob_get_contents();
1401 ob_end_clean();
1404 $id = "insurance_ps_expand";
1405 $dispatchResult = $ed->dispatch(new CardRenderEvent('insurance'), CardRenderEvent::EVENT_HANDLE);
1406 $viewArgs = [
1407 'title' => xl("Insurance"),
1408 'id' => $id,
1409 'btnLabel' => "Edit",
1410 'btnLink' => "demographics_full.php",
1411 'linkMethod' => 'html',
1412 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1413 'ins' => $insArr,
1414 'eligibility' => $output,
1415 'enable_oa' => $GLOBALS['enable_oa'],
1416 'auth' => AclMain::aclCheckCore('patients', 'demo', '', 'write'),
1417 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1418 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1421 if (count($insArr) > 0) {
1422 echo $twig->getTwig()->render('patient/card/insurance.html.twig', $viewArgs);
1424 endif; // end if demographics authorized
1426 if (AclMain::aclCheckCore('patients', 'notes')) :
1427 $dispatchResult = $ed->dispatch(new CardRenderEvent('note'), CardRenderEvent::EVENT_HANDLE);
1428 // Notes expand collapse widget
1429 $id = "pnotes_ps_expand";
1430 $viewArgs = [
1431 'title' => xl("Messages"),
1432 'id' => $id,
1433 'btnLabel' => "Edit",
1434 'btnLink' => "pnotes_full.php?form_active=1",
1435 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1436 'linkMethod' => "html",
1437 'bodyClass' => "notab",
1438 'auth' => AclMain::aclCheckCore('patients', 'notes', '', 'write'),
1439 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1440 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1442 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1443 endif; // end if notes authorized
1445 if (AclMain::aclCheckCore('patients', 'reminder') && $GLOBALS['enable_cdr'] && $GLOBALS['enable_cdr_prw']) :
1446 // patient reminders collapse widget
1447 $dispatchResult = $ed->dispatch(new CardRenderEvent('reminder'), CardRenderEvent::EVENT_HANDLE);
1448 $id = "patient_reminders_ps_expand";
1449 $viewArgs = [
1450 'title' => xl('Patient Reminders'),
1451 'id' => $id,
1452 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1453 'btnLabel' => 'Edit',
1454 'btnLink' => '../reminder/patient_reminders.php?mode=simple&patient_id=' . attr_url($pid),
1455 'linkMethod' => 'html',
1456 'bodyClass' => 'notab collapse show',
1457 'auth' => AclMain::aclCheckCore('patients', 'reminder', '', 'write'),
1458 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1459 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1461 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1462 endif; //end if prw is activated
1464 if (AclMain::aclCheckCore('patients', 'disclosure')) :
1465 $authWriteDisclosure = AclMain::aclCheckCore('patients', 'disclosure', '', 'write');
1466 $authAddonlyDisclosure = AclMain::aclCheckCore('patients', 'disclosure', '', 'addonly');
1467 $dispatchResult = $ed->dispatch(new CardRenderEvent('disclosure'), CardRenderEvent::EVENT_HANDLE);
1468 // disclosures expand collapse widget
1469 $id = "disclosures_ps_expand";
1470 $viewArgs = [
1471 'title' => xl('Disclosures'),
1472 'id' => $id,
1473 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1474 'btnLabel' => 'Edit',
1475 'btnLink' => 'disclosure_full.php',
1476 'linkMethod' => 'html',
1477 'bodyClass' => 'notab collapse show',
1478 'auth' => ($authWriteDisclosure || $authAddonlyDisclosure),
1479 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1480 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1482 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1483 endif; // end if disclosures authorized
1485 if ($GLOBALS['amendments'] && AclMain::aclCheckCore('patients', 'amendment')) :
1486 $dispatchResult = $ed->dispatch(new CardRenderEvent('amendment'), CardRenderEvent::EVENT_HANDLE);
1487 // Amendments widget
1488 $sql = "SELECT * FROM amendments WHERE pid = ? ORDER BY amendment_date DESC";
1489 $result = sqlStatement($sql, [$pid]);
1490 $amendments = [];
1491 while ($row = sqlFetchArray($result)) {
1492 $amendments[] = $row;
1495 $id = "amendments_ps_expand";
1496 $viewArgs = [
1497 'title' => xl('Amendments'),
1498 'id' => $id,
1499 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1500 'btnLabel' => 'Edit',
1501 'btnLink' => $GLOBALS['webroot'] . "/interface/patient_file/summary/list_amendments.php?id=" . attr_url($pid),
1502 'btnCLass' => '',
1503 'linkMethod' => 'html',
1504 'bodyClass' => 'notab collapse show',
1505 'auth' => AclMain::aclCheckCore('patients', 'amendment', '', ['write', 'addonly']),
1506 'amendments' => $amendments,
1507 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1508 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1510 echo $twig->getTwig()->render('patient/card/amendments.html.twig', $viewArgs);
1511 endif; // end amendments authorized
1513 if (AclMain::aclCheckCore('patients', 'lab')) :
1514 $dispatchResult = $ed->dispatch(new CardRenderEvent('lab'), CardRenderEvent::EVENT_HANDLE);
1515 // labdata expand collapse widget
1516 // check to see if any labdata exist
1517 $spruch = "SELECT procedure_report.date_collected AS date
1518 FROM procedure_report
1519 JOIN procedure_order ON procedure_report.procedure_order_id = procedure_order.procedure_order_id
1520 WHERE procedure_order.patient_id = ?
1521 ORDER BY procedure_report.date_collected DESC";
1522 $existLabdata = sqlQuery($spruch, array($pid));
1523 $widgetAuth = ($existLabdata) ? true : false;
1525 $id = "labdata_ps_expand";
1526 $viewArgs = [
1527 'title' => xl('Labs'),
1528 'id' => $id,
1529 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1530 'btnLabel' => 'Trend',
1531 'btnLink' => "../summary/labdata.php",
1532 'linkMethod' => 'html',
1533 'bodyClass' => 'collapse show',
1534 'auth' => $widgetAuth,
1535 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1536 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1538 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1539 endif; // end labs authorized
1541 if ($vitals_is_registered && AclMain::aclCheckCore('patients', 'med')) :
1542 $dispatchResult = $ed->dispatch(new CardRenderEvent('vital_sign'), CardRenderEvent::EVENT_HANDLE);
1543 // vitals expand collapse widget
1544 // check to see if any vitals exist
1545 $existVitals = sqlQuery("SELECT * FROM form_vitals WHERE pid=?", array($pid));
1546 $widgetAuth = ($existVitals) ? true : false;
1548 $id = "vitals_ps_expand";
1549 $viewArgs = [
1550 'title' => xl('Vitals'),
1551 'id' => $id,
1552 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1553 'btnLabel' => 'Trend',
1554 'btnLink' => "../encounter/trend_form.php?formname=vitals&context=dashboard",
1555 'linkMethod' => 'html',
1556 'bodyClass' => 'collapse show',
1557 'auth' => $widgetAuth,
1558 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1559 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1561 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1562 endif; // end vitals
1564 // if anyone wants to render anything after the patient demographic list
1565 $GLOBALS["kernel"]->getEventDispatcher()->dispatch(new RenderEvent($pid), RenderEvent::EVENT_SECTION_LIST_RENDER_AFTER, 10);
1567 // This generates a section similar to Vitals for each LBF form that
1568 // supports charting. The form ID is used as the "widget label".
1569 $gfres = sqlStatement("SELECT grp_form_id AS option_id, grp_title AS title, grp_aco_spec
1570 FROM layout_group_properties
1571 WHERE grp_form_id LIKE 'LBF%'
1572 AND grp_group_id = ''
1573 AND grp_repeats > 0
1574 AND grp_activity = 1
1575 ORDER BY grp_seq, grp_title");
1577 while ($gfrow = sqlFetchArray($gfres)) :
1578 // $jobj = json_decode($gfrow['notes'], true);
1579 $LBF_ACO = empty($gfrow['grp_aco_spec']) ? false : explode('|', $gfrow['grp_aco_spec']);
1580 if ($LBF_ACO && !AclMain::aclCheckCore($LBF_ACO[0], $LBF_ACO[1])) {
1581 continue;
1584 // vitals expand collapse widget
1585 $widgetAuth = false;
1586 if (!$LBF_ACO || AclMain::aclCheckCore($LBF_ACO[0], $LBF_ACO[1], '', 'write')) {
1587 // check to see if any instances exist for this patient
1588 $existVitals = sqlQuery("SELECT * FROM forms WHERE pid = ? AND formdir = ? AND deleted = 0", [$pid, $vitals_form_id]);
1589 $widgetAuth = $existVitals;
1592 $dispatchResult = $ed->dispatch(new CardRenderEvent($gfrow['title']), CardRenderEvent::EVENT_HANDLE);
1593 $viewArgs = [
1594 'title' => xl($gfrow['title']),
1595 'id' => $vitals_form_id,
1596 'initiallyCollapsed' => getUserSetting($vitals_form_id) == true ? true : false,
1597 'btnLabel' => 'Trend',
1598 'btnLink' => "../encounter/trend_form.php?formname=vitals&context=dashboard",
1599 'linkMethod' => 'html',
1600 'bodyClass' => 'notab collapse show',
1601 'auth' => $widgetAuth,
1602 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1603 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1605 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1606 endwhile; // end while
1608 </div> <!-- end left column div -->
1609 <div class="col-md-4">
1610 <!-- start right column div -->
1611 <?php
1612 $_extAccess = [
1613 $GLOBALS['portal_onsite_two_enable'],
1614 $GLOBALS['rest_fhir_api'],
1615 $GLOBALS['rest_api'],
1616 $GLOBALS['rest_portal_api'],
1618 foreach ($_extAccess as $_) {
1619 if ($_) {
1620 $portalCard = new PortalCard($GLOBALS);
1621 break;
1625 $sectionRenderEvents = $ed->dispatch(new SectionEvent('secondary'), SectionEvent::EVENT_HANDLE);
1626 $sectionCards = $sectionRenderEvents->getCards();
1628 $t = $twig->getTwig();
1630 foreach ($sectionCards as $card) {
1631 $_auth = $card->getAcl();
1632 $auth = AclMain::aclCheckCore($_auth[0], $_auth[1]);
1633 if (!$auth) {
1634 continue;
1637 $btnLabel = false;
1638 if ($card->canAdd()) {
1639 $btnLabel = 'Add';
1640 } elseif ($card->canEdit()) {
1641 $btnLabel = 'Edit';
1644 $viewArgs = [
1645 'card' => $card,
1646 'title' => $card->getTitle(),
1647 'id' => $card->getIdentifier() . "_expand",
1648 'auth' => $auth,
1649 'linkMethod' => 'html',
1650 'initiallyCollapsed' => !$card->isInitiallyCollapsed(),
1651 'card_bg_color' => $card->getBackgroundColorClass(),
1652 'card_text_color' => $card->getTextColorClass(),
1653 'forceAlwaysOpen' => !$card->canCollapse(),
1654 'btnLabel' => $btnLabel,
1655 'btnLink' => "javascript:$('#patient_portal').collapse('toggle')",
1658 echo $t->render($card->getTemplateFile(), array_merge($card->getTemplateVariables(), $viewArgs));
1661 if ($GLOBALS['erx_enable']) :
1662 $dispatchResult = $ed->dispatch(new CardRenderEvent('demographics'), CardRenderEvent::EVENT_HANDLE);
1663 echo $twig->getTwig()->render('patient/partials/erx.html.twig', [
1664 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1665 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1667 endif;
1669 // If there is an ID Card or any Photos show the widget
1670 $photos = pic_array($pid, $GLOBALS['patient_photo_category_name']);
1671 if ($photos or $idcard_doc_id) {
1672 $id = "photos_ps_expand";
1673 $dispatchResult = $ed->dispatch(new CardRenderEvent('patient_photo'), CardRenderEvent::EVENT_HANDLE);
1674 $viewArgs = [
1675 'title' => xl("ID Card / Photos"),
1676 'id' => $id,
1677 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1678 'btnLabel' => 'Edit',
1679 'linkMethod' => "javascript",
1680 'bodyClass' => 'collapse show',
1681 'auth' => false,
1682 'patientIDCategoryID' => $GLOBALS['patient_id_category_name'],
1683 'patientPhotoCategoryName' => $GLOBALS['patient_photo_category_name'],
1684 'photos' => $photos,
1685 'idCardDocID' => $idcard_doc_id,
1686 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1687 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1689 echo $twig->getTwig()->render('patient/card/photo.html.twig', $viewArgs);
1692 // Advance Directives
1693 if ($GLOBALS['advance_directives_warning']) {
1694 // advance directives expand collapse widget
1696 $counterFlag = false; //flag to record whether any categories contain ad records
1697 $query = "SELECT id FROM categories WHERE name='Advance Directive'";
1698 $myrow2 = sqlQuery($query);
1699 $advDirArr = [];
1700 if ($myrow2) {
1701 $parentId = $myrow2['id'];
1702 $query = "SELECT id, name FROM categories WHERE parent=?";
1703 $resNew1 = sqlStatement($query, array($parentId));
1704 while ($myrows3 = sqlFetchArray($resNew1)) {
1705 $categoryId = $myrows3['id'];
1706 $nameDoc = $myrows3['name'];
1707 $query = "SELECT documents.date, documents.id
1708 FROM documents
1709 INNER JOIN categories_to_documents ON categories_to_documents.document_id=documents.id
1710 WHERE categories_to_documents.category_id=?
1711 AND documents.foreign_id=?
1712 AND documents.deleted = 0
1713 ORDER BY documents.date DESC";
1714 $resNew2 = sqlStatement($query, array($categoryId, $pid));
1715 $limitCounter = 0; // limit to one entry per category
1716 while (($myrows4 = sqlFetchArray($resNew2)) && ($limitCounter == 0)) {
1717 $dateTimeDoc = $myrows4['date'];
1718 // remove time from datetime stamp
1719 $tempParse = explode(" ", $dateTimeDoc);
1720 $dateDoc = $tempParse[0];
1721 $idDoc = $myrows4['id'];
1722 $tmp = [
1723 'pid' => $pid,
1724 'docID' => $idDoc,
1725 'docName' => $nameDoc,
1726 'docDate' => $dateDoc,
1728 $advDirArr[] = $tmp;
1729 $limitCounter = $limitCounter + 1;
1730 $counterFlag = true;
1734 $id = "adv_directives_ps_expand";
1736 $dispatchResult = $ed->dispatch(new CardRenderEvent('advance_directive'), CardRenderEvent::EVENT_HANDLE);
1737 $viewArgs = [
1738 'title' => xl("Advance Directives"),
1739 'id' => $id,
1740 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1741 'btnLabel' => 'Edit',
1742 'linkMethod' => "javascript",
1743 'btnLink' => "return advdirconfigure();",
1744 'bodyClass' => 'collapse show',
1745 'auth' => true,
1746 'advDirArr' => $advDirArr,
1747 'counterFlag' => $counterFlag,
1748 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1749 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1751 echo $twig->getTwig()->render('patient/card/adv_dir.html.twig', $viewArgs);
1753 } // close advanced dir block
1755 // Show Clinical Reminders for any user that has rules that are permitted.
1756 $clin_rem_check = resolve_rules_sql('', '0', true, '', $_SESSION['authUser']);
1757 $cdr = $GLOBALS['enable_cdr'];
1758 $cdr_crw = $GLOBALS['enable_cdr_crw'];
1759 if (!empty($clin_rem_check) && $cdr && $cdr_crw && AclMain::aclCheckCore('patients', 'alert')) {
1760 // clinical summary expand collapse widget
1761 $id = "clinical_reminders_ps_expand";
1762 $dispatchResult = $ed->dispatch(new CardRenderEvent('clinical_reminders'), CardRenderEvent::EVENT_HANDLE);
1763 $viewArgs = [
1764 'title' => xl("Clinical Reminders"),
1765 'id' => $id,
1766 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1767 'btnLabel' => "Edit",
1768 'btnLink' => "../reminder/clinical_reminders.php?patient_id=" . attr_url($pid),
1769 'linkMethod' => "html",
1770 'auth' => AclMain::aclCheckCore('patients', 'alert', '', 'write'),
1771 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1772 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1774 echo $twig->getTwig()->render('patient/card/loader.html.twig', $viewArgs);
1775 } // end if crw
1777 $displayAppts = false;
1778 $displayRecurrAppts = false;
1779 $displayPastAppts = false;
1781 // Show current and upcoming appointments.
1782 // Recurring appointment support and Appointment Display Sets
1783 // added to Appointments by Ian Jardine ( epsdky ).
1784 if (isset($pid) && !$GLOBALS['disable_calendar'] && AclMain::aclCheckCore('patients', 'appt')) {
1785 $displayAppts = true;
1786 $current_date2 = date('Y-m-d');
1787 $events = array();
1788 $apptNum = (int) $GLOBALS['number_of_appts_to_show'];
1789 $apptNum2 = ($apptNum != 0) ? abs($apptNum) : 10;
1791 $mode1 = !$GLOBALS['appt_display_sets_option'];
1792 $colorSet1 = $GLOBALS['appt_display_sets_color_1'];
1793 $colorSet2 = $GLOBALS['appt_display_sets_color_2'];
1794 $colorSet3 = $GLOBALS['appt_display_sets_color_3'];
1795 $colorSet4 = $GLOBALS['appt_display_sets_color_4'];
1796 $extraAppts = ($mode1) ? 1 : 6;
1797 $extraApptDate = '';
1799 $past_appts = [];
1800 $recallArr = [];
1802 $events = fetchNextXAppts($current_date2, $pid, $apptNum2 + $extraAppts, true);
1804 if ($events) {
1805 $selectNum = 0;
1806 $apptNumber = count($events);
1808 if ($apptNumber <= $apptNum2) {
1809 $extraApptDate = '';
1811 } elseif ($mode1 && $apptNumber == $apptNum2 + 1) {
1812 $extraApptDate = $events[$apptNumber - 1]['pc_eventDate'];
1813 array_pop($events);
1814 --$apptNumber;
1815 $selectNum = 1;
1817 } elseif ($apptNumber == $apptNum2 + 6) {
1818 $extraApptDate = $events[$apptNumber - 1]['pc_eventDate'];
1819 array_pop($events);
1820 --$apptNumber;
1821 $selectNum = 2;
1823 } else { // mode 2 - $apptNum2 < $apptNumber < $apptNum2 + 6
1824 $extraApptDate = '';
1825 $selectNum = 2;
1829 $limitApptIndx = $apptNum2 - 1;
1830 $limitApptDate = $events[$limitApptIndx]['pc_eventDate'] ?? '';
1832 switch ($selectNum) {
1833 case 2:
1834 $lastApptIndx = $apptNumber - 1;
1835 $thisNumber = $lastApptIndx - $limitApptIndx;
1836 for ($i = 1; $i <= $thisNumber; ++$i) {
1837 if ($events[$limitApptIndx + $i]['pc_eventDate'] != $limitApptDate) {
1838 $extraApptDate = $events[$limitApptIndx + $i]['pc_eventDate'];
1839 $events = array_slice($events, 0, $limitApptIndx + $i);
1840 break;
1843 // Break in the loop to improve performance
1844 case 1:
1845 $firstApptIndx = 0;
1846 for ($i = 1; $i <= $limitApptIndx; ++$i) {
1847 if ($events[$limitApptIndx - $i]['pc_eventDate'] != $limitApptDate) {
1848 $firstApptIndx = $apptNum2 - $i;
1849 break;
1852 // Break in the loop to improve performance
1855 if ($extraApptDate) {
1856 if ($extraApptDate != $limitApptDate) {
1857 $apptStyle2 = " style='background-color:" . attr($colorSet3) . ";'";
1858 } else {
1859 $apptStyle2 = " style='background-color:" . attr($colorSet4) . ";'";
1864 $count = 0;
1865 $toggleSet = true;
1866 $priorDate = "";
1867 $therapyGroupCategories = array();
1868 $query = sqlStatement("SELECT pc_catid FROM openemr_postcalendar_categories WHERE pc_cattype = 3 AND pc_active = 1");
1869 while ($result = sqlFetchArray($query)) {
1870 $therapyGroupCategories[] = $result['pc_catid'];
1873 // Build the UI Loop
1874 $appts = [];
1875 foreach ($events as $row) {
1876 $count++;
1877 $dayname = date("D", strtotime($row['pc_eventDate']));
1878 $displayMeridiem = ($GLOBALS['time_display_format'] == 0) ? "" : "am";
1879 $disphour = substr($row['pc_startTime'], 0, 2) + 0;
1880 $dispmin = substr($row['pc_startTime'], 3, 2);
1881 if ($disphour >= 12 && $GLOBALS['time_display_format'] == 1) {
1882 $displayMeridiem = "pm";
1883 if ($disphour > 12) {
1884 $disphour -= 12;
1888 // Note the translaution occurs here instead of in teh Twig file for some specific concatenation needs
1889 $etitle = xl('(Click to edit)');
1890 if ($row['pc_hometext'] != "") {
1891 $etitle = xl('Comments') . ": " . ($row['pc_hometext']) . "\r\n" . $etitle;
1894 $row['etitle'] = $etitle;
1896 if ($extraApptDate && $count > $firstApptIndx) {
1897 $apptStyle = $apptStyle2;
1898 } else {
1899 if ($row['pc_eventDate'] != $priorDate) {
1900 $priorDate = $row['pc_eventDate'];
1901 $toggleSet = !$toggleSet;
1904 $bgColor = ($toggleSet) ? $colorSet2 : $colorSet1;
1907 $row['pc_eventTime'] = sprintf("%02d", $disphour) . ":{$dispmin}";
1908 $row['pc_status'] = generate_display_field(array('data_type' => '1', 'list_id' => 'apptstat'), $row['pc_apptstatus']);
1909 if ($row['pc_status'] == 'None') {
1910 $row['pc_status'] = 'Scheduled';
1913 if (in_array($row['pc_catid'], $therapyGroupCategories)) {
1914 $row['groupName'] = getGroup($row['pc_gid'])['group_name'];
1917 $row['uname'] = text($row['ufname'] . " " . $row['ulname']);
1918 $row['bgColor'] = $bgColor;
1919 $row['dayName'] = $dayname;
1920 $row['displayMeridiem'] = $displayMeridiem;
1921 $row['jsEvent'] = attr_js(preg_replace("/-/", "", $row['pc_eventDate'])) . ', ' . attr_js($row['pc_eid']);
1922 $appts[] = $row;
1925 if ($resNotNull) {
1926 // Show Recall if one exists
1927 $query = sqlStatement("SELECT * FROM `medex_recalls` WHERE `r_pid` = ?", [(int)$pid]);
1928 $recallArr = [];
1929 while ($result2 = sqlFetchArray($query)) {
1930 //tabYourIt('recall', 'main/messages/messages.php?go=' + choice);
1931 //parent.left_nav.loadFrame('1', tabNAME, url);
1932 $recallArr[] = [
1933 'date' => $result2['r_eventDate'],
1934 'reason' => $result2['r_reason'],
1936 $count2++;
1938 $id = "recall_ps_expand";
1939 $dispatchResult = $ed->dispatch(new CardRenderEvent('recall'), CardRenderEvent::EVENT_HANDLE);
1940 echo $twig->getTwig()->render('patient/card/recall.html.twig', [
1941 'title' => xl('Recall'),
1942 'id' => $id,
1943 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
1944 'recalls' => $recallArr,
1945 'recallsAvailable' => ($count < 1 && empty($count2)) ? false : true,
1946 'prependedInjection' => $dispatchResult->getPrependedInjection(),
1947 'appendedInjection' => $dispatchResult->getAppendedInjection(),
1950 } // End of Appointments Widget.
1952 /* Widget that shows recurrences for appointments. */
1953 $recurr = [];
1954 if (isset($pid) && !$GLOBALS['disable_calendar'] && $GLOBALS['appt_recurrences_widget'] && AclMain::aclCheckCore('patients', 'appt')) {
1955 $displayRecurrAppts = true;
1956 $count = 0;
1957 $toggleSet = true;
1958 $priorDate = "";
1960 //Fetch patient's recurrences. Function returns array with recurrence appointments' category, recurrence pattern (interpreted), and end date.
1961 $recurrences = fetchRecurrences($pid);
1962 if (!empty($recurrences)) {
1963 foreach ($recurrences as $row) {
1964 if (!recurrence_is_current($row['pc_endDate'])) {
1965 continue;
1968 if (ends_in_a_week($row['pc_endDate'])) {
1969 $row['close_to_end'] = true;
1971 $recurr[] = $row;
1975 /* End of recurrence widget */
1977 // Show PAST appointments.
1978 // added by Terry Hill to allow reverse sorting of the appointments
1979 $direction = '1';
1980 if ($GLOBALS['num_past_appointments_to_show'] < 0) {
1981 $direction = '2';
1982 ($showpast = -1 * $GLOBALS['num_past_appointments_to_show']);
1983 } else {
1984 $showpast = $GLOBALS['num_past_appointments_to_show'];
1987 if (isset($pid) && !$GLOBALS['disable_calendar'] && $showpast > 0 && AclMain::aclCheckCore('patients', 'appt')) {
1988 $displayPastAppts = true;
1990 $pastAppts = fetchXPastAppts($pid, $showpast, $direction); // This line added by epsdky
1992 $count = 0;
1994 foreach ($pastAppts as $row) {
1995 $count++;
1996 $dayname = date("D", strtotime($row['pc_eventDate']));
1997 $displayMeridiem = ($GLOBALS['time_display_format'] == 0) ? "" : "am";
1998 $disphour = substr($row['pc_startTime'], 0, 2) + 0;
1999 $dispmin = substr($row['pc_startTime'], 3, 2);
2000 if ($disphour >= 12) {
2001 $displayMeridiem = "pm";
2002 if ($disphour > 12 && $GLOBALS['time_display_format'] == 1) {
2003 $disphour -= 12;
2007 $petitle = xl('(Click to edit)');
2008 if ($row['pc_hometext'] != "") {
2009 $petitle = xl('Comments') . ": " . ($row['pc_hometext']) . "\r\n" . $petitle;
2011 $row['etitle'] = $petitle;
2013 $row['pc_status'] = generate_display_field(array('data_type' => '1', 'list_id' => 'apptstat'), $row['pc_apptstatus']);
2015 $row['dayName'] = $dayname;
2016 $row['displayMeridiem'] = $displayMeridiem;
2017 $row['pc_eventTime'] = sprintf("%02d", $disphour) . ":{$dispmin}";
2018 $row['uname'] = text($row['ufname'] . " " . $row['ulname']);
2019 $row['jsEvent'] = attr_js(preg_replace("/-/", "", $row['pc_eventDate'])) . ', ' . attr_js($row['pc_eid']);
2020 $past_appts[] = $row;
2023 // END of past appointments
2025 // Display the Appt card
2026 $id = "appointments_ps_expand";
2027 $dispatchResult = $ed->dispatch(new CardRenderEvent('appointment'), CardRenderEvent::EVENT_HANDLE);
2028 echo $twig->getTwig()->render('patient/card/appointments.html.twig', [
2029 'title' => xl("Appointments"),
2030 'id' => $id,
2031 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
2032 'btnLabel' => "Add",
2033 'btnLink' => "return newEvt()",
2034 'linkMethod' => "javascript",
2035 'appts' => $appts,
2036 'recurrAppts' => $recurr,
2037 'pastAppts' => $past_appts,
2038 'displayAppts' => $displayAppts,
2039 'displayRecurrAppts' => $displayRecurrAppts,
2040 'displayPastAppts' => $displayPastAppts,
2041 'extraApptDate' => $extraApptDate,
2042 'therapyGroupCategories' => $therapyGroupCategories,
2043 'auth' => $resNotNull && (AclMain::aclCheckCore('patients', 'appt', '', 'write') || AclMain::aclCheckCore('patients', 'appt', '', 'addonly')),
2044 'resNotNull' => $resNotNull,
2045 'prependedInjection' => $dispatchResult->getPrependedInjection(),
2046 'appendedInjection' => $dispatchResult->getAppendedInjection(),
2049 echo "<div id=\"stats_div\"></div>";
2051 // TRACK ANYTHING
2052 // Determine if track_anything form is in use for this site.
2053 $tmp = sqlQuery("SELECT count(*) AS count FROM registry WHERE directory = 'track_anything' AND state = 1");
2054 $track_is_registered = $tmp['count'];
2055 if ($track_is_registered) {
2056 $spruch = "SELECT id FROM forms WHERE pid = ? AND formdir = ?";
2057 $existTracks = sqlQuery($spruch, array($pid, "track_anything"));
2058 $id = "track_anything_ps_expand";
2059 $dispatchResult = $ed->dispatch(new CardRenderEvent('track_anything'), CardRenderEvent::EVENT_HANDLE);
2060 echo $twig->getTwig()->render('patient/card/loader.html.twig', [
2061 'title' => xl("Tracks"),
2062 'id' => $id,
2063 'initiallyCollapsed' => (getUserSetting($id) == 0) ? false : true,
2064 'btnLink' => "../../forms/track_anything/create.php",
2065 'linkMethod' => "html",
2066 'prependedInjection' => $dispatchResult->getPrependedInjection(),
2067 'appendedInjection' => $dispatchResult->getAppendedInjection(),
2069 } // end track_anything
2071 if ($thisauth) :
2072 echo $twig->getTwig()->render('patient/partials/delete.html.twig', [
2073 'isAdmin' => AclMain::aclCheckCore('admin', 'super'),
2074 'allowPatientDelete' => $GLOBALS['allow_pat_delete'],
2075 'csrf' => CsrfUtils::collectCsrfToken(),
2076 'pid' => $pid
2078 endif;
2080 </div> <!-- end right column div -->
2081 </div> <!-- end div.main > row:first -->
2082 </div> <!-- end main content div -->
2083 </div><!-- end container div -->
2084 <?php $oemr_ui->oeBelowContainerDiv(); ?>
2085 <script>
2086 // Array of skip conditions for the checkSkipConditions() function.
2087 var skipArray = [
2088 <?php echo ($condition_str ?? ''); ?>
2090 checkSkipConditions();
2094 var isPost = <?php echo js_escape($showEligibility ?? false); ?>;
2095 var listId = '#' + <?php echo js_escape($list_id); ?>;
2096 $(function() {
2097 $(listId).addClass("active");
2098 if (isPost === true) {
2099 $("#eligibility").click();
2100 $("#eligibility").get(0).scrollIntoView();
2103 </script>
2104 </body>
2105 <?php $ed->dispatch(new RenderEvent($pid), RenderEvent::EVENT_RENDER_POST_PAGELOAD, 10); ?>
2106 </html>