Adding document download to portal, take 3.
[openemr.git] / library / appointments.inc.php
blob8e1fec7bf3e29adf5ce8e337105fa30cdf897108
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 ////////////
15 require_once(dirname(__FILE__)."/encounter_events.inc.php");
16 require_once(dirname(__FILE__)."/../interface/main/calendar/modules/PostCalendar/pnincludes/Date/Calc.php");
17 ////////////
20 $COMPARE_FUNCTION_HASH = array(
21 'doctor' => 'compareAppointmentsByDoctorName',
22 'patient' => 'compareAppointmentsByPatientName',
23 'pubpid' => 'compareAppointmentsByPatientId',
24 'date' => 'compareAppointmentsByDate',
25 'time' => 'compareAppointmentsByTime',
26 'type' => 'compareAppointmentsByType',
27 'comment' => 'compareAppointmentsByComment',
28 'status' => 'compareAppointmentsByStatus',
29 'completed' => 'compareAppointmentsByCompletedDrugScreen',
30 'trackerstatus' => 'compareAppointmentsByTrackerStatus'
33 $ORDERHASH = array(
34 'doctor' => array( 'doctor', 'date', 'time' ),
35 'patient' => array( 'patient', 'date', 'time' ),
36 'pubpid' => array( 'pubpid', 'date', 'time' ),
37 'date' => array( 'date', 'time', 'type', 'patient' ),
38 'time' => array( 'time', 'date', 'patient' ),
39 'type' => array( 'type', 'date', 'time', 'patient' ),
40 'comment' => array( 'comment', 'date', 'time', 'patient' ),
41 'status' => array( 'status', 'date', 'time', 'patient' ),
42 'completed' => array( 'completed', 'date', 'time', 'patient' ),
43 'trackerstatus' => array( 'trackerstatus', 'date', 'time', 'patient' ),
46 function fetchEvents( $from_date, $to_date, $where_param = null, $orderby_param = null, $tracker_board = false, $flagPSM = false )
48 //////
49 if($flagPSM) { // Patient Summary Mode
51 $where =
52 "((e.pc_endDate >= CURRENT_DATE AND e.pc_recurrtype > '0') OR " .
53 "(e.pc_eventDate >= CURRENT_DATE))";
55 } else {
56 //////
57 $where =
58 "((e.pc_endDate >= '$from_date' AND e.pc_eventDate <= '$to_date' AND e.pc_recurrtype > '0') OR " .
59 "(e.pc_eventDate >= '$from_date' AND e.pc_eventDate <= '$to_date'))";
63 if ( $where_param ) $where .= $where_param;
65 $order_by = "e.pc_eventDate, e.pc_startTime";
66 if ( $orderby_param ) {
67 $order_by = $orderby_param;
70 // Tracker Board specific stuff
71 $tracker_fields = '';
72 $tracker_joins = '';
73 if ($tracker_board) {
74 $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, " .
75 "q.pt_tracker_id, q.start_datetime, q.room, q.status, q.seq, q.user, " .
76 "s.toggle_setting_1, s.toggle_setting_2, s.option_id, " ;
77 $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 " .
78 "LEFT OUTER JOIN patient_tracker_element AS q ON q.pt_tracker_id = t.id AND q.seq = t.lastseq " .
79 "LEFT OUTER JOIN list_options AS s ON s.list_id = 'apptstat' AND s.option_id = q.status " ;
82 $query = "SELECT " .
83 "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, " .
84 "e.pc_title, e.pc_hometext, e.pc_apptstatus, " .
85 "p.fname, p.mname, p.lname, p.pid, p.pubpid, p.phone_home, p.phone_cell, " .
86 "u.fname AS ufname, u.mname AS umname, u.lname AS ulname, u.id AS uprovider_id, " .
87 "$tracker_fields" .
88 "c.pc_catname, c.pc_catid " .
89 "FROM openemr_postcalendar_events AS e " .
90 "$tracker_joins" .
91 "LEFT OUTER JOIN patient_data AS p ON p.pid = e.pc_pid " .
92 "LEFT OUTER JOIN users AS u ON u.id = e.pc_aid " .
93 "LEFT OUTER JOIN openemr_postcalendar_categories AS c ON c.pc_catid = e.pc_catid " .
94 "WHERE $where " .
95 "ORDER BY $order_by";
98 ///////////////////////////////////////////////////////////////////////
99 // The following code is from the calculateEvents function in the
100 // PostCalendar Module modified and inserted here by epsdky
102 $events2 = array();
103 $res = sqlStatement($query);
104 ////////
105 if($flagPSM) { // Patient Summary Mode
106 global $resNotNull;
107 $resNotNull = (isset($res) && $res != null);
110 while ($event = sqlFetchArray($res)) {
111 ///////
112 if($flagPSM) $stopDate = $event['pc_endDate'];
113 else $stopDate = ($event['pc_endDate'] <= $to_date) ? $event['pc_endDate'] : $to_date;
114 ///////
115 switch($event['pc_recurrtype']) {
117 case '0' :
119 $events2[] = $event;
121 break;
122 //////
123 case '1' :
125 $event_recurrspec = @unserialize($event['pc_recurrspec']);
127 $rfreq = $event_recurrspec['event_repeat_freq'];
128 $rtype = $event_recurrspec['event_repeat_freq_type'];
129 $exdate = $event_recurrspec['exdate'];
131 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
132 // $occurance = Date_Calc::dateFormat($nd,$nm,$ny,'%Y-%m-%d');
133 $occurance = $event['pc_eventDate'];
135 while($occurance < $from_date) {
136 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
137 list($ny,$nm,$nd) = explode('-',$occurance);
140 while($occurance <= $stopDate) {
142 $excluded = false;
143 if (isset($exdate)) {
144 foreach (explode(",", $exdate) as $exception) {
145 // occurrance format == yyyy-mm-dd
146 // exception format == yyyymmdd
147 if (preg_replace("/-/", "", $occurance) == $exception) {
148 $excluded = true;
153 if ($excluded == false) {
154 $event['pc_eventDate'] = $occurance;
155 $event['pc_endDate'] = '0000-00-00';
156 $events2[] = $event;
157 //////
158 if ($flagPSM) break;
159 //////
162 $occurance =& __increment($nd,$nm,$ny,$rfreq,$rtype);
163 list($ny,$nm,$nd) = explode('-',$occurance);
167 break;
169 //////
170 case '2' :
172 $event_recurrspec = @unserialize($event['pc_recurrspec']);
174 $rfreq = $event_recurrspec['event_repeat_on_freq'];
175 $rnum = $event_recurrspec['event_repeat_on_num'];
176 $rday = $event_recurrspec['event_repeat_on_day'];
177 $exdate = $event_recurrspec['exdate'];
179 list($ny,$nm,$nd) = explode('-',$event['pc_eventDate']);
181 $occuranceYm = "$ny-$nm"; // YYYY-mm
182 $from_dateYm = substr($from_date,0,7); // YYYY-mm
183 $stopDateYm = substr($stopDate,0,7); // YYYY-mm
185 // $nd will sometimes be 29, 30 or 31, and if used in mktime below, a problem
186 // with overflow will occur ('01' should be plugged in to avoid this). We need
187 // to mirror the calendar code which has this problem, so $nd has been used.
188 while($occuranceYm < $from_dateYm) {
189 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
190 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
191 $occuranceYm = "$ny-$nm";
194 while($occuranceYm <= $stopDateYm) {
196 // (YYYY-mm)-dd
197 $dnum = $rnum;
198 do {
199 $occurance = Date_Calc::NWeekdayOfMonth($dnum--,$rday,$nm,$ny,$format="%Y-%m-%d");
200 } while($occurance === -1);
202 if($occurance >= $from_date && $occurance <= $stopDate) {
204 $excluded = false;
205 if (isset($exdate)) {
206 foreach (explode(",", $exdate) as $exception) {
207 // occurrance format == yyyy-mm-dd
208 // exception format == yyyymmdd
209 if (preg_replace("/-/", "", $occurance) == $exception) {
210 $excluded = true;
215 if ($excluded == false) {
217 $event['pc_eventDate'] = $occurance;
218 $event['pc_endDate'] = '0000-00-00';
219 $events2[] = $event;
220 //////
221 if($flagPSM) break;
222 //////
228 $occuranceYmX = date('Y-m-d',mktime(0,0,0,$nm+$rfreq,$nd,$ny));
229 list($ny,$nm,$nd) = explode('-',$occuranceYmX);
230 $occuranceYm = "$ny-$nm";
234 break;
239 return $events2;
240 ////////////////////// End of code inserted by epsdky
242 //////////////////////
244 function fetchAllEvents( $from_date, $to_date, $provider_id = null, $facility_id = null )
246 $where = "";
247 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
249 $facility_filter = '';
250 if ( $facility_id ) {
251 $event_facility_filter = " AND e.pc_facility = '" . add_escape_custom($facility_id) . "'"; //escape $facility_id
252 $provider_facility_filter = " AND u.facility_id = '" . add_escape_custom($facility_id) . "'"; //escape $facility_id
253 $facility_filter = $event_facility_filter . $provider_facility_filter;
256 $where .= $facility_filter;
257 $appointments = fetchEvents( $from_date, $to_date, $where );
258 return $appointments;
261 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, $flagPSM = false )
263 $where = "";
264 if ( $provider_id ) $where .= " AND e.pc_aid = '$provider_id'";
265 if ( $patient_id ) {
266 $where .= " AND e.pc_pid = '$patient_id'";
267 } else {
268 $where .= " AND e.pc_pid != ''";
271 $facility_filter = '';
272 if ( $facility_id ) {
273 $event_facility_filter = " AND e.pc_facility = '" . add_escape_custom($facility_id) . "'"; // escape $facility_id
274 $provider_facility_filter = " AND u.facility_id = '" . add_escape_custom($facility_id) . "'"; // escape $facility_id
275 $facility_filter = $event_facility_filter . $provider_facility_filter;
278 $where .= $facility_filter;
280 //Appointment Status Checking
281 $filter_appstatus = '';
282 if($pc_appstatus != ''){
283 $filter_appstatus = " AND e.pc_apptstatus = '".$pc_appstatus."'";
285 $where .= $filter_appstatus;
287 if($pc_catid !=null)
289 $where .= " AND e.pc_catid=".intval($pc_catid); // using intval to escape this parameter
292 //Without Provider checking
293 $filter_woprovider = '';
294 if($with_out_provider != ''){
295 $filter_woprovider = " AND e.pc_aid = ''";
297 $where .= $filter_woprovider;
299 //Without Facility checking
300 $filter_wofacility = '';
301 if($with_out_facility != ''){
302 $filter_wofacility = " AND e.pc_facility = 0";
304 $where .= $filter_wofacility;
306 $appointments = fetchEvents( $from_date, $to_date, $where, '', $tracker_board, $flagPSM );
307 return $appointments;
310 // get the event slot size in seconds
311 function getSlotSize()
313 if ( isset( $GLOBALS['calendar_interval'] ) ) {
314 return $GLOBALS['calendar_interval'] * 60;
316 return 15 * 60;
319 function getAvailableSlots( $from_date, $to_date, $provider_id = null, $facility_id = null )
321 $appointments = fetchAllEvents( $from_date, $to_date, $provider_id, $facility_id );
322 $appointments = sortAppointments( $appointments, "date" );
323 $from_datetime = strtotime( $from_date." 00:00:00" );
324 $to_datetime = strtotime( $to_date." 23:59:59" );
325 $availableSlots = array();
326 $start_time = 0;
327 $date = 0;
328 for ( $i = 0; $i < count( $appointments ); ++$i )
330 if ( $appointments[$i]['pc_catid'] == 2 ) { // 2 == In Office
331 $start_time = $appointments[$i]['pc_startTime'];
332 $date = $appointments[$i]['pc_eventDate'];
333 $provider_id = $appointments[$i]['uprovider_id'];
334 } else if ( $appointments[$i]['pc_catid'] == 3 ) { // 3 == Out Of Office
335 continue;
336 } else {
337 $start_time = $appointments[$i]['pc_endTime'];
338 $date = $appointments[$i]['pc_eventDate'];
339 $provider_id = $appointments[$i]['uprovider_id'];
342 // find next appointment with the same provider
343 $next_appointment_date = 0;
344 $next_appointment_time = 0;
345 for ( $j = $i+1; $j < count( $appointments ); ++$j ) {
346 if ( $appointments[$j]['uprovider_id'] == $provider_id ) {
347 $next_appointment_date = $appointments[$j]['pc_eventDate'];
348 $next_appointment_time = $appointments[$j]['pc_startTime'];
349 break;
353 $same_day = ( strtotime( $next_appointment_date ) == strtotime( $date ) ) ? true : false;
355 if ( $next_appointment_time && $same_day ) {
356 // check the start time of the next appointment
358 $start_datetime = strtotime( $date." ".$start_time );
359 $next_appointment_datetime = strtotime( $next_appointment_date." ".$next_appointment_time );
360 $curr_time = $start_datetime;
361 while ( $curr_time < $next_appointment_datetime - (getSlotSize() / 2) ) {
362 //create a new appointment ever 15 minutes
363 $time = date( "H:i:s", $curr_time );
364 $available_slot = createAvailableSlot(
365 $appointments[$i]['pc_eventDate'],
366 $time,
367 $appointments[$i]['ufname'],
368 $appointments[$i]['ulname'],
369 $appointments[$i]['umname'] );
370 $availableSlots []= $available_slot;
371 $curr_time += getSlotSize(); // add a 15-minute slot
376 return $availableSlots;
379 function createAvailableSlot( $event_date, $start_time, $provider_fname, $provider_lname, $provider_mname = "", $cat_name = "Available" )
381 $newSlot = array();
382 $newSlot['ulname'] = $provider_lname;
383 $newSlot['ufname'] = $provider_fname;
384 $newSlot['umname'] = $provider_mname;
385 $newSlot['pc_eventDate'] = $event_date;
386 $newSlot['pc_startTime'] = $start_time;
387 $newSlot['pc_endTime'] = $start_time;
388 $newSlot['pc_catname'] = $cat_name;
389 return $newSlot;
392 function getCompareFunction( $code ) {
393 global $COMPARE_FUNCTION_HASH;
394 return $COMPARE_FUNCTION_HASH[$code];
397 function getComparisonOrder( $code ) {
398 global $ORDERHASH;
399 return $ORDERHASH[$code];
403 function sortAppointments( array $appointments, $orderBy = 'date' )
405 global $appointment_sort_order;
406 $appointment_sort_order = $orderBy;
407 usort( $appointments, "compareAppointments" );
408 return $appointments;
411 // cmp_function for usort
412 // The comparison function must return an integer less than, equal to,
413 // or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
414 function compareAppointments( $appointment1, $appointment2 )
416 global $appointment_sort_order;
417 $comparisonOrder = getComparisonOrder( $appointment_sort_order );
418 foreach ( $comparisonOrder as $comparison )
420 $cmp_function = getCompareFunction( $comparison );
421 $result = $cmp_function( $appointment1, $appointment2 );
422 if ( 0 != $result ) {
423 return $result;
427 return 0;
430 function compareBasic( $e1, $e2 )
432 if ( $e1 < $e2 ) {
433 return -1;
434 } else if ( $e1 > $e2 ) {
435 return 1;
438 return 0;
441 function compareAppointmentsByDate( $appointment1, $appointment2 )
443 $date1 = strtotime( $appointment1['pc_eventDate'] );
444 $date2 = strtotime( $appointment2['pc_eventDate'] );
446 return compareBasic( $date1, $date2 );
449 function compareAppointmentsByTime( $appointment1, $appointment2 )
451 $time1 = strtotime( $appointment1['pc_startTime'] );
452 $time2 = strtotime( $appointment2['pc_startTime'] );
454 return compareBasic( $time1, $time2 );
457 function compareAppointmentsByDoctorName( $appointment1, $appointment2 )
459 $name1 = $appointment1['ulname'];
460 $name2 = $appointment2['ulname'];
461 $cmp = compareBasic( $name1, $name2 );
462 if ( $cmp == 0 ) {
463 $name1 = $appointment1['ufname'];
464 $name2 = $appointment2['ufname'];
465 return compareBasic( $name1, $name2 );
468 return $cmp;
471 function compareAppointmentsByPatientName( $appointment1, $appointment2 )
473 $name1 = $appointment1['lname'];
474 $name2 = $appointment2['lname'];
475 $cmp = compareBasic( $name1, $name2 );
476 if ( $cmp == 0 ) {
477 $name1 = $appointment1['fname'];
478 $name2 = $appointment2['fname'];
479 return compareBasic( $name1, $name2 );
482 return $cmp;
485 function compareAppointmentsByType( $appointment1, $appointment2 )
487 $type1 = $appointment1['pc_catid'];
488 $type2 = $appointment2['pc_catid'];
489 return compareBasic( $type1, $type2 );
492 function compareAppointmentsByPatientId( $appointment1, $appointment2 )
494 $id1 = $appointment1['pubpid'];
495 $id2 = $appointment2['pubpid'];
496 return compareBasic( $id1, $id2 );
499 function compareAppointmentsByComment( $appointment1, $appointment2 )
501 $comment1 = $appointment1['pc_hometext'];
502 $comment2 = $appointment2['pc_hometext'];
503 return compareBasic( $comment1, $comment2 );
506 function compareAppointmentsByStatus( $appointment1, $appointment2 )
508 $status1 = $appointment1['pc_apptstatus'];
509 $status2 = $appointment2['pc_apptstatus'];
510 return compareBasic( $status1, $status2 );
513 function compareAppointmentsByTrackerStatus( $appointment1, $appointment2 )
515 $trackerstatus1 = $appointment1['status'];
516 $trackerstatus2 = $appointment2['status'];
517 return compareBasic( $trackerstatus1, $trackerstatus2 );
520 function compareAppointmentsByCompletedDrugScreen( $appointment1, $appointment2 )
522 $completed1 = $appointment1['drug_screen_completed'];
523 $completed2 = $appointment2['drug_screen_completed'];
524 return compareBasic( $completed1, $completed2 );
527 function fetchAppointmentCategories()
529 $catSQL= " SELECT pc_catid as id, pc_catname as category "
530 . " FROM openemr_postcalendar_categories WHERE pc_recurrtype=0 and pc_cattype=0 ORDER BY category";
531 return sqlStatement($catSQL);