Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / reminders.php
blob46bbe3f5abc1a7d6f44a3fe90ca38ca3972bea17
1 <?php
2 /**
3 * Patient reminders functions.
5 * These functions should not ever attempt to write to
6 * session variables, because the session_write_close() function
7 * is typically called before utilizing these functions.
9 * Functions for collection/displaying/sending patient reminders. This is
10 * part of the CDR engine, which can be found at library/clinical_rules.php.
12 * Copyright (C) 2010-2012 Brady Miller <brady.g.miller@gmail.com>
14 * LICENSE: This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://opensource.org/licenses/gpl-license.php>;.
25 * @package OpenEMR
26 * @author Brady Miller <brady.g.miller@gmail.com>
27 * @link https://www.open-emr.org
30 /**
31 * Include the main CDR engine library, email class and maviq class
33 require_once(dirname(__FILE__) . "/clinical_rules.php");
34 require_once(dirname(__FILE__) . "/maviq_phone_api.php");
36 //only used in commented out code
37 use OpenEMR\Common\Crypto\CryptoGen;
39 /**
40 * Display the patient reminder widget.
42 * @param integer $patient_id pid of selected patient
43 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
45 function patient_reminder_widget($patient_id, $dateTarget = '')
48 // Set date to current if not set
49 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
51 // Update reminders for patient
52 update_reminders($dateTarget, $patient_id);
54 // Fetch the active reminders
55 $listReminders = fetch_reminders($patient_id);
57 if (empty($listReminders)) {
58 // No reminders to show.
59 echo xlt('No active patient reminders.');
60 return;
63 echo "<table cellpadding='0' cellspacing='0'>";
64 foreach ($listReminders as $reminder) {
65 echo "<tr><td style='padding:0 1em 0 1em;'><span class='small'>";
66 // show reminder label
67 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $reminder['category']) .
68 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $reminder['item']);
69 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
70 // show reminder due status
71 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'), $reminder['due_status']);
72 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
73 // show reminder sent date
74 if (empty($reminder['date_sent'])) {
75 echo xlt('Reminder Not Sent Yet');
76 } else {
77 echo text(xl('Reminder Sent On').": ".$reminder['date_sent']);
80 echo "</span></td></tr>";
83 echo "</table>";
86 /**
87 * Function to update reminders via a batching method to improve performance and decrease memory overhead.
89 * Function that updates reminders and returns an array with a specific data structure.
90 * <pre>The data structure of the return array includes the following elements
91 * 'total_active_actions' - Number of active actions.
92 * 'total_pre_active_reminders' - Number of active reminders before processing.
93 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
94 * 'total_post_active_reminders' - Number of active reminders after processing.
95 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
96 * 'number_new_reminders' - Number of new reminders
97 * 'number_updated_reminders' - Number of updated reminders (due_status change)
98 * 'number_inactivated_reminders' - Number of inactivated reminders.
99 * 'number_unchanged_reminders' - Number of unchanged reminders.
100 * </pre>
102 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
103 * @param integer $batchSize number of patients to batch (default is 25; plan to optimize this default setting in the future)
104 * @param integer $report_id id of report in database (if already bookmarked)
105 * @param boolean $also_send if TRUE, then will also call send_reminder when done
106 * @return array see above for data structure of returned array
108 function update_reminders_batch_method($dateTarget = '', $batchSize = 25, $report_id = null, $also_send = false)
111 // Default to a batchsize, if empty
112 if (empty($batchSize)) {
113 $batchSize=25;
116 // Collect total number of pertinent patients (to calculate batching parameters)
117 $totalNumPatients = buildPatientArray('', '', '', null, null, true);
119 // Cycle through the batches and collect/combine results
120 if (($totalNumPatients%$batchSize) > 0) {
121 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
122 } else {
123 $totalNumberBatches = floor($totalNumPatients/$batchSize);
126 // Prepare the database to track/store results
127 if ($also_send) {
128 $report_id = beginReportDatabase("process_send_reminders", '', $report_id);
129 } else {
130 $report_id = beginReportDatabase("process_reminders", '', $report_id);
133 setTotalItemsReportDatabase($report_id, $totalNumPatients);
135 $patient_counter=0;
136 for ($i=0; $i<$totalNumberBatches; $i++) {
137 $patient_counter = $batchSize*($i+1);
138 if ($patient_counter > $totalNumPatients) {
139 $patient_counter = $totalNumPatients;
142 $update_rem_log_batch = update_reminders($dateTarget, '', (($batchSize*$i)+1), $batchSize);
143 if ($i == 0) {
144 // For first cycle, simply copy it to update_rem_log
145 $update_rem_log = $update_rem_log_batch;
146 } else {
147 // Debug statements
148 //error_log("CDR: ".print_r($update_rem_log,TRUE),0);
149 //error_log("CDR: ".($batchSize*$i). " records",0);
151 // Integrate batch results into main update_rem_log
152 $update_rem_log['total_active_actions'] = $update_rem_log['total_active_actions'] + $update_rem_log_batch['total_active_actions'];
153 $update_rem_log['total_pre_active_reminders'] = $update_rem_log['total_pre_active_reminders'] + $update_rem_log_batch['total_pre_active_reminders'];
154 $update_rem_log['total_pre_unsent_reminders'] = $update_rem_log['total_pre_unsent_reminders'] + $update_rem_log_batch['total_pre_unsent_reminders'];
155 $update_rem_log['number_new_reminders'] = $update_rem_log['number_new_reminders'] + $update_rem_log_batch['number_new_reminders'];
156 $update_rem_log['number_updated_reminders'] = $update_rem_log['number_updated_reminders'] + $update_rem_log_batch['number_updated_reminders'];
157 $update_rem_log['number_unchanged_reminders'] = $update_rem_log['number_unchanged_reminders'] + $update_rem_log_batch['number_unchanged_reminders'];
158 $update_rem_log['number_inactivated_reminders'] = $update_rem_log['number_inactivated_reminders'] + $update_rem_log_batch['number_inactivated_reminders'];
159 $update_rem_log['total_post_active_reminders'] = $update_rem_log['total_post_active_reminders'] + $update_rem_log_batch['total_post_active_reminders'];
160 $update_rem_log['total_post_unsent_reminders'] = $update_rem_log['total_post_unsent_reminders'] + $update_rem_log_batch['total_post_unsent_reminders'];
163 //Update database to track results
164 updateReportDatabase($report_id, $patient_counter);
167 // Create an array for saving to database (allows combining with the send log)
168 $save_log = array();
169 $save_log[] = $update_rem_log;
171 // Send reminders, if this was selected
172 if ($also_send) {
173 $log_send = send_reminders();
174 $save_log[] = $log_send;
177 // Record combo results in database
178 finishReportDatabase($report_id, json_encode($save_log));
180 // Just return the process reminders array
181 return $update_rem_log;
185 * Function to update reminders.
187 * Function that updates reminders and returns an array with a specific data structure.
188 * <pre>The data structure of the return array includes the following elements
189 * 'total_active_actions' - Number of active actions.
190 * 'total_pre_active_reminders' - Number of active reminders before processing.
191 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
192 * 'total_post_active_reminders' - Number of active reminders after processing.
193 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
194 * 'number_new_reminders' - Number of new reminders
195 * 'number_updated_reminders' - Number of updated reminders (due_status change)
196 * 'number_inactivated_reminders' - Number of inactivated reminders.
197 * 'number_unchanged_reminders' - Number of unchanged reminders.
198 * </pre>
200 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
201 * @param integer $patient_id pid of patient. If blank then will check all patients.
202 * @param integer $start applicable patient to start at (when batching process)
203 * @param integer $batchSize number of patients to batch (when batching process)
204 * @return array see above for data structure of returned array
206 function update_reminders($dateTarget = '', $patient_id = '', $start = null, $batchSize = null)
209 $logging = array();
211 // Set date to current if not set
212 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
214 // Collect reminders (note that this function removes redundant and keeps the most distant
215 // reminder (ie. prefers 'past_due' over 'due' over 'soon_due')
216 // Note that due to a limitation in the test_rules_clinic function, the patient_id is explicitly
217 // needed to work correctly. So rather than pass in a '' patient_id to do the entire clinic,
218 // we instead need to pass in each patient_id separately.
219 $collectedReminders = array();
220 $patient_id_complete = "";
221 if (!(empty($patient_id))) {
222 // only one patient id, so run the function
223 $collectedReminders = test_rules_clinic('', 'patient_reminder', $dateTarget, 'reminders-due', $patient_id);
224 $patient_id_complete = $patient_id;
225 } else {
226 // as described above, need to pass in each patient_id
227 // Collect all patient ids
228 $patientData = buildPatientArray('', '', '', $start, $batchSize);
229 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
230 $patientData[$iter]=$row;
233 $first_flag = true;
234 foreach ($patientData as $patient) {
235 // collect reminders
236 $tempCollectReminders = test_rules_clinic('', 'patient_reminder', $dateTarget, 'reminders-due', $patient['pid']);
237 $collectedReminders = array_merge($collectedReminders, $tempCollectReminders);
238 // build the $patient_id_complete variable
239 if ($first_flag) {
240 $patient_id_complete .= $patient['pid'];
241 $first_flag = false;
242 } else {
243 $patient_id_complete .= ",".$patient['pid'];
248 $logging['total_active_actions'] = count($collectedReminders);
250 // For logging purposes only:
251 // Collect number active of active and unsent reminders
252 $logging['total_pre_active_reminders'] = count(fetch_reminders($patient_id_complete));
253 $logging['total_pre_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
255 // Migrate reminders into the patient_reminders table
256 $logging['number_new_reminders'] = 0;
257 $logging['number_updated_reminders'] = 0;
258 $logging['number_unchanged_reminders'] = 0;
259 foreach ($collectedReminders as $reminder) {
260 // See if a reminder already exist
261 $sql = "SELECT `id`, `pid`, `due_status`, `category`, `item` FROM `patient_reminders` WHERE " .
262 "`active`='1' AND `pid`=? AND `category`=? AND `item`=?";
263 $result = sqlQueryCdrEngine($sql, array($reminder['pid'], $reminder['category'], $reminder['item']));
265 if (empty($result)) {
266 // It does not yet exist, so add a new reminder
267 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
268 "VALUES (?, ?, ?, ?, NOW())";
269 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']));
270 $logging['number_new_reminders']++;
271 } else {
272 // It already exist (see if if needs to be updated via adding a new reminder)
273 if ($reminder['due_status'] == $result['due_status']) {
274 // No change in due status, so no need to update
275 $logging['number_unchanged_reminders']++;
276 continue;
277 } else {
278 // Change in due status, so inactivate current reminder and create a new one
279 // First, inactivate the previous reminder
280 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'due_status_update', " .
281 "`date_inactivated` = NOW() WHERE `id`=?";
282 sqlStatementCdrEngine($sql, array($result['id']));
283 // Then, add the new reminder
284 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
285 "VALUES (?, ?, ?, ?, NOW())";
286 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']));
291 // Inactivate reminders that no longer exist
292 // Go through each active reminder and ensure it is in the current list
293 $sqlReminders = fetch_reminders($patient_id_complete);
294 $logging['number_inactivated_reminders'] = 0;
295 foreach ($sqlReminders as $row) {
296 $inactivateFlag = true;
297 foreach ($collectedReminders as $reminder) {
298 if (($row['pid'] == $reminder['pid']) &&
299 ($row['category'] == $reminder['category']) &&
300 ($row['item'] == $reminder['item']) &&
301 ($row['due_status'] == $reminder['due_status']) ) {
302 // The sql reminder has been confirmed, so do not inactivate it
303 $inactivateFlag = false;
304 break;
308 if ($inactivateFlag) {
309 // The sql reminder was not confirmed, so inactivate it
310 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'auto', " .
311 "`date_inactivated` = NOW() WHERE `id`=?";
312 sqlStatementCdrEngine($sql, array($row['id']));
313 $logging['number_inactivated_reminders']++;
317 // For logging purposes only:
318 // Collect number of active and unsent reminders
319 $logging['total_post_active_reminders'] = count(fetch_reminders($patient_id_complete));
320 $logging['total_post_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
322 return $logging;
327 * Function to send reminders.
329 * Function that sends reminders and returns an array with a specific data structure.
330 * <pre>The data structure of the return array includes the following elements
331 * 'total_pre_unsent_reminders' - Number of reminders before processing.
332 * 'total_post_unsent_reminders' - Number of reminders after processing.
333 * 'number_success_emails' - Number of successfully sent email reminders.
334 * 'number_failed_emails' - Number of failed sent email reminders.
335 * 'number_success_calls' - Number of successfully call reminders.
336 * 'number_failed_calls' - Number of failed call reminders.
337 * </pre>
339 * @return array see above for data structure of returned array
341 function send_reminders()
344 $logging = array();
346 // Collect active reminders that have not yet been sent.
347 $active_unsent_reminders = fetch_reminders('', 'unsent');
348 $logging['total_pre_unsent_reminders'] = count($active_unsent_reminders);
350 // Send the unsent reminders
351 $logging['number_success_emails'] = 0;
352 $logging['number_failed_emails'] = 0;
353 $logging['number_success_calls'] = 0;
354 $logging['number_failed_calls'] = 0;
355 foreach ($active_unsent_reminders as $reminder) {
356 // Collect patient information that reminder is going to.
357 $sql = "SELECT `fname`, `lname`, `email`, `phone_home`, `hipaa_voice`, `hipaa_allowemail` from `patient_data` where `pid`=?";
358 $result = sqlQueryCdrEngine($sql, array($reminder['pid']));
359 $patientfname = $result['fname'];
360 $patientlname = $result['lname'];
361 $patientemail = $result['email'];
362 $patientphone = $result['phone_home'];
363 $hipaa_voice = $result['hipaa_voice'];
364 $hipaa_allowemail = $result['hipaa_allowemail'];
366 // Email to patient if Allow Email and set reminder sent flag.
367 if ($hipaa_allowemail == "YES") {
368 $mail = new MyMailer();
369 $sender_name = $GLOBALS['patient_reminder_sender_name'];
370 $email_address = $GLOBALS['patient_reminder_sender_email'];
371 $mail->FromName = $sender_name; // required
372 $mail->Sender = $email_address; // required
373 $mail->From = $email_address; // required
374 $mail->AddAddress($patientemail, $patientfname.", ".$patientlname); // required
375 $mail->AddReplyTo($email_address, $sender_name); // required
376 $category_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'), $reminder['category']);
377 $item_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'), $reminder['item']);
378 $mail->Body = "Dear ".$patientfname.", This is a message from your clinic to remind you of your ".$category_title.": ".$item_title;
379 $mail->Subject = "Clinic Reminder";
380 if ($mail->Send()) {
381 // deal with and keep track of this successful email
382 sqlStatementCdrEngine("UPDATE `patient_reminders` SET `email_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']));
383 $logging['number_success_emails']++;
384 } else {
385 // deal with and keep track of this unsuccesful email
386 $logging['number_failed_emails']++;
390 // Call to patient if Allow Voice Message and set reminder sent flag.
391 if ($hipaa_voice == "YES") {
392 /******************************************************************************
393 * // Maviq does not work, is not currently supported, and seems to break on windows servers, so this
394 * // feature has been commented out for now.
395 * // Automated VOIP service provided by Maviq. Please visit http://signup.maviq.com for more information.
396 * $siteId = $GLOBALS['phone_gateway_username'];
397 * $cryptoGen = new CryptoGen();
398 * $token = $cryptoGen->decryptStandard($GLOBALS['phone_gateway_password']);
399 * $endpoint = $GLOBALS['phone_gateway_url'];
400 * $client = new MaviqClient($siteId, $token, $endpoint);
401 * //Set up params.
402 * $data = array(
403 * "firstName" => $patientfname,
404 * "lastName" => $patientlname,
405 * "phone" => $patientphone,
406 * //"apptDate" => "$scheduled_date[1]/$scheduled_date[2]/$scheduled_date[0]",
407 * "timeRange" => "10-18",
408 * "type" => "reminder",
409 * "timeZone" => date('P'),
410 * "greeting" => str_replace("[[sender]]", $sender_name, str_replace("[[patient_name]]", $patientfname, $myrow['reminder_content']))
411 * );
413 * // Make the call.
414 * $response = $client->sendRequest("appointment", "POST", $data);
416 * if ($response->IsError) {
417 * // deal with and keep track of this unsuccessful call
418 * $logging['number_failed_calls']++;
420 * else {
421 * // deal with and keep track of this succesful call
422 * sqlStatementCdrEngine("UPDATE `patient_reminders` SET `voice_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
423 * $logging['number_success_calls']++;
425 *******************************************************************************/
429 // For logging purposes only:
430 // Collect active reminders that have not yet been sent.
431 $logging['total_post_unsent_reminders'] = count(fetch_reminders('', 'unsent'));
433 return $logging;
437 * Function to fetch reminders.
439 * @param integer/array $patient_id pid(s) of patient(s).
440 * @param string $type Can choose unsent ('unsent') vs all active (BLANK) reminders
441 * @param string $due_status due status of reminders (soon_due,due,past_due). If blank, then will return all.
442 * @param string $select Select component of select statement. If blank, then will return all columns.
443 * @return array Returns an array of reminders.
445 function fetch_reminders($patient_id = '', $type = '', $due_status = '', $select = '*')
448 $arraySqlBind = array();
450 if (!empty($patient_id)) {
451 // check the specified pid(s)
452 $where = "`pid` IN (?) AND ";
453 array_push($arraySqlBind, $patient_id);
456 if (!empty($due_status)) {
457 $where .= "`due_status`=? AND ";
458 array_push($arraySqlBind, $due_status);
461 if (empty($type)) {
462 $where .= "`active`='1'";
463 } else { // $type == 'unsent'
464 $where .= "`active`='1' AND `date_sent` IS NULL";
467 $order = "`due_status`, `date_created`";
469 $sql = "SELECT " . $select . " FROM `patient_reminders` WHERE " .
470 $where . " ORDER BY " . $order;
471 $rez = sqlStatementCdrEngine($sql, $arraySqlBind);
473 $returnval=array();
474 for ($iter=0; $row=sqlFetchArray($rez); $iter++) {
475 $returnval[$iter]=$row;
478 return $returnval;