minor bug fix
[openemr.git] / library / encounter_events.inc.php
blobcef70da1c04e7324a143637ae30c8739bb2b74fc
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 // +------------------------------------------------------------------------------+
27 //===============================================================================
28 //This section handles the events of payment screen.
29 //===============================================================================
30 define('REPEAT_EVERY_DAY', 0);
31 define('REPEAT_EVERY_WEEK', 1);
32 define('REPEAT_EVERY_MONTH', 2);
33 define('REPEAT_EVERY_YEAR', 3);
34 define('REPEAT_EVERY_WORK_DAY',4);
35 //===============================================================================
36 //Create event in calender as arrived
37 function calendar_arrived($form_pid) {
38 $Today=date('Y-m-d');
39 //Take all recurring events relevent for today.
40 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_recurrtype != '0' and pc_pid = ? and pc_endDate != '0000-00-00'
41 and pc_eventDate < ? and pc_endDate >= ? ",
42 array($form_pid,$Today,$Today));
43 if(sqlNumRows($result_event)==0)//no repeating appointment
45 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_pid =? and pc_eventDate = ?",
46 array($form_pid,$Today));
47 if(sqlNumRows($result_event)==0)//no appointment
49 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
50 die;
52 else//one appointment
54 $enc = todaysEncounterCheck($form_pid);//create encounter
55 $zero_enc=0;
56 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus ='@' WHERE pc_pid =? and pc_eventDate = ?",
57 array($form_pid,$Today));
60 else//repeating appointment set
62 while($row_event=sqlFetchArray($result_event))
64 $pc_eid = $row_event['pc_eid'];
65 $pc_eventDate = $row_event['pc_eventDate'];
66 $pc_recurrspec_array = unserialize($row_event['pc_recurrspec']);
67 while(1)
69 if($pc_eventDate==$Today)//Matches so insert.
71 if(!$exist_eid=check_event_exist($pc_eid))
73 update_event($pc_eid);
75 else
77 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?",
78 array($exist_eid));
80 $enc = todaysEncounterCheck($form_pid);//create encounter
81 $zero_enc=0;
82 break;
84 elseif($pc_eventDate>$Today)//the frequency does not match today,no need to increment furthur.
86 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
87 die;
88 break;
91 // Added by Rod to handle repeats on nth or last given weekday of a month:
92 if ($row_event['pc_recurrtype'] == 2) {
93 $my_repeat_on_day = $pc_recurrspec_array['event_repeat_on_day'];
94 $my_repeat_on_num = $pc_recurrspec_array['event_repeat_on_num'];
95 $adate = getdate(strtotime($pc_eventDate));
96 $adate['mon'] += 1;
97 if ($adate['mon'] > 12) {
98 $adate['year'] += 1;
99 $adate['mon'] -= 12;
101 if ($my_repeat_on_num < 5) { // not last
102 $adate['mday'] = 1;
103 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
104 if ($dow > $my_repeat_on_day) $dow -= 7;
105 $adate['mday'] += ($my_repeat_on_num - 1) * 7 + $my_repeat_on_day - $dow;
107 else { // last weekday of month
108 $adate['mday'] = cal_days_in_month(CAL_GREGORIAN, $adate['mon'], $adate['year']);
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_day - $dow;
113 $pc_eventDate = date('Y-m-d', mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']));
114 } // end recurrtype 2
116 else { // pc_recurrtype is 1
117 $pc_eventDate_array = split('-', $pc_eventDate);
118 // Find the next day as per the frequency definition.
119 $pc_eventDate =& __increment($pc_eventDate_array[2], $pc_eventDate_array[1], $pc_eventDate_array[0],
120 $pc_recurrspec_array['event_repeat_freq'], $pc_recurrspec_array['event_repeat_freq_type']);
126 return $enc;
128 //===============================================================================
129 // Checks for the patient's encounter ID for today, creating it if there is none.
131 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true){
132 global $today;
133 $encounter = todaysEncounterIf($patient_id);
134 if($encounter){
135 if($return_existing){
136 return $encounter;
137 }else{
138 return 0;
141 $dos = $enc_date ? $enc_date : $today;
142 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
143 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
144 $username = $tmprow['username'];
145 $facility = $tmprow['facility'];
146 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
147 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
148 $visit_provider = $provider ? (int)$provider : '(NULL)';
149 $visit_cat = $cat ? $cat : '(NULL)';
150 $conn = $GLOBALS['adodb']['db'];
151 $encounter = $conn->GenID("sequences");
152 addForm($encounter, "New Patient Encounter",
153 sqlInsert("INSERT INTO form_encounter SET " .
154 "date = ?, " .
155 "reason = ?, " .
156 "facility = ?, " .
157 "facility_id = ?, " .
158 "billing_facility = ?, " .
159 "provider_id = ?, " .
160 "pid = ?, " .
161 "encounter = ?," .
162 "pc_catid = ?",
163 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
165 "newpatient", $patient_id, "1", "NOW()", $username
167 return $encounter;
169 //===============================================================================
170 // Get the patient's encounter ID for today, if it exists.
171 // In the case of more than one encounter today, pick the last one.
173 function todaysEncounterIf($patient_id) {
174 global $today;
175 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
176 "pid = ? AND date = ? " .
177 "ORDER BY encounter DESC LIMIT 1",array($patient_id,"$today 00:00:00"));
178 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
180 //===============================================================================
182 // Get the patient's encounter ID for today, creating it if there is none.
184 function todaysEncounter($patient_id, $reason='') {
185 global $today, $userauthorized;
187 if (empty($reason)) $reason = xl('Please indicate visit reason');
189 // Was going to use the existing encounter for today if there is one, but
190 // decided it's right to always create a new one. Leaving the code here
191 // (and corresponding function above) in case it is ever wanted later.
192 /*******************************************************************
193 $encounter = todaysEncounterIf($patient_id);
194 if ($encounter) return $encounter;
195 *******************************************************************/
197 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
198 "WHERE id = ?", array($_SESSION["authUserID"]));
199 $username = $tmprow['username'];
200 $facility = $tmprow['facility'];
201 $facility_id = $tmprow['facility_id'];
202 $conn = $GLOBALS['adodb']['db'];
203 $encounter = $conn->GenID("sequences");
204 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
205 addForm($encounter, "New Patient Encounter",
206 sqlInsert("INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
207 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
208 "provider_id = ?",
209 array($today, $today, $reason, $facility, $facility_id, $patient_id,
210 $encounter, $provider_id)
212 "newpatient", $patient_id, $userauthorized, "NOW()", $username
214 return $encounter;
216 //===============================================================================
217 // get the original event's repeat specs
218 function update_event($eid)
220 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
221 $origEvent=sqlFetchArray($origEventRes);
222 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
223 $duration=$origEvent['pc_duration'];
224 $starttime=$origEvent['pc_startTime'];
225 $endtime=$origEvent['pc_endTime'];
226 $selected_date = date("Ymd");
227 if ($oldRecurrspec['exdate'] != "") { $oldRecurrspec['exdate'] .= ",".$selected_date; }
228 else { $oldRecurrspec['exdate'] .= $selected_date; }
229 // mod original event recur specs to exclude this date
230 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?",array(serialize($oldRecurrspec),$eid));
231 // specify some special variables needed for the INSERT
232 // no recurr specs, this is used for adding a new non-recurring event
233 $noRecurrspec = array("event_repeat_freq" => "",
234 "event_repeat_freq_type" => "",
235 "event_repeat_on_num" => "1",
236 "event_repeat_on_day" => "0",
237 "event_repeat_on_freq" => "0",
238 "exdate" => ""
240 // Useless garbage that we must save.
241 $locationspecs = array("event_location" => "",
242 "event_street1" => "",
243 "event_street2" => "",
244 "event_city" => "",
245 "event_state" => "",
246 "event_postal" => ""
248 $locationspec = serialize($locationspecs);
249 $args['event_date'] = date('Y-m-d');
250 $args['duration'] = $duration;
251 // this event is forced to NOT REPEAT
252 $args['form_repeat'] = "0";
253 $args['recurrspec'] = $noRecurrspec;
254 $args['form_enddate'] = "0000-00-00";
255 $args['starttime'] = $starttime;
256 $args['endtime'] = $endtime;
257 $args['locationspec'] = $locationspec;
258 $args['form_category']=$origEvent['pc_catid'];
259 $args['new_multiple_value']=$origEvent['pc_multiple'];
260 $args['form_provider']=$origEvent['pc_aid'];
261 $args['form_pid']=$origEvent['pc_pid'];
262 $args['form_title']=$origEvent['pc_title'];
263 $args['form_allday']=$origEvent['pc_alldayevent'];
264 $args['form_apptstatus']='@';
265 $args['form_prefcat']=$origEvent['pc_prefcatid'];
266 $args['facility']=$origEvent['pc_facility'];
267 $args['billing_facility']=$origEvent['pc_billing_location'];
268 InsertEvent($args,'payment');
270 //===============================================================================
271 // check if event exists
272 function check_event_exist($eid)
274 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
275 $origEvent=sqlFetchArray($origEventRes);
276 $pc_catid=$origEvent['pc_catid'];
277 $pc_aid=$origEvent['pc_aid'];
278 $pc_pid=$origEvent['pc_pid'];
279 $pc_eventDate=date('Y-m-d');
280 $pc_startTime=$origEvent['pc_startTime'];
281 $pc_endTime=$origEvent['pc_endTime'];
282 $pc_facility=$origEvent['pc_facility'];
283 $pc_billing_location=$origEvent['pc_billing_location'];
284 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
285 $origEvent = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
286 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
287 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location));
288 if(sqlNumRows($origEvent)>0)
290 $origEventRow=sqlFetchArray($origEvent);
291 return $origEventRow['pc_eid'];
293 else
295 if(strpos($pc_recurrspec_array['exdate'],date('Ymd')) === false)//;'20110228'
297 return false;
299 else
300 {//this happens in delete case
301 return true;
305 //===============================================================================
306 // insert an event
307 // $args is mainly filled with content from the POST http var
308 function InsertEvent($args,$from = 'general') {
309 $pc_recurrtype = '0';
310 if ($args['form_repeat']) {
311 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
314 if($from == 'general'){
315 return sqlInsert("INSERT INTO openemr_postcalendar_events ( " .
316 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, pc_hometext, " .
317 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
318 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
319 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
320 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?)",
321 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$args['form_pid'],
322 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
323 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
324 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
325 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'])
327 }elseif($from == 'payment'){
328 sqlStatement("INSERT INTO openemr_postcalendar_events ( " .
329 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
330 "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 " .
333 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
334 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$args['form_pid'],$args['form_title'],
335 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
336 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
337 1,1,(int)$args['facility'],(int)$args['billing_facility']));
340 //================================================================================================================
342 * __increment()
343 * returns the next valid date for an event based on the
344 * current day,month,year,freq and type
345 * @private
346 * @returns string YYYY-MM-DD
348 function &__increment($d,$m,$y,$f,$t)
350 if($t == REPEAT_EVERY_DAY) {
351 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
352 } elseif($t == REPEAT_EVERY_WORK_DAY) {
353 // a workday is defined as Mon,Tue,Wed,Thu,Fri
354 // repeating on every or Nth work day means to not include
355 // weekends (Sat/Sun) in the increment... tricky
357 // ugh, a day-by-day loop seems necessary here, something where
358 // we can check to see if the day is a Sat/Sun and increment
359 // the frequency count so as to ignore the weekend. hmmmm....
360 $orig_freq = $f;
361 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
362 $nextWorkDOW = date('D',mktime(0,0,0,$m,($d+$daycount),$y));
363 if ($nextWorkDOW == "Sat") { $f++; }
364 else if ($nextWorkDOW == "Sun") { $f++; }
366 // and finally make sure we haven't landed on a Sat/Sun
367 // adjust as necessary
368 $nextWorkDOW = date('D',mktime(0,0,0,$m,($d+$f),$y));
369 if ($nextWorkDOW == "Sat") { $f+=2; }
370 else if ($nextWorkDOW == "Sun") { $f++; }
372 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
374 } elseif($t == REPEAT_EVERY_WEEK) {
375 return date('Y-m-d',mktime(0,0,0,$m,($d+(7*$f)),$y));
376 } elseif($t == REPEAT_EVERY_MONTH) {
377 return date('Y-m-d',mktime(0,0,0,($m+$f),$d,$y));
378 } elseif($t == REPEAT_EVERY_YEAR) {
379 return date('Y-m-d',mktime(0,0,0,$m,$d,($y+$f)));
382 //================================================================================================================