124bddf04db035eb3358e3e4784c410cc7c8fb0c
[openemr.git] / library / reminders.php
blob124bddf04db035eb3358e3e4784c410cc7c8fb0c
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 and email class
33 require_once(dirname(__FILE__) . "/clinical_rules.php");
34 require_once(dirname(__FILE__) . "/classes/postmaster.php");
36 // This is only pertinent for users of php versions less than 5.2
37 // (ie. this wrapper is only loaded when php version is less than
38 // 5.2; otherwise the native php json functions are used)
39 require_once(dirname(__FILE__) . "/jsonwrapper/jsonwrapper.php");
41 /**
42 * Display the patient reminder widget.
44 * @param integer $patient_id pid of selected patient
45 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
47 function patient_reminder_widget($patient_id,$dateTarget='') {
49 // Set date to current if not set
50 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
52 // Update reminders for patient
53 update_reminders($dateTarget, $patient_id);
55 // Fetch the active reminders
56 $listReminders = fetch_reminders($patient_id);
58 if (empty($listReminders)) {
59 // No reminders to show.
60 echo htmlspecialchars( xl('No active patient reminders.'), ENT_NOQUOTES);
61 return;
64 echo "<table cellpadding='0' cellspacing='0'>";
65 foreach ($listReminders as $reminder) {
66 echo "<tr><td style='padding:0 1em 0 1em;'><span class='small'>";
67 // show reminder label
68 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$reminder['category']) .
69 ": " . generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$reminder['item']);
70 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
71 // show reminder due status
72 echo generate_display_field(array('data_type'=>'1','list_id'=>'rule_reminder_due_opt'),$reminder['due_status']);
73 echo "</span></td><td style='padding:0 1em 0 1em;'><span class='small'>";
74 // show reminder sent date
75 if (empty($reminder['date_sent'])) {
76 echo htmlspecialchars( xl('Reminder Not Sent Yet'), ENT_NOQUOTES);
78 else {
79 echo htmlspecialchars( xl('Reminder Sent On').": ".$reminder['date_sent'], ENT_NOQUOTES);
81 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) {
110 // Default to a batchsize, if empty
111 if (empty($batchSize)) {
112 $batchSize=25;
115 // Collect total number of pertinent patients (to calculate batching parameters)
116 $totalNumPatients = buildPatientArray('','','',NULL,NULL,TRUE);
118 // Cycle through the batches and collect/combine results
119 if (($totalNumPatients%$batchSize) > 0) {
120 $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);
130 else {
131 $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) $patient_counter = $totalNumPatients;
139 $update_rem_log_batch = update_reminders($dateTarget,'',(($batchSize*$i)+1),$batchSize);
140 if ($i == 0) {
141 // For first cycle, simply copy it to update_rem_log
142 $update_rem_log = $update_rem_log_batch;
144 else {
145 // Debug statements
146 //error_log("CDR: ".print_r($update_rem_log,TRUE),0);
147 //error_log("CDR: ".($batchSize*$i). " records",0);
149 // Integrate batch results into main update_rem_log
150 $update_rem_log['total_active_actions'] = $update_rem_log['total_active_actions'] + $update_rem_log_batch['total_active_actions'];
151 $update_rem_log['total_pre_active_reminders'] = $update_rem_log['total_pre_active_reminders'] + $update_rem_log_batch['total_pre_active_reminders'];
152 $update_rem_log['total_pre_unsent_reminders'] = $update_rem_log['total_pre_unsent_reminders'] + $update_rem_log_batch['total_pre_unsent_reminders'];
153 $update_rem_log['number_new_reminders'] = $update_rem_log['number_new_reminders'] + $update_rem_log_batch['number_new_reminders'];
154 $update_rem_log['number_updated_reminders'] = $update_rem_log['number_updated_reminders'] + $update_rem_log_batch['number_updated_reminders'];
155 $update_rem_log['number_unchanged_reminders'] = $update_rem_log['number_unchanged_reminders'] + $update_rem_log_batch['number_unchanged_reminders'];
156 $update_rem_log['number_inactivated_reminders'] = $update_rem_log['number_inactivated_reminders'] + $update_rem_log_batch['number_inactivated_reminders'];
157 $update_rem_log['total_post_active_reminders'] = $update_rem_log['total_post_active_reminders'] + $update_rem_log_batch['total_post_active_reminders'];
158 $update_rem_log['total_post_unsent_reminders'] = $update_rem_log['total_post_unsent_reminders'] + $update_rem_log_batch['total_post_unsent_reminders'];
160 //Update database to track results
161 updateReportDatabase($report_id,$patient_counter);
164 // Create an array for saving to database (allows combining with the send log)
165 $save_log = array();
166 $save_log[] = $update_rem_log;
168 // Send reminders, if this was selected
169 if ($also_send) {
170 $log_send = send_reminders();
171 $save_log[] = $log_send;
174 // Record combo results in database
175 finishReportDatabase($report_id,json_encode($save_log));
177 // Just return the process reminders array
178 return $update_rem_log;
182 * Function to update reminders.
184 * Function that updates reminders and returns an array with a specific data structure.
185 * <pre>The data structure of the return array includes the following elements
186 * 'total_active_actions' - Number of active actions.
187 * 'total_pre_active_reminders' - Number of active reminders before processing.
188 * 'total_pre_unsent_reminders' - Number of unsent reminders before processing.
189 * 'total_post_active_reminders' - Number of active reminders after processing.
190 * 'total_post_unsent_reminders' - Number of unsent reminders after processing.
191 * 'number_new_reminders' - Number of new reminders
192 * 'number_updated_reminders' - Number of updated reminders (due_status change)
193 * 'number_inactivated_reminders' - Number of inactivated reminders.
194 * 'number_unchanged_reminders' - Number of unchanged reminders.
195 * </pre>
197 * @param string $dateTarget target date (format Y-m-d H:i:s). If blank then will test with current date as target.
198 * @param integer $patient_id pid of patient. If blank then will check all patients.
199 * @param integer $start applicable patient to start at (when batching process)
200 * @param integer $batchSize number of patients to batch (when batching process)
201 * @return array see above for data structure of returned array
203 function update_reminders($dateTarget='', $patient_id='', $start=NULL, $batchSize=NULL) {
205 $logging = array();
207 // Set date to current if not set
208 $dateTarget = ($dateTarget) ? $dateTarget : date('Y-m-d H:i:s');
210 // Collect reminders (note that this function removes redundant and keeps the most distant
211 // reminder (ie. prefers 'past_due' over 'due' over 'soon_due')
212 // Note that due to a limitation in the test_rules_clinic function, the patient_id is explicitly
213 // needed to work correctly. So rather than pass in a '' patient_id to do the entire clinic,
214 // we instead need to pass in each patient_id separately.
215 $collectedReminders = array();
216 $patient_id_complete = "";
217 if (!(empty($patient_id))) {
218 // only one patient id, so run the function
219 $collectedReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient_id);
220 $patient_id_complete = $patient_id;
222 else {
223 // as described above, need to pass in each patient_id
224 // Collect all patient ids
225 $patientData = buildPatientArray('','','',$start,$batchSize);
226 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
227 $patientData[$iter]=$row;
229 $first_flag = TRUE;
230 foreach ($patientData as $patient) {
231 // collect reminders
232 $tempCollectReminders = test_rules_clinic('','patient_reminder',$dateTarget,'reminders-due',$patient['pid']);
233 $collectedReminders = array_merge($collectedReminders,$tempCollectReminders);
234 // build the $patient_id_complete variable
235 if ($first_flag) {
236 $patient_id_complete .= $patient['pid'];
237 $first_flag = FALSE;
239 else {
240 $patient_id_complete .= ",".$patient['pid'];
244 $logging['total_active_actions'] = count($collectedReminders);
246 // For logging purposes only:
247 // Collect number active of active and unsent reminders
248 $logging['total_pre_active_reminders'] = count(fetch_reminders($patient_id_complete));
249 $logging['total_pre_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
251 // Migrate reminders into the patient_reminders table
252 $logging['number_new_reminders'] = 0;
253 $logging['number_updated_reminders'] = 0;
254 $logging['number_unchanged_reminders'] = 0;
255 foreach ($collectedReminders as $reminder) {
257 // See if a reminder already exist
258 $sql = "SELECT `id`, `pid`, `due_status`, `category`, `item` FROM `patient_reminders` WHERE " .
259 "`active`='1' AND `pid`=? AND `category`=? AND `item`=?";
260 $result = sqlQueryCdrEngine($sql, array($reminder['pid'], $reminder['category'], $reminder['item']) );
262 if (empty($result)) {
263 // It does not yet exist, so add a new reminder
264 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
265 "VALUES (?, ?, ?, ?, NOW())";
266 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
267 $logging['number_new_reminders']++;
269 else {
270 // It already exist (see if if needs to be updated via adding a new reminder)
271 if ($reminder['due_status'] == $result['due_status']) {
272 // No change in due status, so no need to update
273 $logging['number_unchanged_reminders']++;
274 continue;
276 else {
277 // Change in due status, so inactivate current reminder and create a new one
278 // First, inactivate the previous reminder
279 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'due_status_update', " .
280 "`date_inactivated` = NOW() WHERE `id`=?";
281 sqlStatementCdrEngine($sql, array($result['id']) );
282 // Then, add the new reminder
283 $sql = "INSERT INTO `patient_reminders` (`pid`, `due_status`, `category`, `item`, `date_created`) " .
284 "VALUES (?, ?, ?, ?, NOW())";
285 sqlStatementCdrEngine($sql, array($reminder['pid'], $reminder['due_status'], $reminder['category'], $reminder['item']) );
290 // Inactivate reminders that no longer exist
291 // Go through each active reminder and ensure it is in the current list
292 $sqlReminders = fetch_reminders($patient_id_complete);
293 $logging['number_inactivated_reminders'] = 0;
294 foreach ( $sqlReminders as $row ) {
295 $inactivateFlag = true;
296 foreach ($collectedReminders as $reminder) {
297 if ( ($row['pid'] == $reminder['pid']) &&
298 ($row['category'] == $reminder['category']) &&
299 ($row['item'] == $reminder['item']) &&
300 ($row['due_status'] == $reminder['due_status']) ) {
301 // The sql reminder has been confirmed, so do not inactivate it
302 $inactivateFlag = false;
303 break;
306 if ($inactivateFlag) {
307 // The sql reminder was not confirmed, so inactivate it
308 $sql = "UPDATE `patient_reminders` SET `active` = '0', `reason_inactivated` = 'auto', " .
309 "`date_inactivated` = NOW() WHERE `id`=?";
310 sqlStatementCdrEngine($sql, array($row['id']) );
311 $logging['number_inactivated_reminders']++;
315 // For logging purposes only:
316 // Collect number of active and unsent reminders
317 $logging['total_post_active_reminders'] = count(fetch_reminders($patient_id_complete));
318 $logging['total_post_unsent_reminders'] = count(fetch_reminders($patient_id_complete, 'unsent'));
320 return $logging;
325 * Function to send reminders.
327 * Function that sends reminders and returns an array with a specific data structure.
328 * <pre>The data structure of the return array includes the following elements
329 * 'total_pre_unsent_reminders' - Number of reminders before processing.
330 * 'total_post_unsent_reminders' - Number of reminders after processing.
331 * 'number_success_emails' - Number of successfully sent email reminders.
332 * 'number_failed_emails' - Number of failed sent email reminders.
333 * 'number_success_calls' - Number of successfully call reminders.
334 * 'number_failed_calls' - Number of failed call reminders.
335 * </pre>
337 * @return array see above for data structure of returned array
339 function send_reminders() {
341 $logging = array();
343 // Collect active reminders that have not yet been sent.
344 $active_unsent_reminders = fetch_reminders('', 'unsent');
345 $logging['total_pre_unsent_reminders'] = count($active_unsent_reminders);
347 // Send the unsent reminders
348 $logging['number_success_emails'] = 0;
349 $logging['number_failed_emails'] = 0;
350 $logging['number_success_calls'] = 0;
351 $logging['number_failed_calls'] = 0;
352 foreach ( $active_unsent_reminders as $reminder ) {
354 // Collect patient information that reminder is going to.
355 $sql = "SELECT `fname`, `lname`, `email`, `phone_home`, `hipaa_voice`, `hipaa_allowemail` from `patient_data` where `pid`=?";
356 $result = sqlQueryCdrEngine($sql, array($reminder['pid']) );
357 $patientfname = $result['fname'];
358 $patientlname = $result['lname'];
359 $patientemail = $result['email'];
360 $patientphone = $result['phone_home'];
361 $hipaa_voice = $result['hipaa_voice'];
362 $hipaa_allowemail = $result['hipaa_allowemail'];
364 // Email to patient if Allow Email and set reminder sent flag.
365 if ($hipaa_allowemail == "YES") {
366 $mail = new MyMailer();
367 $sender_name = $GLOBALS['patient_reminder_sender_name'];
368 $email_address = $GLOBALS['patient_reminder_sender_email'];
369 $mail->FromName = $sender_name; // required
370 $mail->Sender = $email_address; // required
371 $mail->From = $email_address; // required
372 $mail->AddAddress($patientemail, $patientfname.", ".$patientlname); // required
373 $mail->AddReplyTo($email_address,$sender_name); // required
374 $category_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action_category'),$reminder['category']);
375 $item_title = generate_display_field(array('data_type'=>'1','list_id'=>'rule_action'),$reminder['item']);
376 $mail->Body = "Dear ".$patientfname.", This is a message from your clinic to remind you of your ".$category_title.": ".$item_title;
377 $mail->Subject = "Clinic Reminder";
378 if ($mail->Send()) {
379 // deal with and keep track of this successful email
380 sqlStatementCdrEngine("UPDATE `patient_reminders` SET `email_status`='1', `date_sent`=NOW() WHERE id=?", array($reminder['id']) );
381 $logging['number_success_emails']++;
383 else {
384 // deal with and keep track of this unsuccesful email
385 $logging['number_failed_emails']++;
389 // Call to patient if Allow Voice Message and set reminder sent flag.
390 if ($hipaa_voice == "YES") {
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']))
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']++;
423 // For logging purposes only:
424 // Collect active reminders that have not yet been sent.
425 $logging['total_post_unsent_reminders'] = count(fetch_reminders('', 'unsent'));
427 return $logging;
431 * Function to fetch reminders.
433 * @param integer/array $patient_id pid(s) of patient(s).
434 * @param string $type Can choose unsent ('unsent') vs all active (BLANK) reminders
435 * @param string $due_status due status of reminders (soon_due,due,past_due). If blank, then will return all.
436 * @param string $select Select component of select statement. If blank, then will return all columns.
437 * @return array Returns an array of reminders.
439 function fetch_reminders($patient_id='',$type='',$due_status='',$select='*') {
441 $arraySqlBind = array();
443 if (!empty($patient_id)) {
444 // check the specified pid(s)
445 $where = "`pid` IN (".add_escape_custom($patient_id).") AND ";
448 if (!empty($due_status)) {
449 $where .= "`due_status`=? AND ";
450 array_push($arraySqlBind,$due_status);
453 if (empty($type)) {
454 $where .= "`active`='1'";
456 else { // $type == 'unsent'
457 $where .= "`active`='1' AND `date_sent` IS NULL";
460 $order = "`due_status`, `date_created`";
462 $sql = "SELECT " . $select . " FROM `patient_reminders` WHERE " .
463 $where . " ORDER BY " . $order;
464 $rez = sqlStatementCdrEngine($sql, $arraySqlBind);
466 $returnval=array();
467 for($iter=0; $row=sqlFetchArray($rez); $iter++)
468 $returnval[$iter]=$row;
470 return $returnval;