minor fix in hover for prior commit
[openemr.git] / library / encounter_events.inc.php
blob8046e527bc3abb289036040d47137330153361a3
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 $dos = $enc_date ? $enc_date : $today;
148 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
149 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
150 $username = $tmprow['username'];
151 $facility = $tmprow['facility'];
152 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
153 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
154 $visit_provider = $provider ? (int)$provider : '(NULL)';
155 $visit_cat = $cat ? $cat : '(NULL)';
156 $conn = $GLOBALS['adodb']['db'];
157 $encounter = $conn->GenID("sequences");
158 addForm($encounter, "New Patient Encounter",
159 sqlInsert("INSERT INTO form_encounter SET " .
160 "date = ?, " .
161 "reason = ?, " .
162 "facility = ?, " .
163 "facility_id = ?, " .
164 "billing_facility = ?, " .
165 "provider_id = ?, " .
166 "pid = ?, " .
167 "encounter = ?," .
168 "pc_catid = ?",
169 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
171 "newpatient", $patient_id, "1", "NOW()", $username
173 return $encounter;
175 //===============================================================================
176 // Get the patient's encounter ID for today, if it exists.
177 // In the case of more than one encounter today, pick the last one.
179 function todaysEncounterIf($patient_id) {
180 global $today;
181 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
182 "pid = ? AND date = ? " .
183 "ORDER BY encounter DESC LIMIT 1",array($patient_id,"$today 00:00:00"));
184 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
186 //===============================================================================
188 // Get the patient's encounter ID for today, creating it if there is none.
190 function todaysEncounter($patient_id, $reason='') {
191 global $today, $userauthorized;
193 if (empty($reason)) $reason = xl('Please indicate visit reason');
195 // Was going to use the existing encounter for today if there is one, but
196 // decided it's right to always create a new one. Leaving the code here
197 // (and corresponding function above) in case it is ever wanted later.
198 /*******************************************************************
199 $encounter = todaysEncounterIf($patient_id);
200 if ($encounter) return $encounter;
201 *******************************************************************/
203 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
204 "WHERE id = ?", array($_SESSION["authUserID"]));
205 $username = $tmprow['username'];
206 $facility = $tmprow['facility'];
207 $facility_id = $tmprow['facility_id'];
208 $conn = $GLOBALS['adodb']['db'];
209 $encounter = $conn->GenID("sequences");
210 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
211 addForm($encounter, "New Patient Encounter",
212 sqlInsert("INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
213 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
214 "provider_id = ?",
215 array($today, $today, $reason, $facility, $facility_id, $patient_id,
216 $encounter, $provider_id)
218 "newpatient", $patient_id, $userauthorized, "NOW()", $username
220 return $encounter;
222 //===============================================================================
223 // get the original event's repeat specs
224 function update_event($eid)
226 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
227 $origEvent=sqlFetchArray($origEventRes);
228 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
229 $duration=$origEvent['pc_duration'];
230 $starttime=$origEvent['pc_startTime'];
231 $endtime=$origEvent['pc_endTime'];
232 $selected_date = date("Ymd");
233 if ($oldRecurrspec['exdate'] != "") { $oldRecurrspec['exdate'] .= ",".$selected_date; }
234 else { $oldRecurrspec['exdate'] .= $selected_date; }
235 // mod original event recur specs to exclude this date
236 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?",array(serialize($oldRecurrspec),$eid));
237 // specify some special variables needed for the INSERT
238 // no recurr specs, this is used for adding a new non-recurring event
239 $noRecurrspec = array("event_repeat_freq" => "",
240 "event_repeat_freq_type" => "",
241 "event_repeat_on_num" => "1",
242 "event_repeat_on_day" => "0",
243 "event_repeat_on_freq" => "0",
244 "exdate" => ""
246 // Useless garbage that we must save.
247 $locationspecs = array("event_location" => "",
248 "event_street1" => "",
249 "event_street2" => "",
250 "event_city" => "",
251 "event_state" => "",
252 "event_postal" => ""
254 $locationspec = serialize($locationspecs);
255 $args['event_date'] = date('Y-m-d');
256 $args['duration'] = $duration;
257 // this event is forced to NOT REPEAT
258 $args['form_repeat'] = "0";
259 $args['recurrspec'] = $noRecurrspec;
260 $args['form_enddate'] = "0000-00-00";
261 $args['starttime'] = $starttime;
262 $args['endtime'] = $endtime;
263 $args['locationspec'] = $locationspec;
264 $args['form_category']=$origEvent['pc_catid'];
265 $args['new_multiple_value']=$origEvent['pc_multiple'];
266 $args['form_provider']=$origEvent['pc_aid'];
267 $args['form_pid']=$origEvent['pc_pid'];
268 $args['form_title']=$origEvent['pc_title'];
269 $args['form_allday']=$origEvent['pc_alldayevent'];
270 $args['form_apptstatus']='@';
271 $args['form_prefcat']=$origEvent['pc_prefcatid'];
272 $args['facility']=$origEvent['pc_facility'];
273 $args['billing_facility']=$origEvent['pc_billing_location'];
274 InsertEvent($args,'payment');
276 //===============================================================================
277 // check if event exists
278 function check_event_exist($eid)
280 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
281 $origEvent=sqlFetchArray($origEventRes);
282 $pc_catid=$origEvent['pc_catid'];
283 $pc_aid=$origEvent['pc_aid'];
284 $pc_pid=$origEvent['pc_pid'];
285 $pc_eventDate=date('Y-m-d');
286 $pc_startTime=$origEvent['pc_startTime'];
287 $pc_endTime=$origEvent['pc_endTime'];
288 $pc_facility=$origEvent['pc_facility'];
289 $pc_billing_location=$origEvent['pc_billing_location'];
290 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
291 $origEvent = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
292 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
293 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location));
294 if(sqlNumRows($origEvent)>0)
296 $origEventRow=sqlFetchArray($origEvent);
297 return $origEventRow['pc_eid'];
299 else
301 if(strpos($pc_recurrspec_array['exdate'],date('Ymd')) === false)//;'20110228'
303 return false;
305 else
306 {//this happens in delete case
307 return true;
311 //===============================================================================
312 // insert an event
313 // $args is mainly filled with content from the POST http var
314 function InsertEvent($args,$from = 'general') {
315 $pc_recurrtype = '0';
316 if ($args['form_repeat'] || $args['days_every_week']) {
317 if($args['recurrspec']['event_repeat_freq_type'] == "6"){
318 $pc_recurrtype = 3;
320 else {
321 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
324 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
325 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
327 if($from == 'general'){
328 $pc_eid = sqlInsert("INSERT INTO openemr_postcalendar_events ( " .
329 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, pc_hometext, " .
330 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
331 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
332 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
333 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
334 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,
335 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
336 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
337 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
338 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
341 //Manage tracker status.
342 if (!empty($form_pid)) {
343 manage_tracker_status($args['event_date'],$args['starttime'],$pc_eid,$form_pid,$_SESSION['authUser'],$args['form_apptstatus'],$args['form_room']);
345 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
347 return $pc_eid;
349 }elseif($from == 'payment'){
350 sqlStatement("INSERT INTO openemr_postcalendar_events ( " .
351 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
352 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
353 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
354 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
355 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
356 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
357 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
358 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
359 1,1,(int)$args['facility'],(int)$args['billing_facility']));
362 //================================================================================================================
364 * __increment()
365 * returns the next valid date for an event based on the
366 * current day,month,year,freq and type
367 * @private
368 * @returns string YYYY-MM-DD
370 function &__increment($d,$m,$y,$f,$t)
373 if($t == REPEAT_EVERY_DAY) {
374 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
375 } elseif($t == REPEAT_EVERY_WORK_DAY) {
376 // a workday is defined as Mon,Tue,Wed,Thu,Fri
377 // repeating on every or Nth work day means to not include
378 // weekends (Sat/Sun) in the increment... tricky
380 // ugh, a day-by-day loop seems necessary here, something where
381 // we can check to see if the day is a Sat/Sun and increment
382 // the frequency count so as to ignore the weekend. hmmmm....
383 $orig_freq = $f;
384 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
385 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$daycount),$y));
386 if (is_weekend_day($nextWorkDOW)) { $f++; }
389 // and finally make sure we haven't landed on a end week days
390 // adjust as necessary
391 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$f),$y));
392 if (count($GLOBALS['weekend_days']) === 2){
393 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
394 $f+=2;
395 }elseif($nextWorkDOW == $GLOBALS['weekend_days'][1]){
396 $f++;
398 } elseif(count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
399 $f++;
402 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
404 } elseif($t == REPEAT_EVERY_WEEK) {
405 return date('Y-m-d',mktime(0,0,0,$m,($d+(7*$f)),$y));
406 } elseif($t == REPEAT_EVERY_MONTH) {
407 return date('Y-m-d',mktime(0,0,0,($m+$f),$d,$y));
408 } elseif($t == REPEAT_EVERY_YEAR) {
409 return date('Y-m-d',mktime(0,0,0,$m,$d,($y+$f)));
410 }elseif($t == REPEAT_DAYS_EVERY_WEEK) {
411 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
412 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
413 return $next_appointment_date;
417 function getTheNextAppointment($appointment_date, $freq){
418 $day_arr = explode(",", $freq);
419 $date_arr = array();
420 foreach ($day_arr as $day){
421 $day = getDayName($day);
422 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
423 array_push($date_arr, $date);
425 $next_appointment = getEarliestDate($date_arr);
426 return $next_appointment;
431 function getDayName($day_num){
432 if($day_num == "1"){return "sunday";}
433 if($day_num == "2"){return "monday";}
434 if($day_num == "3"){return "tuesday";}
435 if($day_num == "4"){return "wednesday";}
436 if($day_num == "5"){return "thursday";}
437 if($day_num == "6"){return "friday";}
438 if($day_num == "7"){return "saturday";}
442 function getEarliestDate($date_arr){
443 $earliest = ($date_arr[0]);
444 foreach ($date_arr as $date){
445 if(strtotime($date) < strtotime($earliest)){
446 $earliest = $date;
449 return $earliest;
451 //================================================================================================================