POS default selection for encounter (#1088)
[openemr.git] / library / encounter_events.inc.php
blob0a8e781a9b9a7b194fc901c3befba91d3d4fc0f2
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 define('REPEAT_DAYS_EVERY_WEEK', 6);
41 //===============================================================================
42 //Create event in calender as arrived
43 function calendar_arrived($form_pid)
45 $Today=date('Y-m-d');
46 //Take all recurring events relevent for today.
47 $result_event=sqlStatement(
48 "SELECT * FROM openemr_postcalendar_events WHERE pc_recurrtype != '0' and pc_pid = ? and pc_endDate != '0000-00-00'
49 and pc_eventDate < ? and pc_endDate >= ? ",
50 array($form_pid,$Today,$Today)
52 if (sqlNumRows($result_event)==0) {//no repeating appointment
53 $result_event=sqlStatement(
54 "SELECT * FROM openemr_postcalendar_events WHERE pc_pid =? and pc_eventDate = ?",
55 array($form_pid,$Today)
57 if (sqlNumRows($result_event)==0) {//no appointment
58 echo "<br><br><br>".htmlspecialchars(xl('Sorry No Appointment is Fixed'), ENT_QUOTES).". ".htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES).".";
59 die;
60 } else //one appointment
62 $enc = todaysEncounterCheck($form_pid);//create encounter
63 $zero_enc=0;
64 sqlStatement(
65 "UPDATE openemr_postcalendar_events SET pc_apptstatus ='@' WHERE pc_pid =? and pc_eventDate = ?",
66 array($form_pid,$Today)
69 } else //repeating appointment set
71 while ($row_event=sqlFetchArray($result_event)) {
72 $pc_eid = $row_event['pc_eid'];
73 $pc_eventDate = $row_event['pc_eventDate'];
74 $pc_recurrspec_array = unserialize($row_event['pc_recurrspec']);
75 while (1) {
76 if ($pc_eventDate==$Today) {//Matches so insert.
77 if (!$exist_eid=check_event_exist($pc_eid)) {
78 update_event($pc_eid);
79 } else {
80 sqlStatement(
81 "UPDATE openemr_postcalendar_events SET pc_apptstatus = '@' WHERE pc_eid = ?",
82 array($exist_eid)
86 $enc = todaysEncounterCheck($form_pid);//create encounter
87 $zero_enc=0;
88 break;
89 } elseif ($pc_eventDate>$Today) {//the frequency does not match today,no need to increment furthur.
90 echo "<br><br><br>".htmlspecialchars(xl('Sorry No Appointment is Fixed'), ENT_QUOTES).". ".htmlspecialchars(xl('No Encounter could be created'), ENT_QUOTES).".";
91 die;
92 break;
95 // Added by Rod to handle repeats on nth or last given weekday of a month:
96 if ($row_event['pc_recurrtype'] == 2) {
97 $my_repeat_on_day = $pc_recurrspec_array['event_repeat_on_day'];
98 $my_repeat_on_num = $pc_recurrspec_array['event_repeat_on_num'];
99 $adate = getdate(strtotime($pc_eventDate));
100 $adate['mon'] += 1;
101 if ($adate['mon'] > 12) {
102 $adate['year'] += 1;
103 $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) {
110 $dow -= 7;
113 $adate['mday'] += ($my_repeat_on_num - 1) * 7 + $my_repeat_on_day - $dow;
114 } else { // last weekday of month
115 $adate['mday'] = cal_days_in_month(CAL_GREGORIAN, $adate['mon'], $adate['year']);
116 $dow = jddayofweek(cal_to_jd(CAL_GREGORIAN, $adate['mon'], $adate['mday'], $adate['year']));
117 if ($dow < $my_repeat_on_day) {
118 $dow += 7;
121 $adate['mday'] += $my_repeat_on_day - $dow;
124 $pc_eventDate = date('Y-m-d', mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']));
125 } // end recurrtype 2
127 else { // pc_recurrtype is 1
128 $pc_eventDate_array = explode('-', $pc_eventDate);
129 // Find the next day as per the frequency definition.
130 $pc_eventDate =& __increment(
131 $pc_eventDate_array[2],
132 $pc_eventDate_array[1],
133 $pc_eventDate_array[0],
134 $pc_recurrspec_array['event_repeat_freq'],
135 $pc_recurrspec_array['event_repeat_freq_type']
142 return $enc;
144 //===============================================================================
145 // Checks for the patient's encounter ID for today, creating it if there is none.
147 function todaysEncounterCheck($patient_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true)
149 global $today;
150 $encounter = todaysEncounterIf($patient_id);
151 if ($encounter) {
152 if ($return_existing) {
153 return $encounter;
154 } else {
155 return 0;
159 if (is_array($provider)) {
160 $visit_provider = (int)$provider[0];
161 } elseif ($provider) {
162 $visit_provider = (int)$provider;
163 } else {
164 $visit_provider = '(NULL)';
167 $dos = $enc_date ? $enc_date : $today;
168 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
169 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
170 $username = $tmprow['username'];
171 $facility = $tmprow['facility'];
172 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
173 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
174 $visit_cat = $cat ? $cat : '(NULL)';
175 $conn = $GLOBALS['adodb']['db'];
176 $encounter = $conn->GenID("sequences");
177 addForm(
178 $encounter,
179 "New Patient Encounter",
180 sqlInsert(
181 "INSERT INTO form_encounter SET " .
182 "date = ?, " .
183 "reason = ?, " .
184 "facility = ?, " .
185 "facility_id = ?, " .
186 "billing_facility = ?, " .
187 "provider_id = ?, " .
188 "pid = ?, " .
189 "encounter = ?," .
190 "pc_catid = ?",
191 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$patient_id,$encounter,$visit_cat)
193 "newpatient",
194 $patient_id,
195 "1",
196 "NOW()",
197 $username
199 return $encounter;
202 //===============================================================================
203 // Checks for the group's encounter ID for today, creating it if there is none.
205 function todaysTherapyGroupEncounterCheck($group_id, $enc_date = '', $reason = '', $fac_id = '', $billing_fac = '', $provider = '', $cat = '', $return_existing = true, $eid = null)
207 global $today;
208 $encounter = todaysTherapyGroupEncounterIf($group_id);
209 if ($encounter) {
210 if ($return_existing) {
211 return $encounter;
212 } else {
213 return 0;
217 if (is_array($provider)) {
218 $visit_provider = (int)$provider[0];
219 $counselors = implode(',', $provider);
220 } elseif ($provider) {
221 $visit_provider = $counselors = (int)$provider;
222 } else {
223 $visit_provider = $counselors = null;
226 $dos = $enc_date ? $enc_date : $today;
227 $visit_reason = $reason ? $reason : xl('Please indicate visit reason');
228 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users WHERE id = ?", array($_SESSION["authUserID"]));
229 $username = $tmprow['username'];
230 $facility = $tmprow['facility'];
231 $facility_id = $fac_id ? (int)$fac_id : $tmprow['facility_id'];
232 $billing_facility = $billing_fac ? (int)$billing_fac : $tmprow['facility_id'];
233 $visit_cat = $cat ? $cat : '(NULL)';
234 $conn = $GLOBALS['adodb']['db'];
235 $encounter = $conn->GenID("sequences");
236 addForm(
237 $encounter,
238 "New Therapy Group Encounter",
239 sqlInsert(
240 "INSERT INTO form_groups_encounter SET " .
241 "date = ?, " .
242 "reason = ?, " .
243 "facility = ?, " .
244 "facility_id = ?, " .
245 "billing_facility = ?, " .
246 "provider_id = ?, " .
247 "group_id = ?, " .
248 "encounter = ?," .
249 "pc_catid = ? ," .
250 "appt_id = ? ," .
251 "counselors = ? ",
252 array($dos,$visit_reason,$facility,$facility_id,$billing_facility,$visit_provider,$group_id,$encounter,$visit_cat, $eid, $counselors)
254 "newGroupEncounter",
255 null,
256 "1",
257 "NOW()",
258 $username,
260 $group_id
262 return $encounter;
264 //===============================================================================
265 // Get the patient's encounter ID for today, if it exists.
266 // In the case of more than one encounter today, pick the last one.
268 function todaysEncounterIf($patient_id)
270 global $today;
271 $tmprow = sqlQuery("SELECT encounter FROM form_encounter WHERE " .
272 "pid = ? AND date = ? " .
273 "ORDER BY encounter DESC LIMIT 1", array($patient_id,"$today 00:00:00"));
274 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
276 //===============================================================================
277 // Get the group's encounter ID for today, if it exists.
278 // In the case of more than one encounter today, pick the last one.
280 function todaysTherapyGroupEncounterIf($group_id)
282 global $today;
283 $tmprow = sqlQuery("SELECT encounter FROM form_groups_encounter WHERE " .
284 "group_id = ? AND date = ? " .
285 "ORDER BY encounter DESC LIMIT 1", array($group_id,"$today 00:00:00"));
286 return empty($tmprow['encounter']) ? 0 : $tmprow['encounter'];
288 //===============================================================================
290 // Get the patient's encounter ID for today, creating it if there is none.
292 function todaysEncounter($patient_id, $reason = '')
294 global $today, $userauthorized;
296 if (empty($reason)) {
297 $reason = xl('Please indicate visit reason');
300 // Was going to use the existing encounter for today if there is one, but
301 // decided it's right to always create a new one. Leaving the code here
302 // (and corresponding function above) in case it is ever wanted later.
303 /*******************************************************************
304 $encounter = todaysEncounterIf($patient_id);
305 if ($encounter) return $encounter;
306 *******************************************************************/
308 $tmprow = sqlQuery("SELECT username, facility, facility_id FROM users " .
309 "WHERE id = ?", array($_SESSION["authUserID"]));
310 $username = $tmprow['username'];
311 $facility = $tmprow['facility'];
312 $facility_id = $tmprow['facility_id'];
313 $conn = $GLOBALS['adodb']['db'];
314 $encounter = $conn->GenID("sequences");
315 $provider_id = $userauthorized ? $_SESSION['authUserID'] : 0;
316 addForm(
317 $encounter,
318 "New Patient Encounter",
319 sqlInsert(
320 "INSERT INTO form_encounter SET date = ?, onset_date = ?, " .
321 "reason = ?, facility = ?, facility_id = ?, pid = ?, encounter = ?, " .
322 "provider_id = ?",
323 array($today, $today, $reason, $facility, $facility_id, $patient_id,
324 $encounter, $provider_id)
326 "newpatient",
327 $patient_id,
328 $userauthorized,
329 "NOW()",
330 $username
332 return $encounter;
334 //===============================================================================
335 // get the original event's repeat specs
336 function update_event($eid)
338 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
339 $origEvent=sqlFetchArray($origEventRes);
340 $oldRecurrspec = unserialize($origEvent['pc_recurrspec']);
341 $duration=$origEvent['pc_duration'];
342 $starttime=$origEvent['pc_startTime'];
343 $endtime=$origEvent['pc_endTime'];
344 $selected_date = date("Ymd");
345 if ($oldRecurrspec['exdate'] != "") {
346 $oldRecurrspec['exdate'] .= ",".$selected_date;
347 } else {
348 $oldRecurrspec['exdate'] .= $selected_date;
351 // mod original event recur specs to exclude this date
352 sqlStatement("UPDATE openemr_postcalendar_events SET pc_recurrspec = ? WHERE pc_eid = ?", array(serialize($oldRecurrspec),$eid));
353 // specify some special variables needed for the INSERT
354 // no recurr specs, this is used for adding a new non-recurring event
355 $noRecurrspec = array("event_repeat_freq" => "",
356 "event_repeat_freq_type" => "",
357 "event_repeat_on_num" => "1",
358 "event_repeat_on_day" => "0",
359 "event_repeat_on_freq" => "0",
360 "exdate" => ""
362 // Useless garbage that we must save.
363 $locationspecs = array("event_location" => "",
364 "event_street1" => "",
365 "event_street2" => "",
366 "event_city" => "",
367 "event_state" => "",
368 "event_postal" => ""
370 $locationspec = serialize($locationspecs);
371 $args['event_date'] = date('Y-m-d');
372 $args['duration'] = $duration;
373 // this event is forced to NOT REPEAT
374 $args['form_repeat'] = "0";
375 $args['recurrspec'] = $noRecurrspec;
376 $args['form_enddate'] = "0000-00-00";
377 $args['starttime'] = $starttime;
378 $args['endtime'] = $endtime;
379 $args['locationspec'] = $locationspec;
380 $args['form_category']=$origEvent['pc_catid'];
381 $args['new_multiple_value']=$origEvent['pc_multiple'];
382 $args['form_provider']=$origEvent['pc_aid'];
383 $args['form_pid']=$origEvent['pc_pid'];
384 $args['form_title']=$origEvent['pc_title'];
385 $args['form_allday']=$origEvent['pc_alldayevent'];
386 $args['form_apptstatus']='@';
387 $args['form_prefcat']=$origEvent['pc_prefcatid'];
388 $args['facility']=$origEvent['pc_facility'];
389 $args['billing_facility']=$origEvent['pc_billing_location'];
390 InsertEvent($args, 'payment');
392 //===============================================================================
393 // check if event exists
394 function check_event_exist($eid)
396 $origEventRes = sqlStatement("SELECT * FROM openemr_postcalendar_events WHERE pc_eid = ?", array($eid));
397 $origEvent=sqlFetchArray($origEventRes);
398 $pc_catid=$origEvent['pc_catid'];
399 $pc_aid=$origEvent['pc_aid'];
400 $pc_pid=$origEvent['pc_pid'];
401 $pc_eventDate=date('Y-m-d');
402 $pc_startTime=$origEvent['pc_startTime'];
403 $pc_endTime=$origEvent['pc_endTime'];
404 $pc_facility=$origEvent['pc_facility'];
405 $pc_billing_location=$origEvent['pc_billing_location'];
406 $pc_recurrspec_array = unserialize($origEvent['pc_recurrspec']);
407 $origEvent = sqlStatement(
408 "SELECT * FROM openemr_postcalendar_events WHERE pc_eid != ? and pc_catid=? and pc_aid=? ".
409 "and pc_pid=? and pc_eventDate=? and pc_startTime=? and pc_endTime=? and pc_facility=? and pc_billing_location=?",
410 array($eid,$pc_catid,$pc_aid,$pc_pid,$pc_eventDate,$pc_startTime,$pc_endTime,$pc_facility,$pc_billing_location)
412 if (sqlNumRows($origEvent)>0) {
413 $origEventRow=sqlFetchArray($origEvent);
414 return $origEventRow['pc_eid'];
415 } else {
416 if (strpos($pc_recurrspec_array['exdate'], date('Ymd')) === false) {//;'20110228'
417 return false;
418 } else {//this happens in delete case
419 return true;
423 //===============================================================================
424 // insert an event
425 // $args is mainly filled with content from the POST http var
426 function InsertEvent($args, $from = 'general')
428 $pc_recurrtype = '0';
429 if ($args['form_repeat'] || $args['days_every_week']) {
430 if ($args['recurrspec']['event_repeat_freq_type'] == "6") {
431 $pc_recurrtype = 3;
432 } else {
433 $pc_recurrtype = $args['recurrspec']['event_repeat_on_freq'] ? '2' : '1';
437 $form_pid = empty($args['form_pid']) ? '' : $args['form_pid'];
438 $form_room = empty($args['form_room']) ? '' : $args['form_room'];
439 $form_gid = empty($args['form_gid']) ? '' : $args['form_gid'];
441 if ($from == 'general') {
442 $pc_eid = sqlInsert(
443 "INSERT INTO openemr_postcalendar_events ( " .
444 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_gid, pc_title, pc_time, pc_hometext, " .
445 "pc_informant, pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
446 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
447 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location,pc_room " .
448 ") VALUES (?,?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,1,1,?,?,?)",
449 array($args['form_category'],(isset($args['new_multiple_value']) ? $args['new_multiple_value'] : ''),$args['form_provider'],$form_pid,$form_gid,
450 $args['form_title'],$args['form_comments'],$_SESSION['authUserID'],$args['event_date'],
451 fixDate($args['form_enddate']),$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
452 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'],
453 $args['locationspec'],(int)$args['facility'],(int)$args['billing_facility'],$form_room)
456 //Manage tracker status.
457 if (!empty($form_pid)) {
458 manage_tracker_status($args['event_date'], $args['starttime'], $pc_eid, $form_pid, $_SESSION['authUser'], $args['form_apptstatus'], $args['form_room']);
461 $GLOBALS['temporary-eid-for-manage-tracker'] = $pc_eid; //used by manage tracker module to set correct encounter in tracker when check in
463 return $pc_eid;
464 } elseif ($from == 'payment') {
465 sqlStatement(
466 "INSERT INTO openemr_postcalendar_events ( " .
467 "pc_catid, pc_multiple, pc_aid, pc_pid, pc_title, pc_time, " .
468 "pc_eventDate, pc_endDate, pc_duration, pc_recurrtype, " .
469 "pc_recurrspec, pc_startTime, pc_endTime, pc_alldayevent, " .
470 "pc_apptstatus, pc_prefcatid, pc_location, pc_eventstatus, pc_sharing, pc_facility,pc_billing_location " .
471 ") VALUES (?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
472 array($args['form_category'],$args['new_multiple_value'],$args['form_provider'],$form_pid,$args['form_title'],
473 $args['event_date'],$args['form_enddate'],$args['duration'],$pc_recurrtype,serialize($args['recurrspec']),
474 $args['starttime'],$args['endtime'],$args['form_allday'],$args['form_apptstatus'],$args['form_prefcat'], $args['locationspec'],
477 (int)$args['facility'],
478 (int)$args['billing_facility'])
482 //================================================================================================================
484 * __increment()
485 * returns the next valid date for an event based on the
486 * current day,month,year,freq and type
487 * @private
488 * @returns string YYYY-MM-DD
490 function &__increment($d, $m, $y, $f, $t)
493 if ($t == REPEAT_EVERY_DAY) {
494 return date('Y-m-d', mktime(0, 0, 0, $m, ($d+$f), $y));
495 } elseif ($t == REPEAT_EVERY_WORK_DAY) {
496 // a workday is defined as Mon,Tue,Wed,Thu,Fri
497 // repeating on every or Nth work day means to not include
498 // weekends (Sat/Sun) in the increment... tricky
500 // ugh, a day-by-day loop seems necessary here, something where
501 // we can check to see if the day is a Sat/Sun and increment
502 // the frequency count so as to ignore the weekend. hmmmm....
503 $orig_freq = $f;
504 for ($daycount=1; $daycount<=$orig_freq; $daycount++) {
505 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d+$daycount), $y));
506 if (is_weekend_day($nextWorkDOW)) {
507 $f++;
511 // and finally make sure we haven't landed on a end week days
512 // adjust as necessary
513 $nextWorkDOW = date('w', mktime(0, 0, 0, $m, ($d+$f), $y));
514 if (count($GLOBALS['weekend_days']) === 2) {
515 if ($nextWorkDOW == $GLOBALS['weekend_days'][0]) {
516 $f+=2;
517 } elseif ($nextWorkDOW == $GLOBALS['weekend_days'][1]) {
518 $f++;
520 } elseif (count($GLOBALS['weekend_days']) === 1 && $nextWorkDOW === $GLOBALS['weekend_days'][0]) {
521 $f++;
524 return date('Y-m-d', mktime(0, 0, 0, $m, ($d+$f), $y));
525 } elseif ($t == REPEAT_EVERY_WEEK) {
526 return date('Y-m-d', mktime(0, 0, 0, $m, ($d+(7*$f)), $y));
527 } elseif ($t == REPEAT_EVERY_MONTH) {
528 return date('Y-m-d', mktime(0, 0, 0, ($m+$f), $d, $y));
529 } elseif ($t == REPEAT_EVERY_YEAR) {
530 return date('Y-m-d', mktime(0, 0, 0, $m, $d, ($y+$f)));
531 } elseif ($t == REPEAT_DAYS_EVERY_WEEK) {
532 $old_appointment_date = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
533 $next_appointment_date = getTheNextAppointment($old_appointment_date, $f);
534 return $next_appointment_date;
538 function getTheNextAppointment($appointment_date, $freq)
540 $day_arr = explode(",", $freq);
541 $date_arr = array();
542 foreach ($day_arr as $day) {
543 $day = getDayName($day);
544 $date = date('Y-m-d', strtotime("next " . $day, strtotime($appointment_date)));
545 array_push($date_arr, $date);
548 $next_appointment = getEarliestDate($date_arr);
549 return $next_appointment;
552 function getDayName($day_num)
554 if ($day_num == "1") {
555 return "sunday";
558 if ($day_num == "2") {
559 return "monday";
562 if ($day_num == "3") {
563 return "tuesday";
566 if ($day_num == "4") {
567 return "wednesday";
570 if ($day_num == "5") {
571 return "thursday";
574 if ($day_num == "6") {
575 return "friday";
578 if ($day_num == "7") {
579 return "saturday";
584 function getEarliestDate($date_arr)
586 $earliest = ($date_arr[0]);
587 foreach ($date_arr as $date) {
588 if (strtotime($date) < strtotime($earliest)) {
589 $earliest = $date;
593 return $earliest;
595 //================================================================================================================