fix: Update patient_tracker.php (#6595)
[openemr.git] / library / encounter_events.inc.php
blob91a63090a0af683b54c6334da57d31e8aaf4abf2
1 <?php
3 /**
4 * Holds library functions used by events
5 * @package OpenEMR
6 * @link https://www.open-emr.org
7 * @author Z&H Consultancy Services Private Limited <sam@zhservices.com>
8 * @author Eldho Chacko <eldho@zhservices.com>
9 * @author Paul Simon K <paul@zhservices.com>
10 * @author Ian Jardine ( github.com/epsdky ) ( Modified calendar_arrived )
11 * @copyright Copyright (c) 2010 Z&H Consultancy Services Private Limited <sam@zhservices.com>
12 * @license https://github.com/openemr/openemr/blob/master/LICENSE GNU General Public License 3
15 require_once(__DIR__ . '/calendar.inc.php');
16 require_once(__DIR__ . '/patient_tracker.inc.php');
18 //===============================================================================
19 //This section handles the events of payment screen.
20 //===============================================================================
21 define('REPEAT_EVERY_DAY', 0);
22 define('REPEAT_EVERY_WEEK', 1);
23 define('REPEAT_EVERY_MONTH', 2);
24 define('REPEAT_EVERY_YEAR', 3);
25 define('REPEAT_EVERY_WORK_DAY', 4);
26 define('REPEAT_DAYS_EVERY_WEEK', 6);
27 //===============================================================================
28 $today = date('Y-m-d');
29 //===============================================================================
30 // If unique current date appointment found update status to arrived and create
31 // encounter
33 function calendar_arrived($form_pid)
35 $appts = array();
36 $today = date('Y-m-d');
37 $appts = fetchAppointments($today, $today, $form_pid);
38 $appt_count = count($appts); //
39 if ($appt_count == 0) {
40 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>";
41 exit;
42 } elseif ($appt_count == 1) {
43 $enc = todaysEncounterCheck($form_pid);
44 if ($appts[0]['pc_recurrtype'] == 0) {
45 sqlStatement("UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?", array($appts[0]['pc_eid']));
46 } else {
47 update_event($appts[0]['pc_eid']);
49 } elseif ($appt_count > 1) {
50 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>";
51 exit;
53 return $enc;
56 //===============================================================================
57 // Checks for the patient's encounter ID for today, creating it if there is none.
59 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true)
61 global $today;
62 $encounter = todaysEncounterIf($patient_id);
63 if ($encounter && (int)$GLOBALS['auto_create_new_encounters'] !== 2) {
64 if ($return_existing) {
65 return $encounter;
66 } else {
67 return 0;
71 if (is_array($provider)) {
72 $visit_provider = (int)$provider[0];
73 } elseif ($provider) {
74 $visit_provider = (int)$provider;
75 } else {
76 $visit_provider = '(NULL)';
79 $dos = $enc_date ? $enc_date : $today;
80 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
81 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
82 $username = $tmprow['username'];
83 $facility = $tmprow['facility'];
84 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
85 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
86 $pos_code = sqlQuery("SELECT pos_code FROM facility WHERE id = ?", array($facility_id))['pos_code'];
87 $visit_cat = $cat ? $cat : '(NULL)';
88 $conn = $GLOBALS['adodb']['db'];
89 $encounter = $conn->GenID("sequences");
90 addForm(
91 $encounter,
92 "New Patient Encounter",
93 sqlInsert(
94 "INSERT INTO form_encounter SET " .
95 "date = ?, " .
96 "reason = ?, " .
97 "facility = ?, " .
98 "facility_id = ?, " .
99 "billing_facility = ?, " .
100 "provider_id = ?, " .
101 "pid = ?, " .
102 "encounter = ?," .
103 "pc_catid = ?," .
104 "pos_code = ?",
105 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat, $pos_code)
107 "newpatient",
108 $patient_id,
109 "1",
110 "NOW()",
111 $username
113 return $encounter;
116 //===============================================================================
117 // Checks for the group's encounter ID for today, creating it if there is none.
119 function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null)
121 global $today;
122 $encounter = todaysTherapyGroupEncounterIf($group_id);
123 if ($encounter) {
124 if ($return_existing) {
125 return $encounter;
126 } else {
127 return 0;
131 if (is_array($provider)) {
132 $visit_provider = (int)$provider[0];
133 $counselors = implode(',', $provider);
134 } elseif ($provider) {
135 $visit_provider = $counselors = (int)$provider;
136 } else {
137 $visit_provider = $counselors = null;
140 $dos = $enc_date ? $enc_date : $today;
141 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
142 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
143 $username = $tmprow['username'];
144 $facility = $tmprow['facility'];
145 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
146 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
147 $visit_cat = $cat ? $cat : '(NULL)';
148 $conn = $GLOBALS['adodb']['db'];
149 $encounter = $conn->GenID("sequences");
150 addForm(
151 $encounter,
152 "New Therapy Group Encounter",
153 sqlInsert(
154 "INSERT INTO form_groups_encounter SET " .
155 "date = ?, " .
156 "reason = ?, " .
157 "facility = ?, " .
158 "facility_id = ?, " .
159 "billing_facility = ?, " .
160 "provider_id = ?, " .
161 "group_id = ?, " .
162 "encounter = ?," .
163 "pc_catid = ? ," .
164 "appt_id = ? ," .
165 "counselors = ? ",
166 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)
168 "newGroupEncounter",
169 null,
170 "1",
171 "NOW()",
172 $username,
174 $group_id
176 return $encounter;
178 //===============================================================================
179 // Get the patient's encounter ID for today, if it exists.
180 // In the case of more than one encounter today, pick the last one.
182 function todaysEncounterIf($patient_id)
184 global $today;
185 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
186 "pid = ? AND date = ? " .
187 "ORDER BY encounter DESC LIMIT 1", array($patient_id,"$today 00:00:00"));
188 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
190 //===============================================================================
191 // Get the group's encounter ID for today, if it exists.
192 // In the case of more than one encounter today, pick the last one.
194 function todaysTherapyGroupEncounterIf($group_id)
196 global $today;
197 $tmprow = sqlQuery("SELECT encounter FROM form_groups_encounter WHERE " .
198 "group_id = ? AND date = ? " .
199 "ORDER BY encounter DESC LIMIT 1", array($group_id,"$today 00:00:00"));
200 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
202 //===============================================================================
204 // Get the patient's encounter ID for today, creating it if there is none.
206 function todaysEncounter($patient_id, $reason = '')
208 global $today, $userauthorized;
210 if (empty($reason)) {
211 $reason = xl('Please indicate visit reason');
214 // Was going to use the existing encounter for today if there is one, but
215 // decided it's right to always create a new one. Leaving the code here
216 // (and corresponding function above) in case it is ever wanted later.
217 /*******************************************************************
218 $encounter = todaysEncounterIf($patient_id);
219 if ($encounter) return $encounter;
220 *******************************************************************/
222 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
223 "WHERE id = ?", array($_SESSION["authUserID"]));
224 $username = $tmprow['username'];
225 $facility = $tmprow['facility'];
226 $facility_id = $tmprow['facility_id'];
227 $conn = $GLOBALS['adodb']['db'];
228 $encounter = $conn->GenID("sequences");
229 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
230 addForm(
231 $encounter,
232 "New Patient Encounter",
233 sqlInsert(
234 "INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
235 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
236 "provider_id = ?",
237 array($today, $today, $reason, $facility, $facility_id, $patient_id,
238 $encounter, $provider_id)
240 "newpatient",
241 $patient_id,
242 $userauthorized,
243 "NOW()",
244 $username
246 return $encounter;
248 //===============================================================================
249 // get the original event's repeat specs
250 function update_event($eid)
252 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
253 $origEvent = sqlFetchArray($origEventRes);
254 $oldRecurrspec = unserialize($origEvent['pc_recurrspec'], ['allowed_classes' => false]);
255 $duration = $origEvent['pc_duration'];
256 $starttime = $origEvent['pc_startTime'];
257 $endtime = $origEvent['pc_endTime'];
258 $selected_date = date("Ymd");
259 if ($oldRecurrspec['exdate'] != "") {
260 $oldRecurrspec['exdate'] .= "," . $selected_date;
261 } else {
262 $oldRecurrspec['exdate'] .= $selected_date;
265 // mod original event recur specs to exclude this date
266 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?", array(serialize($oldRecurrspec),$eid));
267 // specify some special variables needed for the INSERT
268 // no recurr specs, this is used for adding a new non-recurring event
269 $noRecurrspec = array("event_repeat_freq" => "",
270 "event_repeat_freq_type" => "",
271 "event_repeat_on_num" => "1",
272 "event_repeat_on_day" => "0",
273 "event_repeat_on_freq" => "0",
274 "exdate" => ""
276 // Useless garbage that we must save.
277 $locationspecs = array("event_location" => "",
278 "event_street1" => "",
279 "event_street2" => "",
280 "event_city" => "",
281 "event_state" => "",
282 "event_postal" => ""
284 $locationspec = serialize($locationspecs);
285 $args['event_date'] = date('Y-m-d');
286 $args['duration'] = $duration;
287 // this event is forced to NOT REPEAT
288 $args['form_repeat'] = "0";
289 $args['recurrspec'] = $noRecurrspec;
290 $args['form_enddate'] = "0000-00-00";
291 $args['starttime'] = $starttime;
292 $args['endtime'] = $endtime;
293 $args['locationspec'] = $locationspec;
294 $args['form_category'] = $origEvent['pc_catid'];
295 $args['new_multiple_value'] = $origEvent['pc_multiple'];
296 $args['form_provider'] = $origEvent['pc_aid'];
297 $args['form_pid'] = $origEvent['pc_pid'];
298 $args['form_title'] = $origEvent['pc_title'];
299 $args['form_allday'] = $origEvent['pc_alldayevent'];
300 $args['form_apptstatus'] = '@';
301 $args['form_prefcat'] = $origEvent['pc_prefcatid'];
302 $args['facility'] = $origEvent['pc_facility'];
303 $args['billing_facility'] = $origEvent['pc_billing_location'];
304 InsertEvent($args, 'payment');
306 //===============================================================================
307 // check if event exists
308 function check_event_exist($eid)
310 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
311 $origEvent = sqlFetchArray($origEventRes);
312 $pc_catid = $origEvent['pc_catid'];
313 $pc_aid = $origEvent['pc_aid'];
314 $pc_pid = $origEvent['pc_pid'];
315 $pc_eventDate = date('Y-m-d');
316 $pc_startTime = $origEvent['pc_startTime'];
317 $pc_endTime = $origEvent['pc_endTime'];
318 $pc_facility = $origEvent['pc_facility'];
319 $pc_billing_location = $origEvent['pc_billing_location'];
320 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec'], ['allowed_classes' => false]);
321 $origEvent = sqlStatement(
322 "SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? " .
323 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
324 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location)
326 if (sqlNumRows($origEvent) > 0) {
327 $origEventRow = sqlFetchArray($origEvent);
328 return $origEventRow['pc_eid'];
329 } else {
330 if (strpos($pc_recurrspec_array['exdate'], date('Ymd')) === false) {//;'20110228'
331 return false;
332 } else {//this happens in delete case
333 return true;
337 //===============================================================================
338 // insert an event
339 // $args is mainly filled with content from the POST http var
340 function InsertEvent($args, $from = 'general')
342 $pc_recurrtype = '0';
343 if (!empty($args['form_repeat']) || !empty($args['days_every_week'])) {
344 if ($args['recurrspec']['event_repeat_freq_type'] == "6") {
345 $pc_recurrtype = 3;
346 } else {
347 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
351 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
352 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
353 $form_gid = empty($args['form_gid']) ? '' : $args['form_gid'];
355 if ($from == 'general') {
356 $pc_eid = sqlInsert(
357 "INSERT INTO openemr_postcalendar_events ( " .
358 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_gid, pc_title, pc_time, pc_hometext, " .
359 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
360 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
361 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
362 ") VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
363 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,$form_gid,
364 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
365 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
366 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
367 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
370 //Manage tracker status.
371 if (!empty($form_pid)) {
372 manage_tracker_status($args['event_date'], $args['starttime'], $pc_eid, $form_pid, $_SESSION['authUser'], $args['form_apptstatus'], $args['form_room']);
375 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
377 return $pc_eid;
378 } elseif ($from == 'payment') {
379 sqlStatement(
380 "INSERT INTO openemr_postcalendar_events ( " .
381 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
382 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
383 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
384 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
385 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
386 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
387 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
388 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
391 (int)$args['facility'],
392 (int)$args['billing_facility'])
396 //================================================================================================================
398 * __increment()
399 * returns the next valid date for an event based on the
400 * current day,month,year,freq and type
401 * @private
402 * @returns string YYYY-MM-DD
404 function &__increment($d, $m, $y, $f, $t)
406 if ($t == REPEAT_DAYS_EVERY_WEEK) {
407 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
408 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
409 return $next_appointment_date;
412 if ($t == REPEAT_EVERY_DAY) {
413 $d = $d + $f;
414 } elseif ($t == REPEAT_EVERY_WORK_DAY) {
415 // a workday is defined as Mon,Tue,Wed,Thu,Fri
416 // repeating on every or Nth work day means to not include
417 // weekends (Sat/Sun) in the increment... tricky
419 // ugh, a day-by-day loop seems necessary here, something where
420 // we can check to see if the day is a Sat/Sun and increment
421 // the frequency count so as to ignore the weekend. hmmmm....
422 $orig_freq = $f;
423 for ($daycount = 1; $daycount <= $orig_freq; $daycount++) {
424 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d + $daycount), $y));
425 if (is_weekend_day($nextWorkDOW)) {
426 $f++;
430 // and finally make sure we haven't landed on a end week days
431 // adjust as necessary
432 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d + $f), $y));
433 if (count($GLOBALS['weekend_days']) === 2) {
434 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
435 $f += 2;
436 } elseif ($nextWorkDOW == $GLOBALS['weekend_days'][1]) {
437 $f++;
439 } elseif (count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
440 $f++;
443 $d = $d + $f;
444 } elseif ($t == REPEAT_EVERY_WEEK) {
445 $d = $d + (7 * $f);
446 } elseif ($t == REPEAT_EVERY_MONTH) {
447 $m = $m + $f;
448 } elseif ($t == REPEAT_EVERY_YEAR) {
449 $y = $y + $f;
452 $dtYMD = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
453 return $dtYMD;
456 function getTheNextAppointment($appointment_date, $freq)
458 $day_arr = explode(",", $freq);
459 $date_arr = array();
460 foreach ($day_arr as $day) {
461 $day = getDayName($day);
462 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
463 array_push($date_arr, $date);
466 $next_appointment = getEarliestDate($date_arr);
467 return $next_appointment;
470 function getDayName($day_num)
472 if ($day_num == "1") {
473 return "sunday";
476 if ($day_num == "2") {
477 return "monday";
480 if ($day_num == "3") {
481 return "tuesday";
484 if ($day_num == "4") {
485 return "wednesday";
488 if ($day_num == "5") {
489 return "thursday";
492 if ($day_num == "6") {
493 return "friday";
496 if ($day_num == "7") {
497 return "saturday";
502 function getEarliestDate($date_arr)
504 $earliest = ($date_arr[0]);
505 foreach ($date_arr as $date) {
506 if (strtotime($date) < strtotime($earliest)) {
507 $earliest = $date;
511 return $earliest;
513 //================================================================================================================