Eye Form tweaks
[openemr.git] / library / appointments.inc.php
blob3ab7061004b21967b08f57bdf292f8a73520a3ba
1 <?php
3 // Copyright (C) 2011 Ken Chapple
4 //
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // Holds library functions (and hashes) used by the appointment reporting module
14 require_once(dirname(__FILE__)."/encounter_events.inc.php");
15 require_once(dirname(__FILE__)."/../interface/main/calendar/modules/PostCalendar/pnincludes/Date/Calc.php");
18 $COMPARE_FUNCTION_HASH = array(
19 'doctor' => 'compareAppointmentsByDoctorName',
20 'patient' => 'compareAppointmentsByPatientName',
21 'pubpid' => 'compareAppointmentsByPatientId',
22 'date' => 'compareAppointmentsByDate',
23 'time' => 'compareAppointmentsByTime',
24 'type' => 'compareAppointmentsByType',
25 'comment' => 'compareAppointmentsByComment',
26 'status' => 'compareAppointmentsByStatus',
27 'completed' => 'compareAppointmentsByCompletedDrugScreen',
28 'trackerstatus' => 'compareAppointmentsByTrackerStatus'
31 $ORDERHASH = array(
32 'doctor' => array( 'doctor', 'date', 'time' ),
33 'patient' => array( 'patient', 'date', 'time' ),
34 'pubpid' => array( 'pubpid', 'date', 'time' ),
35 'date' => array( 'date', 'time', 'type', 'patient' ),
36 'time' => array( 'time', 'date', 'patient' ),
37 'type' => array( 'type', 'date', 'time', 'patient' ),
38 'comment' => array( 'comment', 'date', 'time', 'patient' ),
39 'status' => array( 'status', 'date', 'time', 'patient' ),
40 'completed' => array( 'completed', 'date', 'time', 'patient' ),
41 'trackerstatus' => array( 'trackerstatus', 'date', 'time', 'patient' ),
44 /*Arrays for the interpretation of recurrence patterns.*/
45 $REPEAT_FREQ = array(
46 '1' => xl('Every'),
47 '2' => xl('Every 2nd'),
48 '3' => xl('Every 3rd'),
49 '4' => xl('Every 4th'),
50 '5' => xl('Every 5th'),
51 '6' => xl('Every 6th')
54 $REPEAT_FREQ_TYPE = array(
55 '0' => xl('day'),
56 '1' => xl('week'),
57 '2' => xl('month'),
58 '3' => xl('year'),
59 '4' => xl('workday')
62 $REPEAT_ON_NUM = array(
63 '1' => xl('1st'),
64 '2' => xl('2nd'),
65 '3' => xl('3rd'),
66 '4' => xl('4th'),
67 '5' => xl('Last')
70 $REPEAT_ON_DAY = array(
71 '0' => xl('Sunday'),
72 '1' => xl('Monday'),
73 '2' => xl('Tuesday'),
74 '3' => xl('Wednesday'),
75 '4' => xl('Thursday'),
76 '5' => xl('Friday'),
77 '6' => xl('Saturday')
80 function fetchEvents( $from_date, $to_date, $where_param = null, $orderby_param = null, $tracker_board = false, $nextX = 0, $bind_param = null, $query_param = null )
83 $sqlBindArray = array();
85 if($query_param) {
87 $query = $query_param;
89 if($bind_param) $sqlBindArray = $bind_param;
91 } else {
92 //////
93 if($nextX) {
95 $where =
96 "((e.pc_endDate >= ? AND e.pc_recurrtype > '0') OR " .
97 "(e.pc_eventDate >= ?))";
99 array_push($sqlBindArray, $from_date, $from_date);
101 } else {
102 //////
103 $where =
104 "((e.pc_endDate >= ? AND e.pc_eventDate <= ? AND e.pc_recurrtype > '0') OR " .
105 "(e.pc_eventDate >= ? AND e.pc_eventDate <= ?))";
107 array_push($sqlBindArray, $from_date, $to_date, $from_date, $to_date);
111 if ( $where_param ) $where .= $where_param;
113 $order_by = "e.pc_eventDate, e.pc_startTime";
114 if ( $orderby_param ) {
115 $order_by = $orderby_param;
118 // Tracker Board specific stuff
119 $tracker_fields = '';
120 $tracker_joins = '';
121 if ($tracker_board) {
122 $tracker_fields = "e.pc_room, e.pc_pid, t.id, t.date, t.apptdate, t.appttime, t.eid, t.pid, t.original_user, t.encounter, t.lastseq, t.random_drug_test, t.drug_screen_completed, " .
123 "q.pt_tracker_id, q.start_datetime, q.room, q.status, q.seq, q.user, " .
124 "s.toggle_setting_1, s.toggle_setting_2, s.option_id, ";
125 $tracker_joins = "LEFT OUTER JOIN patient_tracker AS t ON t.pid = e.pc_pid AND t.apptdate = e.pc_eventDate AND t.appttime = e.pc_starttime AND t.eid = e.pc_eid " .
126 "LEFT OUTER JOIN patient_tracker_element AS q ON q.pt_tracker_id = t.id AND q.seq = t.lastseq " .
127 "LEFT OUTER JOIN list_options AS s ON s.list_id = 'apptstat' AND s.option_id = q.status " ;
130 $query = "SELECT " .
131 "e.pc_eventDate, e.pc_endDate, e.pc_startTime, e.pc_endTime, e.pc_duration, e.pc_recurrtype, e.pc_recurrspec, e.pc_recurrfreq, e.pc_catid, e.pc_eid, " .
132 "e.pc_title, e.pc_hometext, e.pc_apptstatus, " .
133 "p.fname, p.mname, p.lname, p.pid, p.pubpid, p.phone_home, p.phone_cell, " .
134 "u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, " .
135 "f.name, " .
136 "$tracker_fields" .
137 "c.pc_catname, c.pc_catid " .
138 "FROM openemr_postcalendar_events AS e " .
139 "$tracker_joins" .
140 "LEFT OUTER JOIN facility AS f ON e.pc_facility = f.id " .
141 "LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid " .
142 "LEFT OUTER JOIN users AS u ON u.id = e.pc_aid " .
143 "LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid " .
144 "WHERE $where " .
145 "ORDER BY $order_by";
147 if($bind_param) $sqlBindArray = array_merge($sqlBindArray, $bind_param);
152 ///////////////////////////////////////////////////////////////////////
153 // The following code is from the calculateEvents function in the //
154 // PostCalendar Module modified and inserted here by epsdky //
155 ///////////////////////////////////////////////////////////////////////
157 $events2 = array();
159 $res = sqlStatement($query, $sqlBindArray);
161 ////////
162 if($nextX) {
163 global $resNotNull;
164 $resNotNull = (isset($res) && $res != null);
167 while ($event = sqlFetchArray($res)) {
168 ///////
169 if($nextX) $stopDate = $event['pc_endDate'];
170 else $stopDate = ($event['pc_endDate'] <= $to_date) ? $event['pc_endDate'] : $to_date;
171 ///////
172 $incX = 0;
173 switch($event['pc_recurrtype']) {
175 case '0' :
177 $events2[] = $event;
179 break;
180 //////
181 case '1' :
182 case '3' :
183 $event_recurrspec = @unserialize($event['pc_recurrspec']);
185 $rfreq = $event_recurrspec['event_repeat_freq'];
186 $rtype = $event_recurrspec['event_repeat_freq_type'];
187 $exdate = $event_recurrspec['exdate'];
189 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
190 // $occurance = Date_Calc::dateFormat($nd,$nm,$ny,'%Y-%m-%d');
191 $occurance = $event['pc_eventDate'];
193 while($occurance < $from_date) {
194 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
195 list($ny,$nm,$nd) = explode('-',$occurance);
198 while($occurance <= $stopDate) {
200 $excluded = false;
201 if (isset($exdate)) {
202 foreach (explode(",", $exdate) as $exception) {
203 // occurrance format == yyyy-mm-dd
204 // exception format == yyyymmdd
205 if (preg_replace("/-/", "", $occurance) == $exception) {
206 $excluded = true;
211 if ($excluded == false) {
212 $event['pc_eventDate'] = $occurance;
213 $event['pc_endDate'] = '0000-00-00';
214 $events2[] = $event;
215 //////
216 if ($nextX) {
217 ++$incX;
218 if($incX == $nextX) break;
220 //////
223 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
224 list($ny,$nm,$nd) = explode('-',$occurance);
228 break;
230 //////
231 case '2' :
233 $event_recurrspec = @unserialize($event['pc_recurrspec']);
235 $rfreq = $event_recurrspec['event_repeat_on_freq'];
236 $rnum = $event_recurrspec['event_repeat_on_num'];
237 $rday = $event_recurrspec['event_repeat_on_day'];
238 $exdate = $event_recurrspec['exdate'];
240 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
242 $occuranceYm = "$ny-$nm"; // YYYY-mm
243 $from_dateYm = substr($from_date,0,7); // YYYY-mm
244 $stopDateYm = substr($stopDate,0,7); // YYYY-mm
246 // $nd will sometimes be 29, 30 or 31, and if used in mktime below, a problem
247 // with overflow will occur ('01' should be plugged in to avoid this). We need
248 // to mirror the calendar code which has this problem, so $nd has been used.
249 while($occuranceYm < $from_dateYm) {
250 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
251 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
252 $occuranceYm = "$ny-$nm";
255 while($occuranceYm <= $stopDateYm) {
257 // (YYYY-mm)-dd
258 $dnum = $rnum;
259 do {
260 $occurance = Date_Calc::NWeekdayOfMonth($dnum--,$rday,$nm,$ny,$format="%Y-%m-%d");
261 } while($occurance === -1);
263 if($occurance >= $from_date && $occurance <= $stopDate) {
265 $excluded = false;
266 if (isset($exdate)) {
267 foreach (explode(",", $exdate) as $exception) {
268 // occurrance format == yyyy-mm-dd
269 // exception format == yyyymmdd
270 if (preg_replace("/-/", "", $occurance) == $exception) {
271 $excluded = true;
276 if ($excluded == false) {
278 $event['pc_eventDate'] = $occurance;
279 $event['pc_endDate'] = '0000-00-00';
280 $events2[] = $event;
281 //////
282 if($nextX) {
283 ++$incX;
284 if($incX == $nextX) break;
286 //////
292 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
293 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
294 $occuranceYm = "$ny-$nm";
298 break;
305 return $events2;
306 ////////////////////// End of code inserted by epsdky
309 function fetchAllEvents( $from_date, $to_date, $provider_id = null, $facility_id = null )
311 $sqlBindArray = array();
313 $where = "";
315 if ( $provider_id ) {
316 $where .= " AND e.pc_aid = ?";
317 array_push($sqlBindArray, $provider_id);
320 if ( $facility_id ) {
321 $where .= " AND e.pc_facility = ? AND u.facility_id = ?";
322 array_push($sqlBindArray, $facility_id, $facility_id);
325 $appointments = fetchEvents( $from_date, $to_date, $where, null, false, 0, $sqlBindArray );
326 return $appointments;
329 function fetchAppointments( $from_date, $to_date, $patient_id = null, $provider_id = null, $facility_id = null, $pc_appstatus = null, $with_out_provider = null, $with_out_facility = null, $pc_catid = null, $tracker_board = false, $nextX = 0 )
331 $sqlBindArray = array();
333 $where = "";
335 if ( $provider_id ) {
336 $where .= " AND e.pc_aid = ?";
337 array_push($sqlBindArray, $provider_id);
340 if ( $patient_id ) {
341 $where .= " AND e.pc_pid = ?";
342 array_push($sqlBindArray, $patient_id);
343 } else {
344 $where .= " AND e.pc_pid != ''";
347 if ( $facility_id ) {
348 $where .= " AND e.pc_facility = ?";
349 array_push($sqlBindArray, $facility_id);
352 //Appointment Status Checking
353 if($pc_appstatus != ''){
354 $where .= " AND e.pc_apptstatus = ?";
355 array_push($sqlBindArray, $pc_appstatus);
358 if($pc_catid !=null) {
359 $where .= " AND e.pc_catid = ?";
360 array_push($sqlBindArray, $pc_catid);
363 //Without Provider checking
364 if($with_out_provider != ''){
365 $where .= " AND e.pc_aid = ''";
368 //Without Facility checking
369 if($with_out_facility != ''){
370 $where .= " AND e.pc_facility = 0";
373 $appointments = fetchEvents( $from_date, $to_date, $where, '', $tracker_board, $nextX, $sqlBindArray );
374 return $appointments;
377 function fetchNextXAppts($from_date, $patient_id, $nextX = 1) {
379 $appts = array();
380 $nextXAppts = array();
381 $appts = fetchAppointments( $from_date, null, $patient_id, null, null, null, null, null, null, false, $nextX );
382 if($appts) {
383 $appts = sortAppointments($appts);
384 $nextXAppts = array_slice($appts, 0, $nextX);
386 return $nextXAppts;
390 // get the event slot size in seconds
391 function getSlotSize()
393 if ( isset( $GLOBALS['calendar_interval'] ) ) {
394 return $GLOBALS['calendar_interval'] * 60;
396 return 15 * 60;
399 function getAvailableSlots( $from_date, $to_date, $provider_id = null, $facility_id = null )
401 $appointments = fetchAllEvents( $from_date, $to_date, $provider_id, $facility_id );
402 $appointments = sortAppointments( $appointments, "date" );
403 $from_datetime = strtotime( $from_date." 00:00:00" );
404 $to_datetime = strtotime( $to_date." 23:59:59" );
405 $availableSlots = array();
406 $start_time = 0;
407 $date = 0;
408 for ( $i = 0; $i < count( $appointments ); ++$i )
410 if ( $appointments[$i]['pc_catid'] == 2 ) { // 2 == In Office
411 $start_time = $appointments[$i]['pc_startTime'];
412 $date = $appointments[$i]['pc_eventDate'];
413 $provider_id = $appointments[$i]['uprovider_id'];
414 } else if ( $appointments[$i]['pc_catid'] == 3 ) { // 3 == Out Of Office
415 continue;
416 } else {
417 $start_time = $appointments[$i]['pc_endTime'];
418 $date = $appointments[$i]['pc_eventDate'];
419 $provider_id = $appointments[$i]['uprovider_id'];
422 // find next appointment with the same provider
423 $next_appointment_date = 0;
424 $next_appointment_time = 0;
425 for ( $j = $i+1; $j < count( $appointments ); ++$j ) {
426 if ( $appointments[$j]['uprovider_id'] == $provider_id ) {
427 $next_appointment_date = $appointments[$j]['pc_eventDate'];
428 $next_appointment_time = $appointments[$j]['pc_startTime'];
429 break;
433 $same_day = ( strtotime( $next_appointment_date ) == strtotime( $date ) ) ? true : false;
435 if ( $next_appointment_time && $same_day ) {
436 // check the start time of the next appointment
438 $start_datetime = strtotime( $date." ".$start_time );
439 $next_appointment_datetime = strtotime( $next_appointment_date." ".$next_appointment_time );
440 $curr_time = $start_datetime;
441 while ( $curr_time < $next_appointment_datetime - (getSlotSize() / 2) ) {
442 //create a new appointment ever 15 minutes
443 $time = date( "H:i:s", $curr_time );
444 $available_slot = createAvailableSlot(
445 $appointments[$i]['pc_eventDate'],
446 $time,
447 $appointments[$i]['ufname'],
448 $appointments[$i]['ulname'],
449 $appointments[$i]['umname'] );
450 $availableSlots []= $available_slot;
451 $curr_time += getSlotSize(); // add a 15-minute slot
456 return $availableSlots;
459 function createAvailableSlot( $event_date, $start_time, $provider_fname, $provider_lname, $provider_mname = "", $cat_name = "Available" )
461 $newSlot = array();
462 $newSlot['ulname'] = $provider_lname;
463 $newSlot['ufname'] = $provider_fname;
464 $newSlot['umname'] = $provider_mname;
465 $newSlot['pc_eventDate'] = $event_date;
466 $newSlot['pc_startTime'] = $start_time;
467 $newSlot['pc_endTime'] = $start_time;
468 $newSlot['pc_catname'] = $cat_name;
469 return $newSlot;
472 function getCompareFunction( $code ) {
473 global $COMPARE_FUNCTION_HASH;
474 return $COMPARE_FUNCTION_HASH[$code];
477 function getComparisonOrder( $code ) {
478 global $ORDERHASH;
479 return $ORDERHASH[$code];
483 function sortAppointments( array $appointments, $orderBy = 'date' )
485 global $appointment_sort_order;
486 $appointment_sort_order = $orderBy;
487 usort( $appointments, "compareAppointments" );
488 return $appointments;
491 // cmp_function for usort
492 // The comparison function must return an integer less than, equal to,
493 // or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
494 function compareAppointments( $appointment1, $appointment2 )
496 global $appointment_sort_order;
497 $comparisonOrder = getComparisonOrder( $appointment_sort_order );
498 foreach ( $comparisonOrder as $comparison )
500 $cmp_function = getCompareFunction( $comparison );
501 $result = $cmp_function( $appointment1, $appointment2 );
502 if ( 0 != $result ) {
503 return $result;
507 return 0;
510 function compareBasic( $e1, $e2 )
512 if ( $e1 < $e2 ) {
513 return -1;
514 } else if ( $e1 > $e2 ) {
515 return 1;
518 return 0;
521 function compareAppointmentsByDate( $appointment1, $appointment2 )
523 $date1 = strtotime( $appointment1['pc_eventDate'] );
524 $date2 = strtotime( $appointment2['pc_eventDate'] );
526 return compareBasic( $date1, $date2 );
529 function compareAppointmentsByTime( $appointment1, $appointment2 )
531 $time1 = strtotime( $appointment1['pc_startTime'] );
532 $time2 = strtotime( $appointment2['pc_startTime'] );
534 return compareBasic( $time1, $time2 );
537 function compareAppointmentsByDoctorName( $appointment1, $appointment2 )
539 $name1 = $appointment1['ulname'];
540 $name2 = $appointment2['ulname'];
541 $cmp = compareBasic( $name1, $name2 );
542 if ( $cmp == 0 ) {
543 $name1 = $appointment1['ufname'];
544 $name2 = $appointment2['ufname'];
545 return compareBasic( $name1, $name2 );
548 return $cmp;
551 function compareAppointmentsByPatientName( $appointment1, $appointment2 )
553 $name1 = $appointment1['lname'];
554 $name2 = $appointment2['lname'];
555 $cmp = compareBasic( $name1, $name2 );
556 if ( $cmp == 0 ) {
557 $name1 = $appointment1['fname'];
558 $name2 = $appointment2['fname'];
559 return compareBasic( $name1, $name2 );
562 return $cmp;
565 function compareAppointmentsByType( $appointment1, $appointment2 )
567 $type1 = $appointment1['pc_catid'];
568 $type2 = $appointment2['pc_catid'];
569 return compareBasic( $type1, $type2 );
572 function compareAppointmentsByPatientId( $appointment1, $appointment2 )
574 $id1 = $appointment1['pubpid'];
575 $id2 = $appointment2['pubpid'];
576 return compareBasic( $id1, $id2 );
579 function compareAppointmentsByComment( $appointment1, $appointment2 )
581 $comment1 = $appointment1['pc_hometext'];
582 $comment2 = $appointment2['pc_hometext'];
583 return compareBasic( $comment1, $comment2 );
586 function compareAppointmentsByStatus( $appointment1, $appointment2 )
588 $status1 = $appointment1['pc_apptstatus'];
589 $status2 = $appointment2['pc_apptstatus'];
590 return compareBasic( $status1, $status2 );
593 function compareAppointmentsByTrackerStatus( $appointment1, $appointment2 )
595 $trackerstatus1 = $appointment1['status'];
596 $trackerstatus2 = $appointment2['status'];
597 return compareBasic( $trackerstatus1, $trackerstatus2 );
600 function compareAppointmentsByCompletedDrugScreen( $appointment1, $appointment2 )
602 $completed1 = $appointment1['drug_screen_completed'];
603 $completed2 = $appointment2['drug_screen_completed'];
604 return compareBasic( $completed1, $completed2 );
607 function fetchAppointmentCategories()
609 $catSQL= " SELECT pc_catid as id, pc_catname as category "
610 . " FROM openemr_postcalendar_categories WHERE pc_recurrtype=0 and pc_cattype=0 ORDER BY category";
611 return sqlStatement($catSQL);
614 function interpretRecurrence($recurr_freq, $recurr_type){
615 global $REPEAT_FREQ, $REPEAT_FREQ_TYPE, $REPEAT_ON_NUM, $REPEAT_ON_DAY;
616 $interpreted = "";
617 $recurr_freq = unserialize($recurr_freq);
618 if($recurr_type == 1){
619 $interpreted = $REPEAT_FREQ[$recurr_freq['event_repeat_freq']];
620 $interpreted .= " " . $REPEAT_FREQ_TYPE[$recurr_freq['event_repeat_freq_type']];
622 elseif($recurr_type == 2){
623 $interpreted = $REPEAT_FREQ[$recurr_freq['event_repeat_on_freq']];
624 $interpreted .= " " . $REPEAT_ON_NUM[$recurr_freq['event_repeat_on_num']];
625 $interpreted .= " " . $REPEAT_ON_DAY[$recurr_freq['event_repeat_on_day']];
628 return $interpreted;
631 function fetchRecurrences($pid){
632 $query = "SELECT `pc_title`, `pc_endDate`, `pc_recurrtype`, `pc_recurrspec` FROM openemr_postcalendar_events
633 WHERE `pc_pid` = ? AND `pc_recurrtype` > 0;";
634 $sqlBindArray = array();
635 array_push($sqlBindArray, $pid);
636 $res = sqlStatement($query, $sqlBindArray);
637 $row = 0;
638 while($res_arr[$row] = sqlFetchArray($res)) {
639 $res_arr[$row]['pc_recurrspec'] = interpretRecurrence($res_arr[$row]['pc_recurrspec'], $res_arr[$row]['pc_recurrtype']);
640 $row++;
642 return $res_arr;
645 function ends_in_a_week($end_date){
646 $timestamp_in_a_week = strtotime('+7 day');
647 $timestamp_end_date = strtotime($end_date);
648 if($timestamp_in_a_week > $timestamp_end_date){
649 return true; //ends in a week
651 return false; // ends in more than a week
654 //Checks if recurrence is current (didn't end yet).
655 function recurrence_is_current($end_date){
656 $end_date_timestamp = strtotime($end_date);
657 $current_timestamp = time();
658 if($current_timestamp <= $end_date_timestamp){
659 return true; //recurrence is current
661 return false;