changes to prior commit
[openemr.git] / library / encounter_events.inc.php
blob9024c6da904ecd5dcb53e0f74bd7c8a66dd56e13
1 <?php
2 // +-----------------------------------------------------------------------------+
3 // Copyright (C) 2010 Z&H Consultancy Services Private Limited <sam@zhservices.com>
4 //
5 //
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
12 // This program is distributed in the hope that it will be useful,
13 // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 // GNU General Public License for more details.
18 // A copy of the GNU General Public License is included along with this program:
19 // openemr/interface/login/GnuGPL.html
20 // For more information write to the Free Software
21 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 //
23 // Author: Eldho Chacko <eldho@zhservices.com>
24 // Paul Simon K <paul@zhservices.com>
26 // +------------------------------------------------------------------------------+
28 require_once(dirname(__FILE__) . '/calendar.inc');
29 require_once(dirname(__FILE__) . '/patient_tracker.inc.php');
32 //===============================================================================
33 //This section handles the events of payment screen.
34 //===============================================================================
35 define('REPEAT_EVERY_DAY', 0);
36 define('REPEAT_EVERY_WEEK', 1);
37 define('REPEAT_EVERY_MONTH', 2);
38 define('REPEAT_EVERY_YEAR', 3);
39 define('REPEAT_EVERY_WORK_DAY',4);
40 define('REPEAT_DAYS_EVERY_WEEK', 6);
41 //===============================================================================
42 //Create event in calender as arrived
43 function calendar_arrived($form_pid) {
44 $Today=date('Y-m-d');
45 //Take all recurring events relevent for today.
46 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_recurrtype != '0' and pc_pid = ? and pc_endDate != '0000-00-00'
47 and pc_eventDate < ? and pc_endDate >= ? ",
48 array($form_pid,$Today,$Today));
49 if(sqlNumRows($result_event)==0)//no repeating appointment
51 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_pid =? and pc_eventDate = ?",
52 array($form_pid,$Today));
53 if(sqlNumRows($result_event)==0)//no appointment
55 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
56 die;
58 else//one appointment
60 $enc = todaysEncounterCheck($form_pid);//create encounter
61 $zero_enc=0;
62 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus ='@' WHERE pc_pid =? and pc_eventDate = ?",
63 array($form_pid,$Today));
66 else//repeating appointment set
68 while($row_event=sqlFetchArray($result_event))
70 $pc_eid = $row_event['pc_eid'];
71 $pc_eventDate = $row_event['pc_eventDate'];
72 $pc_recurrspec_array = unserialize($row_event['pc_recurrspec']);
73 while(1)
75 if($pc_eventDate==$Today)//Matches so insert.
77 if(!$exist_eid=check_event_exist($pc_eid))
79 update_event($pc_eid);
81 else
83 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?",
84 array($exist_eid));
86 $enc = todaysEncounterCheck($form_pid);//create encounter
87 $zero_enc=0;
88 break;
90 elseif($pc_eventDate>$Today)//the frequency does not match today,no need to increment furthur.
92 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
93 die;
94 break;
97 // Added by Rod to handle repeats on nth or last given weekday of a month:
98 if ($row_event['pc_recurrtype'] == 2) {
99 $my_repeat_on_day = $pc_recurrspec_array['event_repeat_on_day'];
100 $my_repeat_on_num = $pc_recurrspec_array['event_repeat_on_num'];
101 $adate = getdate(strtotime($pc_eventDate));
102 $adate['mon'] += 1;
103 if ($adate['mon'] > 12) {
104 $adate['year'] += 1;
105 $adate['mon'] -= 12;
107 if ($my_repeat_on_num < 5) { // not last
108 $adate['mday'] = 1;
109 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
110 if ($dow > $my_repeat_on_day) $dow -= 7;
111 $adate['mday'] += ($my_repeat_on_num - 1) * 7 + $my_repeat_on_day - $dow;
113 else { // last weekday of month
114 $adate['mday'] = cal_days_in_month(CAL_GREGORIAN, $adate['mon'], $adate['year']);
115 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
116 if ($dow < $my_repeat_on_day) $dow += 7;
117 $adate['mday'] += $my_repeat_on_day - $dow;
119 $pc_eventDate = date('Y-m-d', mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']));
120 } // end recurrtype 2
122 else { // pc_recurrtype is 1
123 $pc_eventDate_array = explode('-', $pc_eventDate);
124 // Find the next day as per the frequency definition.
125 $pc_eventDate =& __increment($pc_eventDate_array[2], $pc_eventDate_array[1], $pc_eventDate_array[0],
126 $pc_recurrspec_array['event_repeat_freq'], $pc_recurrspec_array['event_repeat_freq_type']);
132 return $enc;
134 //===============================================================================
135 // Checks for the patient's encounter ID for today, creating it if there is none.
137 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true){
138 global $today;
139 $encounter = todaysEncounterIf($patient_id);
140 if($encounter){
141 if($return_existing){
142 return $encounter;
143 }else{
144 return 0;
147 if(is_array($provider)){
148 $visit_provider = (int)$provider[0];
149 } elseif($provider){
150 $visit_provider = (int)$provider;
151 } else {
152 $visit_provider = '(NULL)';
154 $dos = $enc_date ? $enc_date : $today;
155 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
156 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
157 $username = $tmprow['username'];
158 $facility = $tmprow['facility'];
159 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
160 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
161 $visit_cat = $cat ? $cat : '(NULL)';
162 $conn = $GLOBALS['adodb']['db'];
163 $encounter = $conn->GenID("sequences");
164 addForm($encounter, "New Patient Encounter",
165 sqlInsert("INSERT INTO form_encounter SET " .
166 "date = ?, " .
167 "reason = ?, " .
168 "facility = ?, " .
169 "facility_id = ?, " .
170 "billing_facility = ?, " .
171 "provider_id = ?, " .
172 "pid = ?, " .
173 "encounter = ?," .
174 "pc_catid = ?",
175 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
177 "newpatient", $patient_id, "1", "NOW()", $username
179 return $encounter;
182 //===============================================================================
183 // Checks for the group's encounter ID for today, creating it if there is none.
185 function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null){
186 global $today;
187 $encounter = todaysTherapyGroupEncounterIf($group_id);
188 if($encounter){
189 if($return_existing){
190 return $encounter;
191 }else{
192 return 0;
195 if(is_array($provider)){
196 $visit_provider = (int)$provider[0];
197 $counselors = implode(',', $provider);
198 } elseif($provider){
199 $visit_provider = $counselors = (int)$provider;
200 } else {
201 $visit_provider = $counselors = NULL;
203 $dos = $enc_date ? $enc_date : $today;
204 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
205 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
206 $username = $tmprow['username'];
207 $facility = $tmprow['facility'];
208 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
209 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
210 $visit_cat = $cat ? $cat : '(NULL)';
211 $conn = $GLOBALS['adodb']['db'];
212 $encounter = $conn->GenID("sequences");
213 addForm($encounter, "New Therapy Group Encounter",
214 sqlInsert("INSERT INTO form_groups_encounter SET " .
215 "date = ?, " .
216 "reason = ?, " .
217 "facility = ?, " .
218 "facility_id = ?, " .
219 "billing_facility = ?, " .
220 "provider_id = ?, " .
221 "group_id = ?, " .
222 "encounter = ?," .
223 "pc_catid = ? ," .
224 "appt_id = ? ," .
225 "counselors = ? ",
226 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)
228 "newGroupEncounter", NULL, "1", "NOW()", $username, "", $group_id
230 return $encounter;
232 //===============================================================================
233 // Get the patient's encounter ID for today, if it exists.
234 // In the case of more than one encounter today, pick the last one.
236 function todaysEncounterIf($patient_id) {
237 global $today;
238 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
239 "pid = ? AND date = ? " .
240 "ORDER BY encounter DESC LIMIT 1",array($patient_id,"$today 00:00:00"));
241 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
243 //===============================================================================
244 // Get the group's encounter ID for today, if it exists.
245 // In the case of more than one encounter today, pick the last one.
247 function todaysTherapyGroupEncounterIf($group_id) {
248 global $today;
249 $tmprow = sqlQuery("SELECT encounter FROM form_groups_encounter WHERE " .
250 "group_id = ? AND date = ? " .
251 "ORDER BY encounter DESC LIMIT 1",array($group_id,"$today 00:00:00"));
252 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
254 //===============================================================================
256 // Get the patient's encounter ID for today, creating it if there is none.
258 function todaysEncounter($patient_id, $reason='') {
259 global $today, $userauthorized;
261 if (empty($reason)) $reason = xl('Please indicate visit reason');
263 // Was going to use the existing encounter for today if there is one, but
264 // decided it's right to always create a new one. Leaving the code here
265 // (and corresponding function above) in case it is ever wanted later.
266 /*******************************************************************
267 $encounter = todaysEncounterIf($patient_id);
268 if ($encounter) return $encounter;
269 *******************************************************************/
271 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
272 "WHERE id = ?", array($_SESSION["authUserID"]));
273 $username = $tmprow['username'];
274 $facility = $tmprow['facility'];
275 $facility_id = $tmprow['facility_id'];
276 $conn = $GLOBALS['adodb']['db'];
277 $encounter = $conn->GenID("sequences");
278 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
279 addForm($encounter, "New Patient Encounter",
280 sqlInsert("INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
281 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
282 "provider_id = ?",
283 array($today, $today, $reason, $facility, $facility_id, $patient_id,
284 $encounter, $provider_id)
286 "newpatient", $patient_id, $userauthorized, "NOW()", $username
288 return $encounter;
290 //===============================================================================
291 // get the original event's repeat specs
292 function update_event($eid)
294 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
295 $origEvent=sqlFetchArray($origEventRes);
296 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
297 $duration=$origEvent['pc_duration'];
298 $starttime=$origEvent['pc_startTime'];
299 $endtime=$origEvent['pc_endTime'];
300 $selected_date = date("Ymd");
301 if ($oldRecurrspec['exdate'] != "") { $oldRecurrspec['exdate'] .= ",".$selected_date; }
302 else { $oldRecurrspec['exdate'] .= $selected_date; }
303 // mod original event recur specs to exclude this date
304 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?",array(serialize($oldRecurrspec),$eid));
305 // specify some special variables needed for the INSERT
306 // no recurr specs, this is used for adding a new non-recurring event
307 $noRecurrspec = array("event_repeat_freq" => "",
308 "event_repeat_freq_type" => "",
309 "event_repeat_on_num" => "1",
310 "event_repeat_on_day" => "0",
311 "event_repeat_on_freq" => "0",
312 "exdate" => ""
314 // Useless garbage that we must save.
315 $locationspecs = array("event_location" => "",
316 "event_street1" => "",
317 "event_street2" => "",
318 "event_city" => "",
319 "event_state" => "",
320 "event_postal" => ""
322 $locationspec = serialize($locationspecs);
323 $args['event_date'] = date('Y-m-d');
324 $args['duration'] = $duration;
325 // this event is forced to NOT REPEAT
326 $args['form_repeat'] = "0";
327 $args['recurrspec'] = $noRecurrspec;
328 $args['form_enddate'] = "0000-00-00";
329 $args['starttime'] = $starttime;
330 $args['endtime'] = $endtime;
331 $args['locationspec'] = $locationspec;
332 $args['form_category']=$origEvent['pc_catid'];
333 $args['new_multiple_value']=$origEvent['pc_multiple'];
334 $args['form_provider']=$origEvent['pc_aid'];
335 $args['form_pid']=$origEvent['pc_pid'];
336 $args['form_title']=$origEvent['pc_title'];
337 $args['form_allday']=$origEvent['pc_alldayevent'];
338 $args['form_apptstatus']='@';
339 $args['form_prefcat']=$origEvent['pc_prefcatid'];
340 $args['facility']=$origEvent['pc_facility'];
341 $args['billing_facility']=$origEvent['pc_billing_location'];
342 InsertEvent($args,'payment');
344 //===============================================================================
345 // check if event exists
346 function check_event_exist($eid)
348 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
349 $origEvent=sqlFetchArray($origEventRes);
350 $pc_catid=$origEvent['pc_catid'];
351 $pc_aid=$origEvent['pc_aid'];
352 $pc_pid=$origEvent['pc_pid'];
353 $pc_eventDate=date('Y-m-d');
354 $pc_startTime=$origEvent['pc_startTime'];
355 $pc_endTime=$origEvent['pc_endTime'];
356 $pc_facility=$origEvent['pc_facility'];
357 $pc_billing_location=$origEvent['pc_billing_location'];
358 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
359 $origEvent = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
360 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
361 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location));
362 if(sqlNumRows($origEvent)>0)
364 $origEventRow=sqlFetchArray($origEvent);
365 return $origEventRow['pc_eid'];
367 else
369 if(strpos($pc_recurrspec_array['exdate'],date('Ymd')) === false)//;'20110228'
371 return false;
373 else
374 {//this happens in delete case
375 return true;
379 //===============================================================================
380 // insert an event
381 // $args is mainly filled with content from the POST http var
382 function InsertEvent($args,$from = 'general') {
383 $pc_recurrtype = '0';
384 if ($args['form_repeat'] || $args['days_every_week']) {
385 if($args['recurrspec']['event_repeat_freq_type'] == "6"){
386 $pc_recurrtype = 3;
388 else {
389 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
392 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
393 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
394 $form_gid = empty($args['form_gid']) ? '' : $args['form_gid'];;
395 if($from == 'general'){
396 $pc_eid = sqlInsert("INSERT INTO openemr_postcalendar_events ( " .
397 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_gid, pc_title, pc_time, pc_hometext, " .
398 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
399 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
400 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
401 ") VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
402 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,$form_gid,
403 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
404 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
405 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
406 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
409 //Manage tracker status.
410 if (!empty($form_pid)) {
411 manage_tracker_status($args['event_date'],$args['starttime'],$pc_eid,$form_pid,$_SESSION['authUser'],$args['form_apptstatus'],$args['form_room']);
413 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
415 return $pc_eid;
417 }elseif($from == 'payment'){
418 sqlStatement("INSERT INTO openemr_postcalendar_events ( " .
419 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
420 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
421 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
422 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
423 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
424 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
425 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
426 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
427 1,1,(int)$args['facility'],(int)$args['billing_facility']));
430 //================================================================================================================
432 * __increment()
433 * returns the next valid date for an event based on the
434 * current day,month,year,freq and type
435 * @private
436 * @returns string YYYY-MM-DD
438 function &__increment($d,$m,$y,$f,$t)
441 if($t == REPEAT_EVERY_DAY) {
442 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
443 } elseif($t == REPEAT_EVERY_WORK_DAY) {
444 // a workday is defined as Mon,Tue,Wed,Thu,Fri
445 // repeating on every or Nth work day means to not include
446 // weekends (Sat/Sun) in the increment... tricky
448 // ugh, a day-by-day loop seems necessary here, something where
449 // we can check to see if the day is a Sat/Sun and increment
450 // the frequency count so as to ignore the weekend. hmmmm....
451 $orig_freq = $f;
452 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
453 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$daycount),$y));
454 if (is_weekend_day($nextWorkDOW)) { $f++; }
457 // and finally make sure we haven't landed on a end week days
458 // adjust as necessary
459 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$f),$y));
460 if (count($GLOBALS['weekend_days']) === 2){
461 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
462 $f+=2;
463 }elseif($nextWorkDOW == $GLOBALS['weekend_days'][1]){
464 $f++;
466 } elseif(count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
467 $f++;
470 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
472 } elseif($t == REPEAT_EVERY_WEEK) {
473 return date('Y-m-d',mktime(0,0,0,$m,($d+(7*$f)),$y));
474 } elseif($t == REPEAT_EVERY_MONTH) {
475 return date('Y-m-d',mktime(0,0,0,($m+$f),$d,$y));
476 } elseif($t == REPEAT_EVERY_YEAR) {
477 return date('Y-m-d',mktime(0,0,0,$m,$d,($y+$f)));
478 }elseif($t == REPEAT_DAYS_EVERY_WEEK) {
479 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
480 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
481 return $next_appointment_date;
485 function getTheNextAppointment($appointment_date, $freq){
486 $day_arr = explode(",", $freq);
487 $date_arr = array();
488 foreach ($day_arr as $day){
489 $day = getDayName($day);
490 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
491 array_push($date_arr, $date);
493 $next_appointment = getEarliestDate($date_arr);
494 return $next_appointment;
499 function getDayName($day_num){
500 if($day_num == "1"){return "sunday";}
501 if($day_num == "2"){return "monday";}
502 if($day_num == "3"){return "tuesday";}
503 if($day_num == "4"){return "wednesday";}
504 if($day_num == "5"){return "thursday";}
505 if($day_num == "6"){return "friday";}
506 if($day_num == "7"){return "saturday";}
510 function getEarliestDate($date_arr){
511 $earliest = ($date_arr[0]);
512 foreach ($date_arr as $date){
513 if(strtotime($date) < strtotime($earliest)){
514 $earliest = $date;
517 return $earliest;
519 //================================================================================================================