Filter appointment report by category
[openemr.git] / library / appointments.inc.php
blob0bb2cd6cddf53409783656bef35e2c47e12f4dd5
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
12 $COMPARE_FUNCTION_HASH = array(
13 'doctor' => 'compareAppointmentsByDoctorName',
14 'patient' => 'compareAppointmentsByPatientName',
15 'pubpid' => 'compareAppointmentsByPatientId',
16 'date' => 'compareAppointmentsByDate',
17 'time' => 'compareAppointmentsByTime',
18 'type' => 'compareAppointmentsByType',
19 'comment' => 'compareAppointmentsByComment',
20 'status' => 'compareAppointmentsByStatus'
23 $ORDERHASH = array(
24 'doctor' => array( 'doctor', 'date', 'time' ),
25 'patient' => array( 'patient', 'date', 'time' ),
26 'pubpid' => array( 'pubpid', 'date', 'time' ),
27 'date' => array( 'date', 'time', 'type', 'patient' ),
28 'time' => array( 'time', 'date', 'patient' ),
29 'type' => array( 'type', 'date', 'time', 'patient' ),
30 'comment' => array( 'comment', 'date', 'time', 'patient' ),
31 'status' => array( 'status', 'date', 'time', 'patient' )
34 function fetchEvents( $from_date, $to_date, $where_param = null, $orderby_param = null )
36 $where =
37 "( (e.pc_endDate >= '$from_date' AND e.pc_eventDate <= '$to_date' AND e.pc_recurrtype = '1') OR " .
38 "(e.pc_eventDate >= '$from_date' AND e.pc_eventDate <= '$to_date') )";
39 if ( $where_param ) $where .= $where_param;
41 $order_by = "e.pc_eventDate, e.pc_startTime";
42 if ( $orderby_param ) {
43 $order_by = $orderby_param;
46 $query = "SELECT " .
47 "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, " .
48 "e.pc_title, e.pc_hometext, e.pc_apptstatus, " .
49 "p.fname, p.mname, p.lname, p.pid, p.pubpid, p.phone_home, p.phone_cell, " .
50 "u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, " .
51 "c.pc_catname, c.pc_catid " .
52 "FROM openemr_postcalendar_events AS e " .
53 "LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid " .
54 "LEFT OUTER JOIN users AS u ON u.id = e.pc_aid " .
55 "LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid " .
56 "WHERE $where " .
57 "ORDER BY $order_by";
59 $res = sqlStatement( $query );
60 $events = array();
61 if ( $res )
63 while ( $row = sqlFetchArray($res) )
65 // if it's a repeating appointment, fetch all occurances in date range
66 if ( $row['pc_recurrtype'] ) {
67 $reccuringEvents = getRecurringEvents( $row, $from_date, $to_date );
68 $events = array_merge( $events, $reccuringEvents );
69 } else {
70 $events []= $row;
75 return $events;
78 function fetchAllEvents( $from_date, $to_date, $provider_id = null, $facility_id = null )
80 $where = "";
81 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
83 $facility_filter = '';
84 if ( $facility_id ) {
85 $event_facility_filter = " AND e.pc_facility = '$facility_id'";
86 $provider_facility_filter = " AND u.facility_id = '$facility_id'";
87 $facility_filter = $event_facility_filter . $provider_facility_filter;
90 $where .= $facility_filter;
91 $appointments = fetchEvents( $from_date, $to_date, $where );
92 return $appointments;
95 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 )
97 $where = "";
98 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
99 if ( $patient_id ) {
100 $where .= " AND e.pc_pid = '$patient_id'";
101 } else {
102 $where .= " AND e.pc_pid != ''";
105 $facility_filter = '';
106 if ( $facility_id ) {
107 $event_facility_filter = " AND e.pc_facility = '$facility_id'";
108 $provider_facility_filter = " AND u.facility_id = '$facility_id'";
109 $facility_filter = $event_facility_filter . $provider_facility_filter;
112 $where .= $facility_filter;
114 //Appointment Status Checking
115 $filter_appstatus = '';
116 if($pc_appstatus != ''){
117 $filter_appstatus = " AND e.pc_apptstatus = '".$pc_appstatus."'";
119 $where .= $filter_appstatus;
121 if($pc_catid !=null)
123 $where .= " AND e.pc_catid=".intval($pc_catid); // using intval to escape this parameter
126 //Without Provider checking
127 $filter_woprovider = '';
128 if($with_out_provider != ''){
129 $filter_woprovider = " AND e.pc_aid = ''";
131 $where .= $filter_woprovider;
133 //Without Facility checking
134 $filter_wofacility = '';
135 if($with_out_facility != ''){
136 $filter_wofacility = " AND e.pc_facility = 0";
138 $where .= $filter_wofacility;
140 $appointments = fetchEvents( $from_date, $to_date, $where );
141 return $appointments;
144 function getRecurringEvents( $event, $from_date, $to_date )
146 $repeatEvents = array();
147 $from_date_time = strtotime( $from_date . " 00:00:00" );
148 $thistime = strtotime( $event['pc_eventDate'] . " 00:00:00" );
149 //$thistime = max( $thistime, $from_date_time );
150 if ( $event['pc_recurrtype'] )
152 preg_match( '/"event_repeat_freq_type";s:1:"(\d)"/', $event['pc_recurrspec'], $matches );
153 $repeattype = $matches[1];
155 preg_match( '/"event_repeat_freq";s:1:"(\d)"/', $event['pc_recurrspec'], $matches );
156 $repeatfreq = $matches[1];
157 if ($event['pc_recurrtype'] == 2) {
158 // Repeat type is 2 so frequency comes from event_repeat_on_freq.
159 preg_match('/"event_repeat_on_freq";s:1:"(\d)"/', $event['pc_recurrspec'], $matches);
160 $repeatfreq = $matches[1];
162 if ( !$repeatfreq ) $repeatfreq = 1;
164 preg_match('/"event_repeat_on_num";s:1:"(\d)"/', $event['pc_recurrspec'], $matches);
165 $my_repeat_on_num = $matches[1];
167 preg_match('/"event_repeat_on_day";s:1:"(\d)"/', $event['pc_recurrspec'], $matches);
168 $my_repeat_on_day = $matches[1];
170 $upToDate = strtotime( $to_date." 23:59:59" ); // set the up-to-date to the last second of the "to_date"
171 $endtime = strtotime( $event['pc_endDate'] . " 23:59:59" );
172 if ( $endtime > $upToDate ) $endtime = $upToDate;
174 $repeatix = 0;
175 while ( $thistime < $endtime )
177 // Skip the event if a repeat frequency > 1 was specified and this is
178 // not the desired occurrence.
179 if ( !$repeatix ) {
180 $inRange = ( $thistime >= $from_date_time && $thistime < $upToDate );
181 if ( $inRange ) {
182 $newEvent = $event;
183 $eventDate = date( "Y-m-d", $thistime );
184 $newEvent['pc_eventDate'] = $eventDate;
185 $newEvent['pc_endDate'] = $eventDate;
186 $repeatEvents []= $newEvent;
190 if ( ++$repeatix >= $repeatfreq ) $repeatix = 0;
192 $adate = getdate($thistime);
194 if ($event['pc_recurrtype'] == 2) {
195 // Need to skip to nth or last weekday of the next month.
196 $adate['mon'] += 1;
197 if ($adate['mon'] > 12) {
198 $adate['year'] += 1;
199 $adate['mon'] -= 12;
201 if ($my_repeat_on_num < 5) { // not last
202 $adate['mday'] = 1;
203 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
204 if ($dow > $my_repeat_on_day) $dow -= 7;
205 $adate['mday'] += ($my_repeat_on_num - 1) * 7 + $my_repeat_on_day - $dow;
207 else { // last weekday of month
208 $adate['mday'] = cal_days_in_month(CAL_GREGORIAN, $adate['mon'], $adate['year']);
209 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
210 if ($dow < $my_repeat_on_day) $dow += 7;
211 $adate['mday'] += $my_repeat_on_day - $dow;
213 } // end recurrtype 2
215 else { // recurrtype 1
216 if ($repeattype == 0) { // daily
217 $adate['mday'] += 1;
218 } else if ($repeattype == 1) { // weekly
219 $adate['mday'] += 7;
220 } else if ($repeattype == 2) { // monthly
221 $adate['mon'] += 1;
222 } else if ($repeattype == 3) { // yearly
223 $adate['year'] += 1;
224 } else if ($repeattype == 4) { // work days
225 if ($adate['wday'] == 5) // if friday, skip to monday
226 $adate['mday'] += 3;
227 else if ($adate['wday'] == 6) // saturday should not happen
228 $adate['mday'] += 2;
229 else
230 $adate['mday'] += 1;
231 } else {
232 die("Invalid repeat type '$repeattype'");
234 } // end recurrtype 1
236 $thistime = mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']);
240 return $repeatEvents;
243 // get the event slot size in seconds
244 function getSlotSize()
246 if ( isset( $GLOBALS['calendar_interval'] ) ) {
247 return $GLOBALS['calendar_interval'] * 60;
249 return 15 * 60;
252 function getAvailableSlots( $from_date, $to_date, $provider_id = null, $facility_id = null )
254 $appointments = fetchAllEvents( $from_date, $to_date, $provider_id, $facility_id );
255 $appointments = sortAppointments( $appointments, "date" );
256 $from_datetime = strtotime( $from_date." 00:00:00" );
257 $to_datetime = strtotime( $to_date." 23:59:59" );
258 $availableSlots = array();
259 $start_time = 0;
260 $date = 0;
261 for ( $i = 0; $i < count( $appointments ); ++$i )
263 if ( $appointments[$i]['pc_catid'] == 2 ) { // 2 == In Office
264 $start_time = $appointments[$i]['pc_startTime'];
265 $date = $appointments[$i]['pc_eventDate'];
266 $provider_id = $appointments[$i]['uprovider_id'];
267 } else if ( $appointments[$i]['pc_catid'] == 3 ) { // 3 == Out Of Office
268 continue;
269 } else {
270 $start_time = $appointments[$i]['pc_endTime'];
271 $date = $appointments[$i]['pc_eventDate'];
272 $provider_id = $appointments[$i]['uprovider_id'];
275 // find next appointment with the same provider
276 $next_appointment_date = 0;
277 $next_appointment_time = 0;
278 for ( $j = $i+1; $j < count( $appointments ); ++$j ) {
279 if ( $appointments[$j]['uprovider_id'] == $provider_id ) {
280 $next_appointment_date = $appointments[$j]['pc_eventDate'];
281 $next_appointment_time = $appointments[$j]['pc_startTime'];
282 break;
286 $same_day = ( strtotime( $next_appointment_date ) == strtotime( $date ) ) ? true : false;
288 if ( $next_appointment_time && $same_day ) {
289 // check the start time of the next appointment
291 $start_datetime = strtotime( $date." ".$start_time );
292 $next_appointment_datetime = strtotime( $next_appointment_date." ".$next_appointment_time );
293 $curr_time = $start_datetime;
294 while ( $curr_time < $next_appointment_datetime - (getSlotSize() / 2) ) {
295 //create a new appointment ever 15 minutes
296 $time = date( "H:i:s", $curr_time );
297 $available_slot = createAvailableSlot(
298 $appointments[$i]['pc_eventDate'],
299 $time,
300 $appointments[$i]['ufname'],
301 $appointments[$i]['ulname'],
302 $appointments[$i]['umname'] );
303 $availableSlots []= $available_slot;
304 $curr_time += getSlotSize(); // add a 15-minute slot
309 return $availableSlots;
312 function createAvailableSlot( $event_date, $start_time, $provider_fname, $provider_lname, $provider_mname = "", $cat_name = "Available" )
314 $newSlot = array();
315 $newSlot['ulname'] = $provider_lname;
316 $newSlot['ufname'] = $provider_fname;
317 $newSlot['umname'] = $provider_mname;
318 $newSlot['pc_eventDate'] = $event_date;
319 $newSlot['pc_startTime'] = $start_time;
320 $newSlot['pc_endTime'] = $start_time;
321 $newSlot['pc_catname'] = $cat_name;
322 return $newSlot;
325 function getCompareFunction( $code ) {
326 global $COMPARE_FUNCTION_HASH;
327 return $COMPARE_FUNCTION_HASH[$code];
330 function getComparisonOrder( $code ) {
331 global $ORDERHASH;
332 return $ORDERHASH[$code];
335 function sortAppointments( array $appointments, $orderBy = 'date' )
337 global $appointment_sort_order;
338 $appointment_sort_order = $orderBy;
339 usort( $appointments, "compareAppointments" );
340 return $appointments;
343 // cmp_function for usort
344 // The comparison function must return an integer less than, equal to,
345 // or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
346 function compareAppointments( $appointment1, $appointment2 )
348 global $appointment_sort_order;
349 $comparisonOrder = getComparisonOrder( $appointment_sort_order );
350 foreach ( $comparisonOrder as $comparison )
352 $cmp_function = getCompareFunction( $comparison );
353 $result = $cmp_function( $appointment1, $appointment2 );
354 if ( 0 != $result ) {
355 return $result;
359 return 0;
362 function compareBasic( $e1, $e2 )
364 if ( $e1 < $e2 ) {
365 return -1;
366 } else if ( $e1 > $e2 ) {
367 return 1;
370 return 0;
373 function compareAppointmentsByDate( $appointment1, $appointment2 )
375 $date1 = strtotime( $appointment1['pc_eventDate'] );
376 $date2 = strtotime( $appointment2['pc_eventDate'] );
378 return compareBasic( $date1, $date2 );
381 function compareAppointmentsByTime( $appointment1, $appointment2 )
383 $time1 = strtotime( $appointment1['pc_startTime'] );
384 $time2 = strtotime( $appointment2['pc_startTime'] );
386 return compareBasic( $time1, $time2 );
389 function compareAppointmentsByDoctorName( $appointment1, $appointment2 )
391 $name1 = $appointment1['ulname'];
392 $name2 = $appointment2['ulname'];
393 $cmp = compareBasic( $name1, $name2 );
394 if ( $cmp == 0 ) {
395 $name1 = $appointment1['ufname'];
396 $name2 = $appointment2['ufname'];
397 return compareBasic( $name1, $name2 );
400 return $cmp;
403 function compareAppointmentsByPatientName( $appointment1, $appointment2 )
405 $name1 = $appointment1['lname'];
406 $name2 = $appointment2['lname'];
407 $cmp = compareBasic( $name1, $name2 );
408 if ( $cmp == 0 ) {
409 $name1 = $appointment1['fname'];
410 $name2 = $appointment2['fname'];
411 return compareBasic( $name1, $name2 );
414 return $cmp;
417 function compareAppointmentsByType( $appointment1, $appointment2 )
419 $type1 = $appointment1['pc_catid'];
420 $type2 = $appointment2['pc_catid'];
421 return compareBasic( $type1, $type2 );
424 function compareAppointmentsByPatientId( $appointment1, $appointment2 )
426 $id1 = $appointment1['pubpid'];
427 $id2 = $appointment2['pubpid'];
428 return compareBasic( $id1, $id2 );
431 function compareAppointmentsByComment( $appointment1, $appointment2 )
433 $comment1 = $appointment1['pc_hometext'];
434 $comment2 = $appointment2['pc_hometext'];
435 return compareBasic( $comment1, $comment2 );
438 function compareAppointmentsByStatus( $appointment1, $appointment2 )
440 $status1 = $appointment1['pc_apptstatus'];
441 $status2 = $appointment2['pc_apptstatus'];
442 return compareBasic( $status1, $status2 );
445 function fetchAppointmentCategories()
447 $catSQL= " SELECT pc_catid as id, pc_catname as category "
448 . " FROM openemr_postcalendar_categories WHERE pc_recurrtype=0 and pc_cattype=0 ORDER BY category";
449 return sqlStatement($catSQL);