Integrate traditional and layout-based forms into their chosen categories in the...
[openemr.git] / library / encounter_events.inc.php
blobeba0994870b85e316e8931784927ddd6c55acadb
1 <?php
3 // +-----------------------------------------------------------------------------+
4 // Copyright (C) 2010 Z&H Consultancy Services Private Limited <sam@zhservices.com>
5 //
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License
9 // as published by the Free Software Foundation; either version 2
10 // of the License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 // GNU General Public License for more details.
19 // A copy of the GNU General Public License is included along with this program:
20 // openemr/interface/login/GnuGPL.html
21 // For more information write to the Free Software
22 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 // Author: Eldho Chacko <eldho@zhservices.com>
25 // Paul Simon K <paul@zhservices.com>
26 // Ian Jardine ( github.com/epsdky ) ( Modified calendar_arrived )
28 // +------------------------------------------------------------------------------+
30 require_once(__DIR__ . '/calendar.inc');
31 require_once(__DIR__ . '/patient_tracker.inc.php');
34 //===============================================================================
35 //This section handles the events of payment screen.
36 //===============================================================================
37 define('REPEAT_EVERY_DAY', 0);
38 define('REPEAT_EVERY_WEEK', 1);
39 define('REPEAT_EVERY_MONTH', 2);
40 define('REPEAT_EVERY_YEAR', 3);
41 define('REPEAT_EVERY_WORK_DAY', 4);
42 define('REPEAT_DAYS_EVERY_WEEK', 6);
43 //===============================================================================
44 $today = date('Y-m-d');
45 //===============================================================================
46 // If unique current date appointment found update status to arrived and create
47 // encounter
49 function calendar_arrived($form_pid)
51 $appts = array();
52 $today = date('Y-m-d');
53 $appts = fetchAppointments($today, $today, $form_pid);
54 $appt_count = count($appts); //
55 if ($appt_count == 0) {
56 echo "<br /><br /><br /><h2 class='text-center'>" . htmlspecialchars(xl('Sorry No Appointment is Fixed'), ENT_QUOTES) . ". " . htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES) . ".</h2>";
57 exit;
58 } elseif ($appt_count == 1) {
59 $enc = todaysEncounterCheck($form_pid);
60 if ($appts[0]['pc_recurrtype'] == 0) {
61 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?", array($appts[0]['pc_eid']));
62 } else {
63 update_event($appts[0]['pc_eid']);
65 } elseif ($appt_count > 1) {
66 echo "<br /><br /><br /><h2 class='text-center'>" . htmlspecialchars(xl('More than one appointment was found'), ENT_QUOTES) . ". " . htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES) . ".</h2>";
67 exit;
69 return $enc;
72 //===============================================================================
73 // Checks for the patient's encounter ID for today, creating it if there is none.
75 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true)
77 global $today;
78 $encounter = todaysEncounterIf($patient_id);
79 if ($encounter && (int)$GLOBALS['auto_create_new_encounters'] !== 2) {
80 if ($return_existing) {
81 return $encounter;
82 } else {
83 return 0;
87 if (is_array($provider)) {
88 $visit_provider = (int)$provider[0];
89 } elseif ($provider) {
90 $visit_provider = (int)$provider;
91 } else {
92 $visit_provider = '(NULL)';
95 $dos = $enc_date ? $enc_date : $today;
96 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
97 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
98 $username = $tmprow['username'];
99 $facility = $tmprow['facility'];
100 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
101 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
102 $pos_code = sqlQuery("SELECT pos_code FROM facility WHERE id = ?", array($facility_id))['pos_code'];
103 $visit_cat = $cat ? $cat : '(NULL)';
104 $conn = $GLOBALS['adodb']['db'];
105 $encounter = $conn->GenID("sequences");
106 addForm(
107 $encounter,
108 "New Patient Encounter",
109 sqlInsert(
110 "INSERT INTO form_encounter SET " .
111 "date = ?, " .
112 "reason = ?, " .
113 "facility = ?, " .
114 "facility_id = ?, " .
115 "billing_facility = ?, " .
116 "provider_id = ?, " .
117 "pid = ?, " .
118 "encounter = ?," .
119 "pc_catid = ?," .
120 "pos_code = ?",
121 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat, $pos_code)
123 "newpatient",
124 $patient_id,
125 "1",
126 "NOW()",
127 $username
129 return $encounter;
132 //===============================================================================
133 // Checks for the group's encounter ID for today, creating it if there is none.
135 function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null)
137 global $today;
138 $encounter = todaysTherapyGroupEncounterIf($group_id);
139 if ($encounter) {
140 if ($return_existing) {
141 return $encounter;
142 } else {
143 return 0;
147 if (is_array($provider)) {
148 $visit_provider = (int)$provider[0];
149 $counselors = implode(',', $provider);
150 } elseif ($provider) {
151 $visit_provider = $counselors = (int)$provider;
152 } else {
153 $visit_provider = $counselors = null;
156 $dos = $enc_date ? $enc_date : $today;
157 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
158 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
159 $username = $tmprow['username'];
160 $facility = $tmprow['facility'];
161 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
162 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
163 $visit_cat = $cat ? $cat : '(NULL)';
164 $conn = $GLOBALS['adodb']['db'];
165 $encounter = $conn->GenID("sequences");
166 addForm(
167 $encounter,
168 "New Therapy Group Encounter",
169 sqlInsert(
170 "INSERT INTO form_groups_encounter SET " .
171 "date = ?, " .
172 "reason = ?, " .
173 "facility = ?, " .
174 "facility_id = ?, " .
175 "billing_facility = ?, " .
176 "provider_id = ?, " .
177 "group_id = ?, " .
178 "encounter = ?," .
179 "pc_catid = ? ," .
180 "appt_id = ? ," .
181 "counselors = ? ",
182 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)
184 "newGroupEncounter",
185 null,
186 "1",
187 "NOW()",
188 $username,
190 $group_id
192 return $encounter;
194 //===============================================================================
195 // Get the patient's encounter ID for today, if it exists.
196 // In the case of more than one encounter today, pick the last one.
198 function todaysEncounterIf($patient_id)
200 global $today;
201 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
202 "pid = ? AND date = ? " .
203 "ORDER BY encounter DESC LIMIT 1", array($patient_id,"$today 00:00:00"));
204 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
206 //===============================================================================
207 // Get the group's encounter ID for today, if it exists.
208 // In the case of more than one encounter today, pick the last one.
210 function todaysTherapyGroupEncounterIf($group_id)
212 global $today;
213 $tmprow = sqlQuery("SELECT encounter FROM form_groups_encounter WHERE " .
214 "group_id = ? AND date = ? " .
215 "ORDER BY encounter DESC LIMIT 1", array($group_id,"$today 00:00:00"));
216 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
218 //===============================================================================
220 // Get the patient's encounter ID for today, creating it if there is none.
222 function todaysEncounter($patient_id, $reason = '')
224 global $today, $userauthorized;
226 if (empty($reason)) {
227 $reason = xl('Please indicate visit reason');
230 // Was going to use the existing encounter for today if there is one, but
231 // decided it's right to always create a new one. Leaving the code here
232 // (and corresponding function above) in case it is ever wanted later.
233 /*******************************************************************
234 $encounter = todaysEncounterIf($patient_id);
235 if ($encounter) return $encounter;
236 *******************************************************************/
238 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
239 "WHERE id = ?", array($_SESSION["authUserID"]));
240 $username = $tmprow['username'];
241 $facility = $tmprow['facility'];
242 $facility_id = $tmprow['facility_id'];
243 $conn = $GLOBALS['adodb']['db'];
244 $encounter = $conn->GenID("sequences");
245 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
246 addForm(
247 $encounter,
248 "New Patient Encounter",
249 sqlInsert(
250 "INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
251 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
252 "provider_id = ?",
253 array($today, $today, $reason, $facility, $facility_id, $patient_id,
254 $encounter, $provider_id)
256 "newpatient",
257 $patient_id,
258 $userauthorized,
259 "NOW()",
260 $username
262 return $encounter;
264 //===============================================================================
265 // get the original event's repeat specs
266 function update_event($eid)
268 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
269 $origEvent = sqlFetchArray($origEventRes);
270 $oldRecurrspec = unserialize($origEvent['pc_recurrspec'], ['allowed_classes' => false]);
271 $duration = $origEvent['pc_duration'];
272 $starttime = $origEvent['pc_startTime'];
273 $endtime = $origEvent['pc_endTime'];
274 $selected_date = date("Ymd");
275 if ($oldRecurrspec['exdate'] != "") {
276 $oldRecurrspec['exdate'] .= "," . $selected_date;
277 } else {
278 $oldRecurrspec['exdate'] .= $selected_date;
281 // mod original event recur specs to exclude this date
282 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?", array(serialize($oldRecurrspec),$eid));
283 // specify some special variables needed for the INSERT
284 // no recurr specs, this is used for adding a new non-recurring event
285 $noRecurrspec = array("event_repeat_freq" => "",
286 "event_repeat_freq_type" => "",
287 "event_repeat_on_num" => "1",
288 "event_repeat_on_day" => "0",
289 "event_repeat_on_freq" => "0",
290 "exdate" => ""
292 // Useless garbage that we must save.
293 $locationspecs = array("event_location" => "",
294 "event_street1" => "",
295 "event_street2" => "",
296 "event_city" => "",
297 "event_state" => "",
298 "event_postal" => ""
300 $locationspec = serialize($locationspecs);
301 $args['event_date'] = date('Y-m-d');
302 $args['duration'] = $duration;
303 // this event is forced to NOT REPEAT
304 $args['form_repeat'] = "0";
305 $args['recurrspec'] = $noRecurrspec;
306 $args['form_enddate'] = "0000-00-00";
307 $args['starttime'] = $starttime;
308 $args['endtime'] = $endtime;
309 $args['locationspec'] = $locationspec;
310 $args['form_category'] = $origEvent['pc_catid'];
311 $args['new_multiple_value'] = $origEvent['pc_multiple'];
312 $args['form_provider'] = $origEvent['pc_aid'];
313 $args['form_pid'] = $origEvent['pc_pid'];
314 $args['form_title'] = $origEvent['pc_title'];
315 $args['form_allday'] = $origEvent['pc_alldayevent'];
316 $args['form_apptstatus'] = '@';
317 $args['form_prefcat'] = $origEvent['pc_prefcatid'];
318 $args['facility'] = $origEvent['pc_facility'];
319 $args['billing_facility'] = $origEvent['pc_billing_location'];
320 InsertEvent($args, 'payment');
322 //===============================================================================
323 // check if event exists
324 function check_event_exist($eid)
326 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
327 $origEvent = sqlFetchArray($origEventRes);
328 $pc_catid = $origEvent['pc_catid'];
329 $pc_aid = $origEvent['pc_aid'];
330 $pc_pid = $origEvent['pc_pid'];
331 $pc_eventDate = date('Y-m-d');
332 $pc_startTime = $origEvent['pc_startTime'];
333 $pc_endTime = $origEvent['pc_endTime'];
334 $pc_facility = $origEvent['pc_facility'];
335 $pc_billing_location = $origEvent['pc_billing_location'];
336 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec'], ['allowed_classes' => false]);
337 $origEvent = sqlStatement(
338 "SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? " .
339 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
340 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location)
342 if (sqlNumRows($origEvent) > 0) {
343 $origEventRow = sqlFetchArray($origEvent);
344 return $origEventRow['pc_eid'];
345 } else {
346 if (strpos($pc_recurrspec_array['exdate'], date('Ymd')) === false) {//;'20110228'
347 return false;
348 } else {//this happens in delete case
349 return true;
353 //===============================================================================
354 // insert an event
355 // $args is mainly filled with content from the POST http var
356 function InsertEvent($args, $from = 'general')
358 $pc_recurrtype = '0';
359 if (!empty($args['form_repeat']) || !empty($args['days_every_week'])) {
360 if ($args['recurrspec']['event_repeat_freq_type'] == "6") {
361 $pc_recurrtype = 3;
362 } else {
363 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
367 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
368 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
369 $form_gid = empty($args['form_gid']) ? '' : $args['form_gid'];
371 if ($from == 'general') {
372 $pc_eid = sqlInsert(
373 "INSERT INTO openemr_postcalendar_events ( " .
374 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_gid, pc_title, pc_time, pc_hometext, " .
375 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
376 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
377 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
378 ") VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
379 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,$form_gid,
380 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
381 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
382 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
383 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
386 //Manage tracker status.
387 if (!empty($form_pid)) {
388 manage_tracker_status($args['event_date'], $args['starttime'], $pc_eid, $form_pid, $_SESSION['authUser'], $args['form_apptstatus'], $args['form_room']);
391 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
393 return $pc_eid;
394 } elseif ($from == 'payment') {
395 sqlStatement(
396 "INSERT INTO openemr_postcalendar_events ( " .
397 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
398 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
399 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
400 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
401 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
402 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
403 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
404 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
407 (int)$args['facility'],
408 (int)$args['billing_facility'])
412 //================================================================================================================
414 * __increment()
415 * returns the next valid date for an event based on the
416 * current day,month,year,freq and type
417 * @private
418 * @returns string YYYY-MM-DD
420 function &__increment($d, $m, $y, $f, $t)
422 if ($t == REPEAT_DAYS_EVERY_WEEK) {
423 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
424 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
425 return $next_appointment_date;
428 if ($t == REPEAT_EVERY_DAY) {
429 $d = $d + $f;
430 } elseif ($t == REPEAT_EVERY_WORK_DAY) {
431 // a workday is defined as Mon,Tue,Wed,Thu,Fri
432 // repeating on every or Nth work day means to not include
433 // weekends (Sat/Sun) in the increment... tricky
435 // ugh, a day-by-day loop seems necessary here, something where
436 // we can check to see if the day is a Sat/Sun and increment
437 // the frequency count so as to ignore the weekend. hmmmm....
438 $orig_freq = $f;
439 for ($daycount = 1; $daycount <= $orig_freq; $daycount++) {
440 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d + $daycount), $y));
441 if (is_weekend_day($nextWorkDOW)) {
442 $f++;
446 // and finally make sure we haven't landed on a end week days
447 // adjust as necessary
448 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d + $f), $y));
449 if (count($GLOBALS['weekend_days']) === 2) {
450 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
451 $f += 2;
452 } elseif ($nextWorkDOW == $GLOBALS['weekend_days'][1]) {
453 $f++;
455 } elseif (count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
456 $f++;
459 $d = $d + $f;
460 } elseif ($t == REPEAT_EVERY_WEEK) {
461 $d = $d + (7 * $f);
462 } elseif ($t == REPEAT_EVERY_MONTH) {
463 $m = $m + $f;
464 } elseif ($t == REPEAT_EVERY_YEAR) {
465 $y = $y + $f;
468 $dtYMD = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
469 return $dtYMD;
472 function getTheNextAppointment($appointment_date, $freq)
474 $day_arr = explode(",", $freq);
475 $date_arr = array();
476 foreach ($day_arr as $day) {
477 $day = getDayName($day);
478 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
479 array_push($date_arr, $date);
482 $next_appointment = getEarliestDate($date_arr);
483 return $next_appointment;
486 function getDayName($day_num)
488 if ($day_num == "1") {
489 return "sunday";
492 if ($day_num == "2") {
493 return "monday";
496 if ($day_num == "3") {
497 return "tuesday";
500 if ($day_num == "4") {
501 return "wednesday";
504 if ($day_num == "5") {
505 return "thursday";
508 if ($day_num == "6") {
509 return "friday";
512 if ($day_num == "7") {
513 return "saturday";
518 function getEarliestDate($date_arr)
520 $earliest = ($date_arr[0]);
521 foreach ($date_arr as $date) {
522 if (strtotime($date) < strtotime($earliest)) {
523 $earliest = $date;
527 return $earliest;
529 //================================================================================================================