removed redundant docs (it is on the wiki)
[openemr.git] / library / encounter_events.inc.php
blob66aa37db4cc20261f61e803434e304c70824628a
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 //===============================================================================
41 //Create event in calender as arrived
42 function calendar_arrived($form_pid) {
43 $Today=date('Y-m-d');
44 //Take all recurring events relevent for today.
45 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_recurrtype != '0' and pc_pid = ? and pc_endDate != '0000-00-00'
46 and pc_eventDate < ? and pc_endDate >= ? ",
47 array($form_pid,$Today,$Today));
48 if(sqlNumRows($result_event)==0)//no repeating appointment
50 $result_event=sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_pid =? and pc_eventDate = ?",
51 array($form_pid,$Today));
52 if(sqlNumRows($result_event)==0)//no appointment
54 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
55 die;
57 else//one appointment
59 $enc = todaysEncounterCheck($form_pid);//create encounter
60 $zero_enc=0;
61 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus ='@' WHERE pc_pid =? and pc_eventDate = ?",
62 array($form_pid,$Today));
65 else//repeating appointment set
67 while($row_event=sqlFetchArray($result_event))
69 $pc_eid = $row_event['pc_eid'];
70 $pc_eventDate = $row_event['pc_eventDate'];
71 $pc_recurrspec_array = unserialize($row_event['pc_recurrspec']);
72 while(1)
74 if($pc_eventDate==$Today)//Matches so insert.
76 if(!$exist_eid=check_event_exist($pc_eid))
78 update_event($pc_eid);
80 else
82 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?",
83 array($exist_eid));
85 $enc = todaysEncounterCheck($form_pid);//create encounter
86 $zero_enc=0;
87 break;
89 elseif($pc_eventDate>$Today)//the frequency does not match today,no need to increment furthur.
91 echo "<br><br><br>".htmlspecialchars( xl('Sorry No Appointment is Fixed'), ENT_QUOTES ).". ".htmlspecialchars( xl('No Encounter could be created'), ENT_QUOTES ).".";
92 die;
93 break;
96 // Added by Rod to handle repeats on nth or last given weekday of a month:
97 if ($row_event['pc_recurrtype'] == 2) {
98 $my_repeat_on_day = $pc_recurrspec_array['event_repeat_on_day'];
99 $my_repeat_on_num = $pc_recurrspec_array['event_repeat_on_num'];
100 $adate = getdate(strtotime($pc_eventDate));
101 $adate['mon'] += 1;
102 if ($adate['mon'] > 12) {
103 $adate['year'] += 1;
104 $adate['mon'] -= 12;
106 if ($my_repeat_on_num < 5) { // not last
107 $adate['mday'] = 1;
108 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
109 if ($dow > $my_repeat_on_day) $dow -= 7;
110 $adate['mday'] += ($my_repeat_on_num - 1) * 7 + $my_repeat_on_day - $dow;
112 else { // last weekday of month
113 $adate['mday'] = cal_days_in_month(CAL_GREGORIAN, $adate['mon'], $adate['year']);
114 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
115 if ($dow < $my_repeat_on_day) $dow += 7;
116 $adate['mday'] += $my_repeat_on_day - $dow;
118 $pc_eventDate = date('Y-m-d', mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']));
119 } // end recurrtype 2
121 else { // pc_recurrtype is 1
122 $pc_eventDate_array = explode('-', $pc_eventDate);
123 // Find the next day as per the frequency definition.
124 $pc_eventDate =& __increment($pc_eventDate_array[2], $pc_eventDate_array[1], $pc_eventDate_array[0],
125 $pc_recurrspec_array['event_repeat_freq'], $pc_recurrspec_array['event_repeat_freq_type']);
131 return $enc;
133 //===============================================================================
134 // Checks for the patient's encounter ID for today, creating it if there is none.
136 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true){
137 global $today;
138 $encounter = todaysEncounterIf($patient_id);
139 if($encounter){
140 if($return_existing){
141 return $encounter;
142 }else{
143 return 0;
146 $dos = $enc_date ? $enc_date : $today;
147 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
148 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
149 $username = $tmprow['username'];
150 $facility = $tmprow['facility'];
151 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
152 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
153 $visit_provider = $provider ? (int)$provider : '(NULL)';
154 $visit_cat = $cat ? $cat : '(NULL)';
155 $conn = $GLOBALS['adodb']['db'];
156 $encounter = $conn->GenID("sequences");
157 addForm($encounter, "New Patient Encounter",
158 sqlInsert("INSERT INTO form_encounter SET " .
159 "date = ?, " .
160 "reason = ?, " .
161 "facility = ?, " .
162 "facility_id = ?, " .
163 "billing_facility = ?, " .
164 "provider_id = ?, " .
165 "pid = ?, " .
166 "encounter = ?," .
167 "pc_catid = ?",
168 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
170 "newpatient", $patient_id, "1", "NOW()", $username
172 return $encounter;
174 //===============================================================================
175 // Get the patient's encounter ID for today, if it exists.
176 // In the case of more than one encounter today, pick the last one.
178 function todaysEncounterIf($patient_id) {
179 global $today;
180 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
181 "pid = ? AND date = ? " .
182 "ORDER BY encounter DESC LIMIT 1",array($patient_id,"$today 00:00:00"));
183 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
185 //===============================================================================
187 // Get the patient's encounter ID for today, creating it if there is none.
189 function todaysEncounter($patient_id, $reason='') {
190 global $today, $userauthorized;
192 if (empty($reason)) $reason = xl('Please indicate visit reason');
194 // Was going to use the existing encounter for today if there is one, but
195 // decided it's right to always create a new one. Leaving the code here
196 // (and corresponding function above) in case it is ever wanted later.
197 /*******************************************************************
198 $encounter = todaysEncounterIf($patient_id);
199 if ($encounter) return $encounter;
200 *******************************************************************/
202 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
203 "WHERE id = ?", array($_SESSION["authUserID"]));
204 $username = $tmprow['username'];
205 $facility = $tmprow['facility'];
206 $facility_id = $tmprow['facility_id'];
207 $conn = $GLOBALS['adodb']['db'];
208 $encounter = $conn->GenID("sequences");
209 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
210 addForm($encounter, "New Patient Encounter",
211 sqlInsert("INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
212 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
213 "provider_id = ?",
214 array($today, $today, $reason, $facility, $facility_id, $patient_id,
215 $encounter, $provider_id)
217 "newpatient", $patient_id, $userauthorized, "NOW()", $username
219 return $encounter;
221 //===============================================================================
222 // get the original event's repeat specs
223 function update_event($eid)
225 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
226 $origEvent=sqlFetchArray($origEventRes);
227 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
228 $duration=$origEvent['pc_duration'];
229 $starttime=$origEvent['pc_startTime'];
230 $endtime=$origEvent['pc_endTime'];
231 $selected_date = date("Ymd");
232 if ($oldRecurrspec['exdate'] != "") { $oldRecurrspec['exdate'] .= ",".$selected_date; }
233 else { $oldRecurrspec['exdate'] .= $selected_date; }
234 // mod original event recur specs to exclude this date
235 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?",array(serialize($oldRecurrspec),$eid));
236 // specify some special variables needed for the INSERT
237 // no recurr specs, this is used for adding a new non-recurring event
238 $noRecurrspec = array("event_repeat_freq" => "",
239 "event_repeat_freq_type" => "",
240 "event_repeat_on_num" => "1",
241 "event_repeat_on_day" => "0",
242 "event_repeat_on_freq" => "0",
243 "exdate" => ""
245 // Useless garbage that we must save.
246 $locationspecs = array("event_location" => "",
247 "event_street1" => "",
248 "event_street2" => "",
249 "event_city" => "",
250 "event_state" => "",
251 "event_postal" => ""
253 $locationspec = serialize($locationspecs);
254 $args['event_date'] = date('Y-m-d');
255 $args['duration'] = $duration;
256 // this event is forced to NOT REPEAT
257 $args['form_repeat'] = "0";
258 $args['recurrspec'] = $noRecurrspec;
259 $args['form_enddate'] = "0000-00-00";
260 $args['starttime'] = $starttime;
261 $args['endtime'] = $endtime;
262 $args['locationspec'] = $locationspec;
263 $args['form_category']=$origEvent['pc_catid'];
264 $args['new_multiple_value']=$origEvent['pc_multiple'];
265 $args['form_provider']=$origEvent['pc_aid'];
266 $args['form_pid']=$origEvent['pc_pid'];
267 $args['form_title']=$origEvent['pc_title'];
268 $args['form_allday']=$origEvent['pc_alldayevent'];
269 $args['form_apptstatus']='@';
270 $args['form_prefcat']=$origEvent['pc_prefcatid'];
271 $args['facility']=$origEvent['pc_facility'];
272 $args['billing_facility']=$origEvent['pc_billing_location'];
273 InsertEvent($args,'payment');
275 //===============================================================================
276 // check if event exists
277 function check_event_exist($eid)
279 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
280 $origEvent=sqlFetchArray($origEventRes);
281 $pc_catid=$origEvent['pc_catid'];
282 $pc_aid=$origEvent['pc_aid'];
283 $pc_pid=$origEvent['pc_pid'];
284 $pc_eventDate=date('Y-m-d');
285 $pc_startTime=$origEvent['pc_startTime'];
286 $pc_endTime=$origEvent['pc_endTime'];
287 $pc_facility=$origEvent['pc_facility'];
288 $pc_billing_location=$origEvent['pc_billing_location'];
289 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
290 $origEvent = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
291 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
292 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location));
293 if(sqlNumRows($origEvent)>0)
295 $origEventRow=sqlFetchArray($origEvent);
296 return $origEventRow['pc_eid'];
298 else
300 if(strpos($pc_recurrspec_array['exdate'],date('Ymd')) === false)//;'20110228'
302 return false;
304 else
305 {//this happens in delete case
306 return true;
310 //===============================================================================
311 // insert an event
312 // $args is mainly filled with content from the POST http var
313 function InsertEvent($args,$from = 'general') {
314 $pc_recurrtype = '0';
315 if ($args['form_repeat']) {
316 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
318 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
319 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
321 if($from == 'general'){
322 $pc_eid = sqlInsert("INSERT INTO openemr_postcalendar_events ( " .
323 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, pc_hometext, " .
324 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
325 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
326 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
327 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
328 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,
329 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
330 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
331 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
332 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
335 //Manage tracker status.
336 if (!empty($form_pid)) {
337 manage_tracker_status($args['event_date'],$args['starttime'],$pc_eid,$form_pid,$_SESSION['authUser'],$args['form_apptstatus'],$args['form_room']);
339 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
341 return $pc_eid;
343 }elseif($from == 'payment'){
344 sqlStatement("INSERT INTO openemr_postcalendar_events ( " .
345 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
346 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
347 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
348 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
349 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
350 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
351 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
352 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
353 1,1,(int)$args['facility'],(int)$args['billing_facility']));
356 //================================================================================================================
358 * __increment()
359 * returns the next valid date for an event based on the
360 * current day,month,year,freq and type
361 * @private
362 * @returns string YYYY-MM-DD
364 function &__increment($d,$m,$y,$f,$t)
366 if($t == REPEAT_EVERY_DAY) {
367 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
368 } elseif($t == REPEAT_EVERY_WORK_DAY) {
369 // a workday is defined as Mon,Tue,Wed,Thu,Fri
370 // repeating on every or Nth work day means to not include
371 // weekends (Sat/Sun) in the increment... tricky
373 // ugh, a day-by-day loop seems necessary here, something where
374 // we can check to see if the day is a Sat/Sun and increment
375 // the frequency count so as to ignore the weekend. hmmmm....
376 $orig_freq = $f;
377 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
378 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$daycount),$y));
379 if (is_weekend_day($nextWorkDOW)) { $f++; }
382 // and finally make sure we haven't landed on a end week days
383 // adjust as necessary
384 $nextWorkDOW = date('w',mktime(0,0,0,$m,($d+$f),$y));
385 if (count($GLOBALS['weekend_days']) === 2){
386 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
387 $f+=2;
388 }elseif($nextWorkDOW == $GLOBALS['weekend_days'][1]){
389 $f++;
391 } elseif(count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
392 $f++;
395 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
397 } elseif($t == REPEAT_EVERY_WEEK) {
398 return date('Y-m-d',mktime(0,0,0,$m,($d+(7*$f)),$y));
399 } elseif($t == REPEAT_EVERY_MONTH) {
400 return date('Y-m-d',mktime(0,0,0,($m+$f),$d,$y));
401 } elseif($t == REPEAT_EVERY_YEAR) {
402 return date('Y-m-d',mktime(0,0,0,$m,$d,($y+$f)));
405 //================================================================================================================