minor fix in hover for prior commit
[openemr.git] / library / reminders.php
blobf532c8e693f4003c84306824833360775269056e
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@sparmy.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@sparmy.com>
27 * @link http://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__) . "/classes/postmaster.php");
35 require_once(dirname(__FILE__) . "/maviq_phone_api.php");
37 /**
38 * Display the patient reminder widget.
40 * @param integer $patient_id pid of selected patient
41 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
43 function patient_reminder_widget($patient_id,$dateTarget='') {
45 // Set date to current if not set
46 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
48 // Update reminders for patient
49 update_reminders($dateTarget, $patient_id);
51 // Fetch the active reminders
52 $listReminders = fetch_reminders($patient_id);
54 if (empty($listReminders)) {
55 // No reminders to show.
56 echo htmlspecialchars( xl('No active patient reminders.'), ENT_NOQUOTES);
57 return;
60 echo "<table cellpadding='0' cellspacing='0'>";
61 foreach ($listReminders as $reminder) {
62 echo "<tr><td style='padding:0 1em 0 1em;'><span class='small'>";
63 // show reminder label
64 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$reminder['category']) .
65 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$reminder['item']);
66 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
67 // show reminder due status
68 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$reminder['due_status']);
69 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
70 // show reminder sent date
71 if (empty($reminder['date_sent'])) {
72 echo htmlspecialchars( xl('Reminder Not Sent Yet'), ENT_NOQUOTES);
74 else {
75 echo htmlspecialchars( xl('Reminder Sent On').": ".$reminder['date_sent'], ENT_NOQUOTES);
77 echo "</span></td></tr>";
79 echo "</table>";
82 /**
83 * Function to update reminders via a batching method to improve performance and decrease memory overhead.
85 * Function that updates reminders and returns an array with a specific data structure.
86 * <pre>The data structure of the return array includes the following elements
87 * 'total_active_actions' - Number of active actions.
88 * 'total_pre_active_reminders' - Number of active reminders before processing.
89 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
90 * 'total_post_active_reminders' - Number of active reminders after processing.
91 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
92 * 'number_new_reminders' - Number of new reminders
93 * 'number_updated_reminders' - Number of updated reminders (due_status change)
94 * 'number_inactivated_reminders' - Number of inactivated reminders.
95 * 'number_unchanged_reminders' - Number of unchanged reminders.
96 * </pre>
98 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
99 * @param integer $batchSize number of patients to batch (default is 25; plan to optimize this default setting in the future)
100 * @param integer $report_id id of report in database (if already bookmarked)
101 * @param boolean $also_send if TRUE, then will also call send_reminder when done
102 * @return array see above for data structure of returned array
104 function update_reminders_batch_method($dateTarget='', $batchSize=25, $report_id=NULL, $also_send=FALSE) {
106 // Default to a batchsize, if empty
107 if (empty($batchSize)) {
108 $batchSize=25;
111 // Collect total number of pertinent patients (to calculate batching parameters)
112 $totalNumPatients = buildPatientArray('','','',NULL,NULL,TRUE);
114 // Cycle through the batches and collect/combine results
115 if (($totalNumPatients%$batchSize) > 0) {
116 $totalNumberBatches = floor($totalNumPatients/$batchSize) + 1;
118 else {
119 $totalNumberBatches = floor($totalNumPatients/$batchSize);
122 // Prepare the database to track/store results
123 if ($also_send) {
124 $report_id = beginReportDatabase("process_send_reminders",'',$report_id);
126 else {
127 $report_id = beginReportDatabase("process_reminders",'',$report_id);
129 setTotalItemsReportDatabase($report_id,$totalNumPatients);
131 $patient_counter=0;
132 for ($i=0;$i<$totalNumberBatches;$i++) {
133 $patient_counter = $batchSize*($i+1);
134 if ($patient_counter > $totalNumPatients) $patient_counter = $totalNumPatients;
135 $update_rem_log_batch = update_reminders($dateTarget,'',(($batchSize*$i)+1),$batchSize);
136 if ($i == 0) {
137 // For first cycle, simply copy it to update_rem_log
138 $update_rem_log = $update_rem_log_batch;
140 else {
141 // Debug statements
142 //error_log("CDR: ".print_r($update_rem_log,TRUE),0);
143 //error_log("CDR: ".($batchSize*$i). " records",0);
145 // Integrate batch results into main update_rem_log
146 $update_rem_log['total_active_actions'] = $update_rem_log['total_active_actions'] + $update_rem_log_batch['total_active_actions'];
147 $update_rem_log['total_pre_active_reminders'] = $update_rem_log['total_pre_active_reminders'] + $update_rem_log_batch['total_pre_active_reminders'];
148 $update_rem_log['total_pre_unsent_reminders'] = $update_rem_log['total_pre_unsent_reminders'] + $update_rem_log_batch['total_pre_unsent_reminders'];
149 $update_rem_log['number_new_reminders'] = $update_rem_log['number_new_reminders'] + $update_rem_log_batch['number_new_reminders'];
150 $update_rem_log['number_updated_reminders'] = $update_rem_log['number_updated_reminders'] + $update_rem_log_batch['number_updated_reminders'];
151 $update_rem_log['number_unchanged_reminders'] = $update_rem_log['number_unchanged_reminders'] + $update_rem_log_batch['number_unchanged_reminders'];
152 $update_rem_log['number_inactivated_reminders'] = $update_rem_log['number_inactivated_reminders'] + $update_rem_log_batch['number_inactivated_reminders'];
153 $update_rem_log['total_post_active_reminders'] = $update_rem_log['total_post_active_reminders'] + $update_rem_log_batch['total_post_active_reminders'];
154 $update_rem_log['total_post_unsent_reminders'] = $update_rem_log['total_post_unsent_reminders'] + $update_rem_log_batch['total_post_unsent_reminders'];
156 //Update database to track results
157 updateReportDatabase($report_id,$patient_counter);
160 // Create an array for saving to database (allows combining with the send log)
161 $save_log = array();
162 $save_log[] = $update_rem_log;
164 // Send reminders, if this was selected
165 if ($also_send) {
166 $log_send = send_reminders();
167 $save_log[] = $log_send;
170 // Record combo results in database
171 finishReportDatabase($report_id,json_encode($save_log));
173 // Just return the process reminders array
174 return $update_rem_log;
178 * Function to update reminders.
180 * Function that updates reminders and returns an array with a specific data structure.
181 * <pre>The data structure of the return array includes the following elements
182 * 'total_active_actions' - Number of active actions.
183 * 'total_pre_active_reminders' - Number of active reminders before processing.
184 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
185 * 'total_post_active_reminders' - Number of active reminders after processing.
186 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
187 * 'number_new_reminders' - Number of new reminders
188 * 'number_updated_reminders' - Number of updated reminders (due_status change)
189 * 'number_inactivated_reminders' - Number of inactivated reminders.
190 * 'number_unchanged_reminders' - Number of unchanged reminders.
191 * </pre>
193 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
194 * @param integer $patient_id pid of patient. If blank then will check all patients.
195 * @param integer $start applicable patient to start at (when batching process)
196 * @param integer $batchSize number of patients to batch (when batching process)
197 * @return array see above for data structure of returned array
199 function update_reminders($dateTarget='', $patient_id='', $start=NULL, $batchSize=NULL) {
201 $logging = array();
203 // Set date to current if not set
204 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
206 // Collect reminders (note that this function removes redundant and keeps the most distant
207 // reminder (ie. prefers 'past_due' over 'due' over 'soon_due')
208 // Note that due to a limitation in the test_rules_clinic function, the patient_id is explicitly
209 // needed to work correctly. So rather than pass in a '' patient_id to do the entire clinic,
210 // we instead need to pass in each patient_id separately.
211 $collectedReminders = array();
212 $patient_id_complete = "";
213 if (!(empty($patient_id))) {
214 // only one patient id, so run the function
215 $collectedReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient_id);
216 $patient_id_complete = $patient_id;
218 else {
219 // as described above, need to pass in each patient_id
220 // Collect all patient ids
221 $patientData = buildPatientArray('','','',$start,$batchSize);
222 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
223 $patientData[$iter]=$row;
225 $first_flag = TRUE;
226 foreach ($patientData as $patient) {
227 // collect reminders
228 $tempCollectReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient['pid']);
229 $collectedReminders = array_merge($collectedReminders,$tempCollectReminders);
230 // build the $patient_id_complete variable
231 if ($first_flag) {
232 $patient_id_complete .= $patient['pid'];
233 $first_flag = FALSE;
235 else {
236 $patient_id_complete .= ",".$patient['pid'];
240 $logging['total_active_actions'] = count($collectedReminders);
242 // For logging purposes only:
243 // Collect number active of active and unsent reminders
244 $logging['total_pre_active_reminders'] = count(fetch_reminders($patient_id_complete));
245 $logging['total_pre_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
247 // Migrate reminders into the patient_reminders table
248 $logging['number_new_reminders'] = 0;
249 $logging['number_updated_reminders'] = 0;
250 $logging['number_unchanged_reminders'] = 0;
251 foreach ($collectedReminders as $reminder) {
253 // See if a reminder already exist
254 $sql = "SELECT `id`, `pid`, `due_status`, `category`, `item` FROM `patient_reminders` WHERE " .
255 "`active`='1' AND `pid`=? AND `category`=? AND `item`=?";
256 $result = sqlQueryCdrEngine($sql, array($reminder['pid'], $reminder['category'], $reminder['item']) );
258 if (empty($result)) {
259 // It does not yet exist, so add a new reminder
260 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
261 "VALUES (?, ?, ?, ?, NOW())";
262 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
263 $logging['number_new_reminders']++;
265 else {
266 // It already exist (see if if needs to be updated via adding a new reminder)
267 if ($reminder['due_status'] == $result['due_status']) {
268 // No change in due status, so no need to update
269 $logging['number_unchanged_reminders']++;
270 continue;
272 else {
273 // Change in due status, so inactivate current reminder and create a new one
274 // First, inactivate the previous reminder
275 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'due_status_update', " .
276 "`date_inactivated` = NOW() WHERE `id`=?";
277 sqlStatementCdrEngine($sql, array($result['id']) );
278 // Then, add the new reminder
279 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
280 "VALUES (?, ?, ?, ?, NOW())";
281 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
286 // Inactivate reminders that no longer exist
287 // Go through each active reminder and ensure it is in the current list
288 $sqlReminders = fetch_reminders($patient_id_complete);
289 $logging['number_inactivated_reminders'] = 0;
290 foreach ( $sqlReminders as $row ) {
291 $inactivateFlag = true;
292 foreach ($collectedReminders as $reminder) {
293 if ( ($row['pid'] == $reminder['pid']) &&
294 ($row['category'] == $reminder['category']) &&
295 ($row['item'] == $reminder['item']) &&
296 ($row['due_status'] == $reminder['due_status']) ) {
297 // The sql reminder has been confirmed, so do not inactivate it
298 $inactivateFlag = false;
299 break;
302 if ($inactivateFlag) {
303 // The sql reminder was not confirmed, so inactivate it
304 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'auto', " .
305 "`date_inactivated` = NOW() WHERE `id`=?";
306 sqlStatementCdrEngine($sql, array($row['id']) );
307 $logging['number_inactivated_reminders']++;
311 // For logging purposes only:
312 // Collect number of active and unsent reminders
313 $logging['total_post_active_reminders'] = count(fetch_reminders($patient_id_complete));
314 $logging['total_post_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
316 return $logging;
321 * Function to send reminders.
323 * Function that sends reminders and returns an array with a specific data structure.
324 * <pre>The data structure of the return array includes the following elements
325 * 'total_pre_unsent_reminders' - Number of reminders before processing.
326 * 'total_post_unsent_reminders' - Number of reminders after processing.
327 * 'number_success_emails' - Number of successfully sent email reminders.
328 * 'number_failed_emails' - Number of failed sent email reminders.
329 * 'number_success_calls' - Number of successfully call reminders.
330 * 'number_failed_calls' - Number of failed call reminders.
331 * </pre>
333 * @return array see above for data structure of returned array
335 function send_reminders() {
337 $logging = array();
339 // Collect active reminders that have not yet been sent.
340 $active_unsent_reminders = fetch_reminders('', 'unsent');
341 $logging['total_pre_unsent_reminders'] = count($active_unsent_reminders);
343 // Send the unsent reminders
344 $logging['number_success_emails'] = 0;
345 $logging['number_failed_emails'] = 0;
346 $logging['number_success_calls'] = 0;
347 $logging['number_failed_calls'] = 0;
348 foreach ( $active_unsent_reminders as $reminder ) {
350 // Collect patient information that reminder is going to.
351 $sql = "SELECT `fname`, `lname`, `email`, `phone_home`, `hipaa_voice`, `hipaa_allowemail` from `patient_data` where `pid`=?";
352 $result = sqlQueryCdrEngine($sql, array($reminder['pid']) );
353 $patientfname = $result['fname'];
354 $patientlname = $result['lname'];
355 $patientemail = $result['email'];
356 $patientphone = $result['phone_home'];
357 $hipaa_voice = $result['hipaa_voice'];
358 $hipaa_allowemail = $result['hipaa_allowemail'];
360 // Email to patient if Allow Email and set reminder sent flag.
361 if ($hipaa_allowemail == "YES") {
362 $mail = new MyMailer();
363 $sender_name = $GLOBALS['patient_reminder_sender_name'];
364 $email_address = $GLOBALS['patient_reminder_sender_email'];
365 $mail->FromName = $sender_name; // required
366 $mail->Sender = $email_address; // required
367 $mail->From = $email_address; // required
368 $mail->AddAddress($patientemail, $patientfname.", ".$patientlname); // required
369 $mail->AddReplyTo($email_address,$sender_name); // required
370 $category_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$reminder['category']);
371 $item_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$reminder['item']);
372 $mail->Body = "Dear ".$patientfname.", This is a message from your clinic to remind you of your ".$category_title.": ".$item_title;
373 $mail->Subject = "Clinic Reminder";
374 if ($mail->Send()) {
375 // deal with and keep track of this successful email
376 sqlStatementCdrEngine("UPDATE `patient_reminders` SET `email_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
377 $logging['number_success_emails']++;
379 else {
380 // deal with and keep track of this unsuccesful email
381 $logging['number_failed_emails']++;
385 // Call to patient if Allow Voice Message and set reminder sent flag.
386 if ($hipaa_voice == "YES") {
388 /******************************************************************************
389 * // Maviq does not work, is not currently supported, and seems to break on windows servers, so this
390 * // feature has been commented out for now.
391 * // Automated VOIP service provided by Maviq. Please visit http://signup.maviq.com for more information.
392 * $siteId = $GLOBALS['phone_gateway_username'];
393 * $token = $GLOBALS['phone_gateway_password'];
394 * $endpoint = $GLOBALS['phone_gateway_url'];
395 * $client = new MaviqClient($siteId, $token, $endpoint);
396 * //Set up params.
397 * $data = array(
398 * "firstName" => $patientfname,
399 * "lastName" => $patientlname,
400 * "phone" => $patientphone,
401 * //"apptDate" => "$scheduled_date[1]/$scheduled_date[2]/$scheduled_date[0]",
402 * "timeRange" => "10-18",
403 * "type" => "reminder",
404 * "timeZone" => date('P'),
405 * "greeting" => str_replace("[[sender]]", $sender_name, str_replace("[[patient_name]]", $patientfname, $myrow['reminder_content']))
406 * );
408 * // Make the call.
409 * $response = $client->sendRequest("appointment", "POST", $data);
411 * if ($response->IsError) {
412 * // deal with and keep track of this unsuccessful call
413 * $logging['number_failed_calls']++;
415 * else {
416 * // deal with and keep track of this succesful call
417 * sqlStatementCdrEngine("UPDATE `patient_reminders` SET `voice_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
418 * $logging['number_success_calls']++;
420 *******************************************************************************/
425 // For logging purposes only:
426 // Collect active reminders that have not yet been sent.
427 $logging['total_post_unsent_reminders'] = count(fetch_reminders('', 'unsent'));
429 return $logging;
433 * Function to fetch reminders.
435 * @param integer/array $patient_id pid(s) of patient(s).
436 * @param string $type Can choose unsent ('unsent') vs all active (BLANK) reminders
437 * @param string $due_status due status of reminders (soon_due,due,past_due). If blank, then will return all.
438 * @param string $select Select component of select statement. If blank, then will return all columns.
439 * @return array Returns an array of reminders.
441 function fetch_reminders($patient_id='',$type='',$due_status='',$select='*') {
443 $arraySqlBind = array();
445 if (!empty($patient_id)) {
446 // check the specified pid(s)
447 $where = "`pid` IN (?) AND ";
448 array_push($arraySqlBind,$patient_id);
451 if (!empty($due_status)) {
452 $where .= "`due_status`=? AND ";
453 array_push($arraySqlBind,$due_status);
456 if (empty($type)) {
457 $where .= "`active`='1'";
459 else { // $type == 'unsent'
460 $where .= "`active`='1' AND `date_sent` IS NULL";
463 $order = "`due_status`, `date_created`";
465 $sql = "SELECT " . $select . " FROM `patient_reminders` WHERE " .
466 $where . " ORDER BY " . $order;
467 $rez = sqlStatementCdrEngine($sql, $arraySqlBind);
469 $returnval=array();
470 for($iter=0; $row=sqlFetchArray($rez); $iter++)
471 $returnval[$iter]=$row;
473 return $returnval;