This commit helps in the following
[openemr.git] / library / encounter_events.inc.php
blob968e1e50fdb2e41b1080a554ee654ae1eec49e0d
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='1' 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;
90 $pc_eventDate_array=split('-',$pc_eventDate);
91 //Find the next day as per the frequency definition.
92 $pc_eventDate=& __increment($pc_eventDate_array[2],$pc_eventDate_array[1],$pc_eventDate_array[0],
93 $pc_recurrspec_array['event_repeat_freq'],$pc_recurrspec_array['event_repeat_freq_type']);
97 return $enc;
99 //===============================================================================
100 // Checks for the patient's encounter ID for today, creating it if there is none.
102 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true){
103 global $today;
104 $encounter = todaysEncounterIf($patient_id);
105 if($encounter){
106 if($return_existing){
107 return $encounter;
108 }else{
109 return 0;
112 $dos = $enc_date ? $enc_date : $today;
113 $visit_reason = $reason ? $reason : 'Please indicate visit reason';
114 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]) );
115 $username = $tmprow['username'];
116 $facility = $tmprow['facility'];
117 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
118 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
119 $visit_provider = $provider ? (int)$provider : '(NULL)';
120 $visit_cat = $cat ? $cat : '(NULL)';
121 $conn = $GLOBALS['adodb']['db'];
122 $encounter = $conn->GenID("sequences");
123 addForm($encounter, "New Patient Encounter",
124 sqlInsert("INSERT INTO form_encounter SET " .
125 "date = ?, " .
126 "reason = ?, " .
127 "facility = ?, " .
128 "facility_id = ?, " .
129 "billing_facility = ?, " .
130 "provider_id = ?, " .
131 "pid = ?, " .
132 "encounter = ?," .
133 "pc_catid = ?",
134 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
136 "newpatient", $patient_id, "1", "NOW()", $username
138 return $encounter;
140 //===============================================================================
141 // Get the patient's encounter ID for today, if it exists.
142 // In the case of more than one encounter today, pick the last one.
144 function todaysEncounterIf($patient_id) {
145 global $today;
146 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
147 "pid = ? AND date = ? " .
148 "ORDER BY encounter DESC LIMIT 1",array($patient_id,"$today 00:00:00"));
149 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
151 //===============================================================================
153 // Get the patient's encounter ID for today, creating it if there is none.
155 function todaysEncounter($patient_id, $reason='') {
156 global $today, $userauthorized;
158 if (empty($reason)) $reason = xl('Please indicate visit reason');
160 // Was going to use the existing encounter for today if there is one, but
161 // decided it's right to always create a new one. Leaving the code here
162 // (and corresponding function above) in case it is ever wanted later.
163 /*******************************************************************
164 $encounter = todaysEncounterIf($patient_id);
165 if ($encounter) return $encounter;
166 *******************************************************************/
168 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
169 "WHERE id = ?", array($_SESSION["authUserID"]));
170 $username = $tmprow['username'];
171 $facility = $tmprow['facility'];
172 $facility_id = $tmprow['facility_id'];
173 $conn = $GLOBALS['adodb']['db'];
174 $encounter = $conn->GenID("sequences");
175 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
176 addForm($encounter, "New Patient Encounter",
177 sqlInsert("INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
178 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
179 "provider_id = ?",
180 array($today, $today, $reason, $facility, $facility_id, $patient_id,
181 $encounter, $provider_id)
183 "newpatient", $patient_id, $userauthorized, "NOW()", $username
185 return $encounter;
187 //===============================================================================
188 // get the original event's repeat specs
189 function update_event($eid)
191 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
192 $origEvent=sqlFetchArray($origEventRes);
193 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
194 $duration=$origEvent['pc_duration'];
195 $starttime=$origEvent['pc_startTime'];
196 $endtime=$origEvent['pc_endTime'];
197 $selected_date = date("Ymd");
198 if ($oldRecurrspec['exdate'] != "") { $oldRecurrspec['exdate'] .= ",".$selected_date; }
199 else { $oldRecurrspec['exdate'] .= $selected_date; }
200 // mod original event recur specs to exclude this date
201 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?",array(serialize($oldRecurrspec),$eid));
202 // specify some special variables needed for the INSERT
203 // no recurr specs, this is used for adding a new non-recurring event
204 $noRecurrspec = array("event_repeat_freq" => "",
205 "event_repeat_freq_type" => "",
206 "event_repeat_on_num" => "1",
207 "event_repeat_on_day" => "0",
208 "event_repeat_on_freq" => "0",
209 "exdate" => ""
211 // Useless garbage that we must save.
212 $locationspecs = array("event_location" => "",
213 "event_street1" => "",
214 "event_street2" => "",
215 "event_city" => "",
216 "event_state" => "",
217 "event_postal" => ""
219 $locationspec = serialize($locationspecs);
220 $args['event_date'] = date('Y-m-d');
221 $args['duration'] = $duration;
222 // this event is forced to NOT REPEAT
223 $args['form_repeat'] = "0";
224 $args['recurrspec'] = $noRecurrspec;
225 $args['form_enddate'] = "0000-00-00";
226 $args['starttime'] = $starttime;
227 $args['endtime'] = $endtime;
228 $args['locationspec'] = $locationspec;
229 $args['form_category']=$origEvent['pc_catid'];
230 $args['new_multiple_value']=$origEvent['pc_multiple'];
231 $args['form_provider']=$origEvent['pc_aid'];
232 $args['form_pid']=$origEvent['pc_pid'];
233 $args['form_title']=$origEvent['pc_title'];
234 $args['form_allday']=$origEvent['pc_alldayevent'];
235 $args['form_apptstatus']='@';
236 $args['form_prefcat']=$origEvent['pc_prefcatid'];
237 $args['facility']=$origEvent['pc_facility'];
238 $args['billing_facility']=$origEvent['pc_billing_location'];
239 InsertEvent($args,'payment');
241 //===============================================================================
242 // check if event exists
243 function check_event_exist($eid)
245 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?",array($eid));
246 $origEvent=sqlFetchArray($origEventRes);
247 $pc_catid=$origEvent['pc_catid'];
248 $pc_aid=$origEvent['pc_aid'];
249 $pc_pid=$origEvent['pc_pid'];
250 $pc_eventDate=date('Y-m-d');
251 $pc_startTime=$origEvent['pc_startTime'];
252 $pc_endTime=$origEvent['pc_endTime'];
253 $pc_facility=$origEvent['pc_facility'];
254 $pc_billing_location=$origEvent['pc_billing_location'];
255 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
256 $origEvent = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
257 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
258 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location));
259 if(sqlNumRows($origEvent)>0)
261 $origEventRow=sqlFetchArray($origEvent);
262 return $origEventRow['pc_eid'];
264 else
266 if(strpos($pc_recurrspec_array['exdate'],date('Ymd')) === false)//;'20110228'
268 return false;
270 else
271 {//this happens in delete case
272 return true;
276 //===============================================================================
277 // insert an event
278 // $args is mainly filled with content from the POST http var
279 function InsertEvent($args,$from = 'general') {
280 if($from == 'general'){
281 return sqlInsert("INSERT INTO openemr_postcalendar_events ( " .
282 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, pc_hometext, " .
283 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
284 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
285 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
286 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?)",
287 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$args['form_pid'],
288 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
289 fixDate($args['form_enddate']),$args['duration'],($args['form_repeat'] ? '1' : '0'),serialize($args['recurrspec']),
290 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
291 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'])
293 }elseif($from == 'payment'){
294 sqlStatement("INSERT INTO openemr_postcalendar_events ( " .
295 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
296 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
297 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
298 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
299 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
300 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$args['form_pid'],$args['form_title'],
301 $args['event_date'],$args['form_enddate'],$args['duration'],($args['form_repeat'] ? '1' : '0'),serialize($args['recurrspec']),
302 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
303 1,1,(int)$args['facility'],(int)$args['billing_facility']));
306 //================================================================================================================
308 * __increment()
309 * returns the next valid date for an event based on the
310 * current day,month,year,freq and type
311 * @private
312 * @returns string YYYY-MM-DD
314 function &__increment($d,$m,$y,$f,$t)
316 if($t == REPEAT_EVERY_DAY) {
317 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
318 } elseif($t == REPEAT_EVERY_WORK_DAY) {
319 // a workday is defined as Mon,Tue,Wed,Thu,Fri
320 // repeating on every or Nth work day means to not include
321 // weekends (Sat/Sun) in the increment... tricky
323 // ugh, a day-by-day loop seems necessary here, something where
324 // we can check to see if the day is a Sat/Sun and increment
325 // the frequency count so as to ignore the weekend. hmmmm....
326 $orig_freq = $f;
327 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
328 $nextWorkDOW = date('D',mktime(0,0,0,$m,($d+$daycount),$y));
329 if ($nextWorkDOW == "Sat") { $f++; }
330 else if ($nextWorkDOW == "Sun") { $f++; }
332 // and finally make sure we haven't landed on a Sat/Sun
333 // adjust as necessary
334 $nextWorkDOW = date('D',mktime(0,0,0,$m,($d+$f),$y));
335 if ($nextWorkDOW == "Sat") { $f+=2; }
336 else if ($nextWorkDOW == "Sun") { $f++; }
338 return date('Y-m-d',mktime(0,0,0,$m,($d+$f),$y));
340 } elseif($t == REPEAT_EVERY_WEEK) {
341 return date('Y-m-d',mktime(0,0,0,$m,($d+(7*$f)),$y));
342 } elseif($t == REPEAT_EVERY_MONTH) {
343 return date('Y-m-d',mktime(0,0,0,($m+$f),$d,$y));
344 } elseif($t == REPEAT_EVERY_YEAR) {
345 return date('Y-m-d',mktime(0,0,0,$m,$d,($y+$f)));
348 //================================================================================================================