Fully responsive globals.php with vertical menu (#2460)
[openemr.git] / library / encounter_events.inc.php
blob194d79d770e305d9b497035decd02bab001aee8a
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>
25 // Ian Jardine ( github.com/epsdky ) ( Modified calendar_arrived )
27 // +------------------------------------------------------------------------------+
29 require_once(dirname(__FILE__) . '/calendar.inc');
30 require_once(dirname(__FILE__) . '/patient_tracker.inc.php');
33 //===============================================================================
34 //This section handles the events of payment screen.
35 //===============================================================================
36 define('REPEAT_EVERY_DAY', 0);
37 define('REPEAT_EVERY_WEEK', 1);
38 define('REPEAT_EVERY_MONTH', 2);
39 define('REPEAT_EVERY_YEAR', 3);
40 define('REPEAT_EVERY_WORK_DAY', 4);
41 define('REPEAT_DAYS_EVERY_WEEK', 6);
42 //===============================================================================
43 $today=date('Y-m-d');
44 //===============================================================================
45 // If unique current date appointment found update status to arrived and create
46 // encounter
48 function calendar_arrived($form_pid)
50 $appts = array();
51 $today = date('Y-m-d');
52 $appts = fetchAppointments($today, $today, $form_pid);
53 $appt_count = count($appts); //
54 if ($appt_count == 0) {
55 echo "<br><br><br><h2 style='text-align:center;'>" . htmlspecialchars(xl('Sorry No Appointment is Fixed'), ENT_QUOTES) . ". " . htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES) . ".</h2>";
56 exit;
57 } elseif ($appt_count == 1) {
58 $enc = todaysEncounterCheck($form_pid);
59 if ($appts[0]['pc_recurrtype'] == 0) {
60 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?", array($appts[0]['pc_eid']));
61 } else {
62 update_event($appts[0]['pc_eid']);
64 } elseif ($appt_count > 1) {
65 echo "<br><br><br><h2 style='text-align:center;'>" . htmlspecialchars(xl('More than one appointment was found'), ENT_QUOTES) . ". " . htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES) . ".</h2>";
66 exit;
68 return $enc;
71 //===============================================================================
72 // Checks for the patient's encounter ID for today, creating it if there is none.
74 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true)
76 global $today;
77 $encounter = todaysEncounterIf($patient_id);
78 if ($encounter && (int)$GLOBALS['auto_create_new_encounters'] !== 2) {
79 if ($return_existing) {
80 return $encounter;
81 } else {
82 return 0;
86 if (is_array($provider)) {
87 $visit_provider = (int)$provider[0];
88 } elseif ($provider) {
89 $visit_provider = (int)$provider;
90 } else {
91 $visit_provider = '(NULL)';
94 $dos = $enc_date ? $enc_date : $today;
95 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
96 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
97 $username = $tmprow['username'];
98 $facility = $tmprow['facility'];
99 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
100 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
101 $visit_cat = $cat ? $cat : '(NULL)';
102 $conn = $GLOBALS['adodb']['db'];
103 $encounter = $conn->GenID("sequences");
104 addForm(
105 $encounter,
106 "New Patient Encounter",
107 sqlInsert(
108 "INSERT INTO form_encounter SET " .
109 "date = ?, " .
110 "reason = ?, " .
111 "facility = ?, " .
112 "facility_id = ?, " .
113 "billing_facility = ?, " .
114 "provider_id = ?, " .
115 "pid = ?, " .
116 "encounter = ?," .
117 "pc_catid = ?",
118 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
120 "newpatient",
121 $patient_id,
122 "1",
123 "NOW()",
124 $username
126 return $encounter;
129 //===============================================================================
130 // Checks for the group's encounter ID for today, creating it if there is none.
132 function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null)
134 global $today;
135 $encounter = todaysTherapyGroupEncounterIf($group_id);
136 if ($encounter) {
137 if ($return_existing) {
138 return $encounter;
139 } else {
140 return 0;
144 if (is_array($provider)) {
145 $visit_provider = (int)$provider[0];
146 $counselors = implode(',', $provider);
147 } elseif ($provider) {
148 $visit_provider = $counselors = (int)$provider;
149 } else {
150 $visit_provider = $counselors = null;
153 $dos = $enc_date ? $enc_date : $today;
154 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
155 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
156 $username = $tmprow['username'];
157 $facility = $tmprow['facility'];
158 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
159 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
160 $visit_cat = $cat ? $cat : '(NULL)';
161 $conn = $GLOBALS['adodb']['db'];
162 $encounter = $conn->GenID("sequences");
163 addForm(
164 $encounter,
165 "New Therapy Group Encounter",
166 sqlInsert(
167 "INSERT INTO form_groups_encounter SET " .
168 "date = ?, " .
169 "reason = ?, " .
170 "facility = ?, " .
171 "facility_id = ?, " .
172 "billing_facility = ?, " .
173 "provider_id = ?, " .
174 "group_id = ?, " .
175 "encounter = ?," .
176 "pc_catid = ? ," .
177 "appt_id = ? ," .
178 "counselors = ? ",
179 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)
181 "newGroupEncounter",
182 null,
183 "1",
184 "NOW()",
185 $username,
187 $group_id
189 return $encounter;
191 //===============================================================================
192 // Get the patient's encounter ID for today, if it exists.
193 // In the case of more than one encounter today, pick the last one.
195 function todaysEncounterIf($patient_id)
197 global $today;
198 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
199 "pid = ? AND date = ? " .
200 "ORDER BY encounter DESC LIMIT 1", array($patient_id,"$today 00:00:00"));
201 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
203 //===============================================================================
204 // Get the group's encounter ID for today, if it exists.
205 // In the case of more than one encounter today, pick the last one.
207 function todaysTherapyGroupEncounterIf($group_id)
209 global $today;
210 $tmprow = sqlQuery("SELECT encounter FROM form_groups_encounter WHERE " .
211 "group_id = ? AND date = ? " .
212 "ORDER BY encounter DESC LIMIT 1", array($group_id,"$today 00:00:00"));
213 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
215 //===============================================================================
217 // Get the patient's encounter ID for today, creating it if there is none.
219 function todaysEncounter($patient_id, $reason = '')
221 global $today, $userauthorized;
223 if (empty($reason)) {
224 $reason = xl('Please indicate visit reason');
227 // Was going to use the existing encounter for today if there is one, but
228 // decided it's right to always create a new one. Leaving the code here
229 // (and corresponding function above) in case it is ever wanted later.
230 /*******************************************************************
231 $encounter = todaysEncounterIf($patient_id);
232 if ($encounter) return $encounter;
233 *******************************************************************/
235 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
236 "WHERE id = ?", array($_SESSION["authUserID"]));
237 $username = $tmprow['username'];
238 $facility = $tmprow['facility'];
239 $facility_id = $tmprow['facility_id'];
240 $conn = $GLOBALS['adodb']['db'];
241 $encounter = $conn->GenID("sequences");
242 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
243 addForm(
244 $encounter,
245 "New Patient Encounter",
246 sqlInsert(
247 "INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
248 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
249 "provider_id = ?",
250 array($today, $today, $reason, $facility, $facility_id, $patient_id,
251 $encounter, $provider_id)
253 "newpatient",
254 $patient_id,
255 $userauthorized,
256 "NOW()",
257 $username
259 return $encounter;
261 //===============================================================================
262 // get the original event's repeat specs
263 function update_event($eid)
265 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
266 $origEvent=sqlFetchArray($origEventRes);
267 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
268 $duration=$origEvent['pc_duration'];
269 $starttime=$origEvent['pc_startTime'];
270 $endtime=$origEvent['pc_endTime'];
271 $selected_date = date("Ymd");
272 if ($oldRecurrspec['exdate'] != "") {
273 $oldRecurrspec['exdate'] .= ",".$selected_date;
274 } else {
275 $oldRecurrspec['exdate'] .= $selected_date;
278 // mod original event recur specs to exclude this date
279 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?", array(serialize($oldRecurrspec),$eid));
280 // specify some special variables needed for the INSERT
281 // no recurr specs, this is used for adding a new non-recurring event
282 $noRecurrspec = array("event_repeat_freq" => "",
283 "event_repeat_freq_type" => "",
284 "event_repeat_on_num" => "1",
285 "event_repeat_on_day" => "0",
286 "event_repeat_on_freq" => "0",
287 "exdate" => ""
289 // Useless garbage that we must save.
290 $locationspecs = array("event_location" => "",
291 "event_street1" => "",
292 "event_street2" => "",
293 "event_city" => "",
294 "event_state" => "",
295 "event_postal" => ""
297 $locationspec = serialize($locationspecs);
298 $args['event_date'] = date('Y-m-d');
299 $args['duration'] = $duration;
300 // this event is forced to NOT REPEAT
301 $args['form_repeat'] = "0";
302 $args['recurrspec'] = $noRecurrspec;
303 $args['form_enddate'] = "0000-00-00";
304 $args['starttime'] = $starttime;
305 $args['endtime'] = $endtime;
306 $args['locationspec'] = $locationspec;
307 $args['form_category']=$origEvent['pc_catid'];
308 $args['new_multiple_value']=$origEvent['pc_multiple'];
309 $args['form_provider']=$origEvent['pc_aid'];
310 $args['form_pid']=$origEvent['pc_pid'];
311 $args['form_title']=$origEvent['pc_title'];
312 $args['form_allday']=$origEvent['pc_alldayevent'];
313 $args['form_apptstatus']='@';
314 $args['form_prefcat']=$origEvent['pc_prefcatid'];
315 $args['facility']=$origEvent['pc_facility'];
316 $args['billing_facility']=$origEvent['pc_billing_location'];
317 InsertEvent($args, 'payment');
319 //===============================================================================
320 // check if event exists
321 function check_event_exist($eid)
323 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
324 $origEvent=sqlFetchArray($origEventRes);
325 $pc_catid=$origEvent['pc_catid'];
326 $pc_aid=$origEvent['pc_aid'];
327 $pc_pid=$origEvent['pc_pid'];
328 $pc_eventDate=date('Y-m-d');
329 $pc_startTime=$origEvent['pc_startTime'];
330 $pc_endTime=$origEvent['pc_endTime'];
331 $pc_facility=$origEvent['pc_facility'];
332 $pc_billing_location=$origEvent['pc_billing_location'];
333 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
334 $origEvent = sqlStatement(
335 "SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
336 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
337 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location)
339 if (sqlNumRows($origEvent)>0) {
340 $origEventRow=sqlFetchArray($origEvent);
341 return $origEventRow['pc_eid'];
342 } else {
343 if (strpos($pc_recurrspec_array['exdate'], date('Ymd')) === false) {//;'20110228'
344 return false;
345 } else {//this happens in delete case
346 return true;
350 //===============================================================================
351 // insert an event
352 // $args is mainly filled with content from the POST http var
353 function InsertEvent($args, $from = 'general')
355 $pc_recurrtype = '0';
356 if ($args['form_repeat'] || $args['days_every_week']) {
357 if ($args['recurrspec']['event_repeat_freq_type'] == "6") {
358 $pc_recurrtype = 3;
359 } else {
360 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
364 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
365 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
366 $form_gid = empty($args['form_gid']) ? '' : $args['form_gid'];
368 if ($from == 'general') {
369 $pc_eid = sqlInsert(
370 "INSERT INTO openemr_postcalendar_events ( " .
371 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_gid, pc_title, pc_time, pc_hometext, " .
372 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
373 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
374 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
375 ") VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
376 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,$form_gid,
377 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
378 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
379 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
380 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
383 //Manage tracker status.
384 if (!empty($form_pid)) {
385 manage_tracker_status($args['event_date'], $args['starttime'], $pc_eid, $form_pid, $_SESSION['authUser'], $args['form_apptstatus'], $args['form_room']);
388 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
390 return $pc_eid;
391 } elseif ($from == 'payment') {
392 sqlStatement(
393 "INSERT INTO openemr_postcalendar_events ( " .
394 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
395 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
396 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
397 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
398 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
399 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
400 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
401 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
404 (int)$args['facility'],
405 (int)$args['billing_facility'])
409 //================================================================================================================
411 * __increment()
412 * returns the next valid date for an event based on the
413 * current day,month,year,freq and type
414 * @private
415 * @returns string YYYY-MM-DD
417 function &__increment($d, $m, $y, $f, $t)
419 if ($t == REPEAT_DAYS_EVERY_WEEK) {
420 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
421 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
422 return $next_appointment_date;
425 if ($t == REPEAT_EVERY_DAY) {
426 $d = $d+$f;
427 } elseif ($t == REPEAT_EVERY_WORK_DAY) {
428 // a workday is defined as Mon,Tue,Wed,Thu,Fri
429 // repeating on every or Nth work day means to not include
430 // weekends (Sat/Sun) in the increment... tricky
432 // ugh, a day-by-day loop seems necessary here, something where
433 // we can check to see if the day is a Sat/Sun and increment
434 // the frequency count so as to ignore the weekend. hmmmm....
435 $orig_freq = $f;
436 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
437 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d+$daycount), $y));
438 if (is_weekend_day($nextWorkDOW)) {
439 $f++;
443 // and finally make sure we haven't landed on a end week days
444 // adjust as necessary
445 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d+$f), $y));
446 if (count($GLOBALS['weekend_days']) === 2) {
447 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
448 $f+=2;
449 } elseif ($nextWorkDOW == $GLOBALS['weekend_days'][1]) {
450 $f++;
452 } elseif (count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
453 $f++;
456 $d = $d+$f;
457 } elseif ($t == REPEAT_EVERY_WEEK) {
458 $d = $d+(7*$f);
459 } elseif ($t == REPEAT_EVERY_MONTH) {
460 $m = $m+$f;
461 } elseif ($t == REPEAT_EVERY_YEAR) {
462 $y = $y+$f;
465 $dtYMD = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
466 return $dtYMD;
469 function getTheNextAppointment($appointment_date, $freq)
471 $day_arr = explode(",", $freq);
472 $date_arr = array();
473 foreach ($day_arr as $day) {
474 $day = getDayName($day);
475 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
476 array_push($date_arr, $date);
479 $next_appointment = getEarliestDate($date_arr);
480 return $next_appointment;
483 function getDayName($day_num)
485 if ($day_num == "1") {
486 return "sunday";
489 if ($day_num == "2") {
490 return "monday";
493 if ($day_num == "3") {
494 return "tuesday";
497 if ($day_num == "4") {
498 return "wednesday";
501 if ($day_num == "5") {
502 return "thursday";
505 if ($day_num == "6") {
506 return "friday";
509 if ($day_num == "7") {
510 return "saturday";
515 function getEarliestDate($date_arr)
517 $earliest = ($date_arr[0]);
518 foreach ($date_arr as $date) {
519 if (strtotime($date) < strtotime($earliest)) {
520 $earliest = $date;
524 return $earliest;
526 //================================================================================================================