2 include_once("{$GLOBALS['srcdir']}/sql.inc");
3 require_once(dirname(__FILE__) . "/classes/WSWrapper.class.php");
5 // These are for sports team use:
6 $PLAYER_FITNESSES = array(
9 xl('Restricted Training'),
13 xl('International Duty')
15 $PLAYER_FITCOLORS = array('#6677ff', '#00cc00', '#ffff00', '#ff3333', '#ff8800', '#ffeecc', '#ffccaa');
17 function getPatientData($pid, $given = "*, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS") {
18 $sql = "select $given from patient_data where pid='$pid' order by date DESC limit 0,1";
19 return sqlQuery($sql);
22 function getLanguages() {
23 $returnval = array('','english');
24 $sql = "select distinct lower(language) as language from patient_data";
25 $rez = sqlStatement($sql);
26 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
27 if (($row["language"] != "english") && ($row["language"] != "")) {
28 array_push($returnval, $row["language"]);
34 function getInsuranceProviders() {
38 $sql = "select name, id from insurance_companies order by name, id";
39 $rez = sqlStatement($sql);
40 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
41 $returnval[$row['id']] = $row['name'];
45 // Please leave this here. I have a user who wants to see zip codes and PO
46 // box numbers listed along with the insurance company names, as many companies
47 // have different billing addresses for different plans. -- Rod Roark
50 $sql = "select insurance_companies.name, insurance_companies.id, " .
51 "addresses.zip, addresses.line1 " .
52 "from insurance_companies, addresses " .
53 "where addresses.foreign_id = insurance_companies.id " .
54 "order by insurance_companies.name, addresses.zip";
56 $rez = sqlStatement($sql);
58 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
59 preg_match("/\d+/", $row['line1'], $matches);
60 $returnval[$row['id']] = $row['name'] . " (" . $row['zip'] .
61 "," . $matches[0] . ")";
68 function getProviders() {
69 $returnval = array("");
70 $sql = "select fname, lname from users where authorized = 1 and " .
71 "active = 1 and username != ''";
72 $rez = sqlStatement($sql);
73 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
74 if (($row["fname"] != "") && ($row["lname"] != "")) {
75 array_push($returnval, $row["fname"] . " " . $row["lname"]);
81 // ----------------------------------------------------------------------------
83 * GET ADDITIONAL INFORMATIONS
87 * @param $pid - patient id
90 function getPatientDataNL($pid) {
91 sqlQuery("SET NAMES 'utf8'");
92 $sql = "SELECT * FROM patient_data_NL WHERE pdn_id = '$pid'";
93 return sqlQuery($sql);
96 // Get one facility row. If the ID is not specified, then get either the
97 // "main" (billing) facility, or the default facility of the currently
98 // logged-in user. This was created to support genFacilityTitle() but
99 // may find additional uses.
101 function getFacility($facid=0) {
103 $query = "SELECT * FROM facility WHERE id = '$facid'";
105 else if ($facid == 0) {
106 $query = "SELECT * FROM facility ORDER BY " .
107 "billing_location DESC, service_location, id LIMIT 1";
110 $query = "SELECT facility.* FROM users, facility WHERE " .
111 "users.id = '" . $_SESSION['authUserID'] . "' AND " .
112 "facility.id = users.facility_id";
114 return sqlQuery($query);
117 // Generate a report title including report name and facility name, address
120 function genFacilityTitle($repname='', $facid=0) {
122 $s .= "<table class='ftitletable'>\n";
124 $s .= " <td class='ftitlecell1'>$repname</td>\n";
125 $s .= " <td class='ftitlecell2'>\n";
126 $r = getFacility($facid);
128 $s .= "<b>" . $r['name'] . "</b>\n";
129 if ($r['street']) $s .= "<br />" . $r['street'] . "\n";
130 if ($r['city'] || $r['state'] || $r['postal_code']) {
132 if ($r['city']) $s .= $r['city'];
134 if ($r['city']) $s .= ", \n";
137 if ($r['postal_code']) $s .= " " . $r['postal_code'];
140 if ($r['country_code']) $s .= "<br />" . $r['country_code'] . "\n";
141 if (preg_match('/[1-9]/', $r['phone'])) $s .= "<br />" . $r['phone'] . "\n";
152 returns all facilities or just the id for the first one
153 (FACILITY FILTERING (lemonsoftware))
155 @param string - if 'first' return first facility ordered by id
156 @return array | int for 'first' case
158 function getFacilities($first = '') {
159 $r = sqlStatement("SELECT * FROM facility ORDER BY id");
161 while ( $row = sqlFetchArray($r) ) {
165 if ( $first == 'first') {
166 return $ret[0]['id'];
173 GET SERVICE FACILITIES
175 returns all service_location facilities or just the id for the first one
176 (FACILITY FILTERING (CHEMED))
178 @param string - if 'first' return first facility ordered by id
179 @return array | int for 'first' case
181 function getServiceFacilities($first = '') {
182 $r = sqlStatement("SELECT * FROM facility WHERE service_location != 0 ORDER BY id");
184 while ( $row = sqlFetchArray($r) ) {
188 if ( $first == 'first') {
189 return $ret[0]['id'];
195 //(CHEMED) facility filter
196 function getProviderInfo($providerID = "%", $providers_only = true, $facility = '' ) {
198 if ($providers_only) {
199 // $param1 = " AND authorized=1 AND ( info IS NULL OR info NOT LIKE '%Nocalendar%' ) ";
200 $param1 = " AND authorized = 1 AND calendar = 1 ";
203 //--------------------------------
204 //(CHEMED) facility filter
207 if ($GLOBALS['restrict_user_facility']) {
208 $param2 = " AND (facility_id = $facility
212 where tablename = 'users'
218 $param2 = " AND facility_id = $facility ";
221 //--------------------------------
224 if ($providerID == "%") {
227 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
228 "from users where username != '' and active = 1 and id $command '" .
229 mysql_real_escape_string($providerID) . "' " . $param1 . $param2;
230 // sort by last name -- JRM June 2008
231 $query .= " ORDER BY lname, fname ";
232 $rez = sqlStatement($query);
233 for($iter=0; $row=sqlFetchArray($rez); $iter++)
234 $returnval[$iter]=$row;
236 //if only one result returned take the key/value pairs in array [0] and merge them down the the base array so that $resultval[0]['key'] is also
237 //accessible from $resultval['key']
240 $akeys = array_keys($returnval[0]);
241 foreach($akeys as $key) {
242 $returnval[0][$key] = $returnval[0][$key];
248 //same as above but does not reduce if only 1 row returned
249 function getCalendarProviderInfo($providerID = "%", $providers_only = true) {
251 if ($providers_only) {
252 $param1 = "AND authorized=1";
255 if ($providerID == "%") {
258 $query = "select distinct id, username, lname, fname, authorized, info, facility " .
259 "from users where active = 1 and username != '' and id $command '" .
260 mysql_real_escape_string($providerID) . "' " . $param1;
262 $rez = sqlStatement($query);
263 for($iter=0; $row=sqlFetchArray($rez); $iter++)
264 $returnval[$iter]=$row;
269 function getProviderName($providerID) {
270 $pi = getProviderInfo($providerID);
271 if (strlen($pi[0]["lname"]) > 0) {
272 return $pi[0]['fname'] . " " . $pi[0]['lname'];
277 function getProviderId($providerName) {
278 $query = "select id from users where username = '". mysql_real_escape_string($providerName)."'";
279 $rez = sqlStatement($query);
280 for($iter=0; $row=sqlFetchArray($rez); $iter++)
281 $returnval[$iter]=$row;
285 function getEthnoRacials() {
286 $returnval = array("");
287 $sql = "select distinct lower(ethnoracial) as ethnoracial from patient_data";
288 $rez = sqlStatement($sql);
289 for($iter=0; $row=sqlFetchArray($rez); $iter++) {
290 if (($row["ethnoracial"] != "")) {
291 array_push($returnval, $row["ethnoracial"]);
297 function getHistoryData($pid, $given = "*")
299 $sql = "select $given from history_data where pid='$pid' order by date DESC limit 0,1";
300 return sqlQuery($sql);
303 // function getInsuranceData($pid, $type = "primary", $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
304 function getInsuranceData($pid, $type = "primary", $given = "insd.*, ic.name as provider_name")
306 $sql = "select $given from insurance_data as insd " .
307 "left join insurance_companies as ic on ic.id = insd.provider " .
308 "where pid = '$pid' and type = '$type' order by date DESC limit 1";
309 return sqlQuery($sql);
312 function getInsuranceDataByDate($pid, $date, $type,
313 $given = "insd.*, DATE_FORMAT(subscriber_DOB,'%m/%d/%Y') as subscriber_DOB, ic.name as provider_name")
314 { // this must take the date in the following manner: YYYY-MM-DD
315 // this function recalls the insurance value that was most recently enterred from the
316 // given date. it will call up most recent records up to and on the date given,
317 // but not records enterred after the given date
318 $sql = "select $given from insurance_data as insd " .
319 "left join insurance_companies as ic on ic.id = provider " .
320 "where pid = '$pid' and date_format(date,'%Y-%m-%d') <= '$date' and " .
321 "type='$type' order by date DESC limit 1";
322 return sqlQuery($sql);
325 function getEmployerData($pid, $given = "*")
327 $sql = "select $given from employer_data where pid='$pid' order by date DESC limit 0,1";
328 return sqlQuery($sql);
331 function _set_patient_inc_count($limit, $count, $where) {
332 // When the limit is exceeded, find out what the unlimited count would be.
333 $GLOBALS['PATIENT_INC_COUNT'] = $count;
334 // if ($limit != "all" && $GLOBALS['PATIENT_INC_COUNT'] >= $limit) {
335 if ($limit != "all") {
336 $tmp = sqlQuery("SELECT count(*) AS count FROM patient_data WHERE $where");
337 $GLOBALS['PATIENT_INC_COUNT'] = $tmp['count'];
341 function getPatientLnames($lname = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
343 // Allow the last name to be followed by a comma and some part of a first name.
344 // New behavior for searches:
345 // Allows comma alone followed by some part of a first name
346 // If the first letter of either name is capital, searches for name starting
347 // with given substring (the expected behavior). If it is lower case, it
348 // it searches for the substring anywhere in the name. This applies to either
349 // last name or first name or both. The arbitrary limit of 100 results is set
350 // in the sql query below. --Mark Leeds
351 $lname = trim($lname);
353 if (preg_match('/^(.*),(.*)/', $lname, $matches)) {
354 $lname = trim($matches[1]);
355 $fname = trim($matches[2]);
357 $search_for_pieces1 = '';
358 $search_for_pieces2 = '';
359 if ($lname{0} != strtoupper($lname{0})) {$search_for_pieces1 = '%';}
360 if ($fname{0} != strtoupper($fname{0})) {$search_for_pieces2 = '%';}
362 $where = "lname LIKE '" . $search_for_pieces1 . "$lname%' " .
363 "AND fname LIKE '" . $search_for_pieces2 . "$fname%' ";
364 if (!empty($GLOBALS['pt_restrict_field'])) {
365 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
366 $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
370 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
371 if ($limit != "all") $sql .= " LIMIT $start, $limit";
373 $rez = sqlStatement($sql);
375 for($iter=0; $row=sqlFetchArray($rez); $iter++)
376 $returnval[$iter] = $row;
378 _set_patient_inc_count($limit, count($returnval), $where);
382 function getPatientId($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
385 $where = "pubpid LIKE '$pid%' ";
386 if (!empty($GLOBALS['pt_restrict_field']) && $GLOBALS['pt_restrict_by_id'] ) {
387 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
388 $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
392 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
393 if ($limit != "all") $sql .= " limit $start, $limit";
394 $rez = sqlStatement($sql);
395 for($iter=0; $row=sqlFetchArray($rez); $iter++)
396 $returnval[$iter]=$row;
398 _set_patient_inc_count($limit, count($returnval), $where);
402 function getByPatientDemographics($searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
404 $layoutCols = sqlStatement( "SELECT field_id FROM layout_options WHERE form_id='DEM' AND group_name not like ('%Employer%' ) AND uor !=0" );
407 for($iter=0; $row=sqlFetchArray($layoutCols); $iter++) {
411 $where .= " ".$row["field_id"]." like '%".$searchTerm."%' ";
414 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
415 if ($limit != "all") $sql .= " limit $start, $limit";
416 $rez = sqlStatement($sql);
417 for($iter=0; $row=sqlFetchArray($rez); $iter++)
418 $returnval[$iter]=$row;
419 _set_patient_inc_count($limit, count($returnval), $where);
423 function getByPatientDemographicsFilter($searchFields, $searchTerm = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0" )
425 $layoutCols = split( '~', $searchFields );
428 foreach ($layoutCols as $val ) {
433 $where .= " $val = '$searchTerm' ";
436 $where .= " $val like '$searchTerm%' ";
440 $sql = "SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
441 if ($limit != "all") $sql .= " limit $start, $limit";
442 $rez = sqlStatement($sql);
443 for($iter=0; $row=sqlFetchArray($rez); $iter++)
444 $returnval[$iter]=$row;
445 _set_patient_inc_count($limit, count($returnval), $where);
449 // return a collection of Patient PIDs
450 // new arg style by JRM March 2008
451 // orig function getPatientPID($pid = "%", $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
452 function getPatientPID($args)
455 $given = "pid, id, lname, fname, mname, providerID, DATE_FORMAT(DOB,'%m/%d/%Y') as DOB_TS";
456 $orderby = "lname ASC, fname ASC";
460 // alter default values if defined in the passed in args
461 if (isset($args['pid'])) { $pid = $args['pid']; }
462 if (isset($args['given'])) { $given = $args['given']; }
463 if (isset($args['orderby'])) { $orderby = $args['orderby']; }
464 if (isset($args['limit'])) { $limit = $args['limit']; }
465 if (isset($args['start'])) { $start = $args['start']; }
468 if ($pid == -1) $pid = "%";
469 elseif (empty($pid)) $pid = "NULL";
471 if (strstr($pid,"%")) $command = "like";
473 $sql="select $given from patient_data where pid $command '$pid' order by $orderby";
474 if ($limit != "all") $sql .= " limit $start, $limit";
476 $rez = sqlStatement($sql);
477 for($iter=0; $row=sqlFetchArray($rez); $iter++)
478 $returnval[$iter]=$row;
483 /* return a patient's name in the format LAST, FIRST */
484 function getPatientName($pid) {
485 if (empty($pid)) return "";
486 $patientData = getPatientPID(array("pid"=>$pid));
487 if (empty($patientData[0]['lname'])) return "";
488 $patientName = $patientData[0]['lname'] . ", " . $patientData[0]['fname'];
492 /* find patient data by DOB */
493 function getPatientDOB($DOB = "%", $given = "pid, id, lname, fname, mname", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
495 $DOB = fixDate($DOB, $DOB);
496 $where = "DOB like '$DOB%' ";
497 if (!empty($GLOBALS['pt_restrict_field'])) {
498 if ( $_SESSION{"authUser"} != 'admin' || $GLOBALS['pt_restrict_admin'] ) {
499 $where .= "AND ( patient_data.".$GLOBALS['pt_restrict_field']." = ( SELECT facility_id FROM users WHERE username = '".$_SESSION{"authUser"}."') OR patient_data.".$GLOBALS['pt_restrict_field']." = '' ) ";
503 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
505 if ($limit != "all") $sql .= " LIMIT $start, $limit";
507 $rez = sqlStatement($sql);
508 for($iter=0; $row=sqlFetchArray($rez); $iter++)
509 $returnval[$iter]=$row;
511 _set_patient_inc_count($limit, count($returnval), $where);
515 /* find patient data by SSN */
516 function getPatientSSN($ss = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
518 $where = "ss LIKE '$ss%'";
519 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
520 if ($limit != "all") $sql .= " LIMIT $start, $limit";
522 $rez = sqlStatement($sql);
523 for($iter=0; $row=sqlFetchArray($rez); $iter++)
524 $returnval[$iter]=$row;
526 _set_patient_inc_count($limit, count($returnval), $where);
530 //(CHEMED) Search by phone number
531 function getPatientPhone($phone = "%", $given = "pid, id, lname, fname, mname, providerID", $orderby = "lname ASC, fname ASC", $limit="all", $start="0")
533 $phone = ereg_replace( "[[:punct:]]","", $phone );
534 $where = "REPLACE(REPLACE(phone_home, '-', ''), ' ', '') REGEXP '$phone'";
535 $sql="SELECT $given FROM patient_data WHERE $where ORDER BY $orderby";
536 if ($limit != "all") $sql .= " LIMIT $start, $limit";
538 $rez = sqlStatement($sql);
539 for($iter=0; $row=sqlFetchArray($rez); $iter++)
540 $returnval[$iter]=$row;
542 _set_patient_inc_count($limit, count($returnval), $where);
546 function getPatientIds($given = "pid, id, lname, fname, mname", $orderby = "id ASC", $limit="all", $start="0")
548 $sql="select $given from patient_data order by $orderby";
551 $sql .= " limit $start, $limit";
553 $rez = sqlStatement($sql);
554 for($iter=0; $row=sqlFetchArray($rez); $iter++)
555 $returnval[$iter]=$row;
560 //----------------------input functions
561 function newPatientData( $db_id="",
584 $contact_relationship = "",
591 $migrantseasonal = "",
593 $monthly_income = "",
595 $financial_review = "",
608 $drivers_license = "",
614 $prefixlastpartner = "",
617 $provider_data = array(),
618 $referer_data = array()
623 $DOB = fixDate($DOB);
624 $regdate = fixDate($regdate);
627 $referral_source = '';
629 $rez = sqlQuery("select id, fitness, referral_source from patient_data where pid = $pid");
630 // Check for brain damage:
631 if ($db_id != $rez['id']) {
632 $errmsg = "Internal error: Attempt to change patient_data.id from '" .
633 $rez['id'] . "' to '$db_id' for pid '$pid'";
636 $fitness = $rez['fitness'];
637 $referral_source = $rez['referral_source'];
640 // Get the default price level.
641 $lrow = sqlQuery("SELECT option_id FROM list_options WHERE " .
642 "list_id = 'pricelevel' ORDER BY is_default DESC, seq ASC LIMIT 1");
643 $pricelevel = empty($lrow['option_id']) ? '' : $lrow['option_id'];
645 $query = ("replace into patient_data set
654 postal_code='$postal_code',
657 country_code='$country_code',
658 drivers_license='$drivers_license',
660 occupation='$occupation',
661 phone_home='$phone_home',
662 phone_biz='$phone_biz',
663 phone_contact='$phone_contact',
665 contact_relationship='$contact_relationship',
666 referrer='$referrer',
667 referrerID='$referrerID',
669 language='$language',
670 ethnoracial='$ethnoracial',
671 interpretter='$interpretter',
672 migrantseasonal='$migrantseasonal',
673 family_size='$family_size',
674 monthly_income='$monthly_income',
675 homeless='$homeless',
676 financial_review='$financial_review',
679 providerID = '$providerID',
680 genericname1 = '$genericname1',
681 genericval1 = '$genericval1',
682 genericname2 = '$genericname2',
683 genericval2 = '$genericval2',
684 phone_cell = '$phone_cell',
685 pharmacy_id = '$pharmacy_id',
686 hipaa_mail = '$hipaa_mail',
687 hipaa_voice = '$hipaa_voice',
688 hipaa_notice = '$hipaa_notice',
689 hipaa_message = '$hipaa_message',
692 referral_source='$referral_source',
694 pricelevel='$pricelevel',
697 $id = sqlInsert($query);
701 // find the last inserted id for new patient case
702 $db_id = empty($GLOBALS['dutchpc']) ? mysql_insert_id() : dsql_lastid();
706 $foo = sqlQuery("select pid from patient_data where id='$id' order by date limit 0,1");
709 if ( $GLOBALS['dutchpc'] ) {
710 $init = strtoupper(preg_replace('/[\s\.\-_0-9]/','',$initials));
712 $querynl = ("REPLACE INTO patient_data_NL SET
714 pdn_pxlast = '$prefixlast',
715 pdn_pxlastpar = '$prefixlastpartner',
716 pdn_lastpar = '$lastpartner',
717 pdn_street = '$nstreet',
719 pdn_addition = '$nadd',
720 pdn_initials = '$init'
723 if ( $db_id ) $idnl = sqlInsert($querynl); // only if exists
730 if ( $GLOBALS['dutchpc'] && $db_id && $provider_data && $referer_data) {
731 $querypr = ("INSERT INTO cl_providers(pro_pid, pro_company, pro_initials, pro_prefix, pro_lname,
732 pro_street, pro_number, pro_addition, pro_city, pro_zipcode, pro_phone, pro_fax, pro_email, pro_referer )
733 VALUES ($db_id, '{$provider_data['pro_company']}', '{$provider_data['pro_initials']}',
734 '{$provider_data['pro_prefix']}', '{$provider_data['pro_lname']}',
735 '{$provider_data['pro_street']}', '{$provider_data['pro_number']}', '{$provider_data['pro_addition']}',
736 '{$provider_data['pro_city']}', '{$provider_data['pro_zipcode']}',
737 '{$provider_data['pro_phone']}', '{$provider_data['pro_fax']}', '{$provider_data['pro_email']}',
738 '{$provider_data['pro_referer']}')
739 ON DUPLICATE KEY UPDATE pro_referer = '{$provider_data['pro_referer']}',
740 pro_company = '{$provider_data['pro_company']}', pro_initials = '{$provider_data['pro_initials']}',
741 pro_prefix = '{$provider_data['pro_prefix']}',
742 pro_lname = '{$provider_data['pro_lname']}', pro_street = '{$provider_data['pro_street']}',
743 pro_number = '{$provider_data['pro_number']}', pro_addition = '{$provider_data['pro_addition']}',
744 pro_city = '{$provider_data['pro_city']}', pro_zipcode = '{$provider_data['pro_zipcode']}',
745 pro_phone = '{$provider_data['pro_phone']}', pro_fax = '{$provider_data['pro_fax']}',
746 pro_email = '{$provider_data['pro_email']}'
748 $idpr = sqlInsert($querypr);
750 // referer if it's the case
751 if ( $referer_data['ref_code'] ) {
752 $queryre = ("INSERT INTO cl_referers(ref_pid, ref_code, ref_company, ref_initials, ref_prefix,
753 ref_lname, ref_street, ref_number, ref_addition, ref_city, ref_zipcode, ref_phone, ref_fax,
755 VALUES ($db_id, {$referer_data['ref_code']}, '{$referer_data['ref_company']}',
756 '{$referer_data['ref_initials']}', '{$referer_data['ref_prefix']}',
757 '{$referer_data['ref_lname']}', '{$referer_data['ref_street']}', '{$referer_data['ref_number']}',
758 '{$referer_data['ref_addition']}', '{$referer_data['ref_city']}', '{$referer_data['ref_zipcode']}',
759 '{$referer_data['ref_phone']}', '{$referer_data['ref_fax']}', '{$referer_data['ref_email']}')
760 ON DUPLICATE KEY UPDATE ref_code = {$referer_data['ref_code']},
761 ref_company = '{$referer_data['ref_company']}', ref_initials = '{$referer_data['ref_initials']}',
762 ref_prefix = '{$referer_data['ref_prefix']}',
763 ref_lname = '{$referer_data['ref_lname']}', ref_street = '{$referer_data['ref_street']}',
764 ref_number = '{$referer_data['ref_number']}', ref_addition = '{$referer_data['ref_addition']}',
765 ref_city = '{$referer_data['ref_city']}', ref_zipcode = '{$referer_data['ref_zipcode']}',
766 ref_phone = '{$referer_data['ref_phone']}', ref_fax = '{$referer_data['ref_fax']}',
767 ref_email = '{$referer_data['ref_email']}'
769 $idre = sqlInsert($queryre);
774 sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
775 $phone_biz,$phone_cell,$email,$pid);
780 // Supported input date formats are:
782 // mm/dd/yy (assumes 20yy for yy < 10, else 19yy)
784 // also mm-dd-yyyy, etc. and mm.dd.yyyy, etc.
786 function fixDate($date, $default="0000-00-00") {
787 $fixed_date = $default;
789 if (preg_match("'^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$'", $date)) {
790 $dmy = preg_split("'[/.-]'", $date);
792 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[0], $dmy[1], $dmy[2]);
794 if ($dmy[0] != 0 || $dmy[1] != 0 || $dmy[2] != 0) {
795 if ($dmy[2] < 1000) $dmy[2] += 1900;
796 if ($dmy[2] < 1910) $dmy[2] += 100;
798 $fixed_date = sprintf("%04u-%02u-%02u", $dmy[2], $dmy[0], $dmy[1]);
805 // Create or update patient data from an array.
807 function updatePatientData($pid, $new, $create=false)
809 /*******************************************************************
810 $real = getPatientData($pid);
811 $new['DOB'] = fixDate($new['DOB']);
812 while(list($key, $value) = each ($new))
813 $real[$key] = $value;
814 $real['date'] = "'+NOW()+'";
816 $sql = "insert into patient_data set ";
817 while(list($key, $value) = each($real))
818 $sql .= $key." = '$value', ";
819 $sql = substr($sql, 0, -2);
820 return sqlInsert($sql);
821 *******************************************************************/
823 // The above was broken, though seems intent to insert a new patient_data
824 // row for each update. A good idea, but nothing is doing that yet so
825 // the code below does not yet attempt it.
827 $new['DOB'] = fixDate($new['DOB']);
830 $sql = "INSERT INTO patient_data SET pid = '$pid', date = NOW()";
831 foreach ($new as $key => $value) {
832 if ($key == 'id') continue;
833 $sql .= ", `$key` = '$value'";
835 $db_id = sqlInsert($sql);
839 $rez = sqlQuery("SELECT pid FROM patient_data WHERE id = '$db_id'");
840 // Check for brain damage:
841 if ($pid != $rez['pid']) {
842 $errmsg = "Internal error: Attempt to change patient data with pid = '" .
843 $rez['pid'] . "' when current pid is '$pid' for id '$db_id'";
846 $sql = "UPDATE patient_data SET date = NOW()";
847 foreach ($new as $key => $value) {
848 $sql .= ", `$key` = '$value'";
850 $sql .= " WHERE id = '$db_id'";
854 $rez = sqlQuery("SELECT * FROM patient_data WHERE id = '$db_id'");
855 sync_patient($db_id,$rez['fname'],$rez['lname'],$rez['street'],$rez['city'],
856 $rez['postal_code'],$rez['state'],$rez['phone_home'],$rez['phone_biz'],
857 $rez['phone_cell'],$rez['email'],$rez['pid']);
862 function newEmployerData( $pid,
871 return sqlInsert("insert into employer_data set
874 postal_code='$postal_code',
883 // Create or update employer data from an array.
885 function updateEmployerData($pid, $new, $create=false)
887 $colnames = array('name','street','city','state','postal_code','country');
890 $set .= "pid = '$pid', date = NOW()";
891 foreach ($colnames as $key) {
892 $value = isset($new[$key]) ? $new[$key] : '';
893 $set .= ", `$key` = '$value'";
895 return sqlInsert("INSERT INTO employer_data SET $set");
899 $old = getEmployerData($pid);
901 foreach ($colnames as $key) {
902 $value = empty($old[$key]) ? '' : addslashes($old[$key]);
903 if (isset($new[$key]) && strcmp($new[$key], $value) != 0) {
907 $set .= "`$key` = '$value', ";
910 $set .= "pid = '$pid', date = NOW()";
911 return sqlInsert("INSERT INTO employer_data SET $set");
917 // This updates or adds the given insurance data info, while retaining any
918 // previously added insurance_data rows that should be preserved.
919 // This does not directly support the maintenance of non-current insurance.
921 function newInsuranceData(
928 $subscriber_lname = "",
929 $subscriber_mname = "",
930 $subscriber_fname = "",
931 $subscriber_relationship = "",
933 $subscriber_DOB = "",
934 $subscriber_street = "",
935 $subscriber_postal_code = "",
936 $subscriber_city = "",
937 $subscriber_state = "",
938 $subscriber_country = "",
939 $subscriber_phone = "",
940 $subscriber_employer = "",
941 $subscriber_employer_street = "",
942 $subscriber_employer_city = "",
943 $subscriber_employer_postal_code = "",
944 $subscriber_employer_state = "",
945 $subscriber_employer_country = "",
947 $subscriber_sex = "",
948 $effective_date = "0000-00-00",
949 $accept_assignment = "TRUE")
951 if (strlen($type) <= 0) return FALSE;
953 // If a bad date was passed, err on the side of caution.
954 $effective_date = fixDate($effective_date, date('Y-m-d'));
956 $idres = sqlStatement("SELECT * FROM insurance_data WHERE " .
957 "pid = '$pid' AND type = '$type' ORDER BY date DESC");
958 $idrow = sqlFetchArray($idres);
960 // Replace the most recent entry in any of the following cases:
961 // * Its effective date is >= this effective date.
962 // * It is the first entry and it has no (insurance) provider.
963 // * There is no encounter that is earlier than the new effective date but
964 // on or after the old effective date.
965 // Otherwise insert a new entry.
969 if (strcmp($idrow['date'], $effective_date) > 0) {
973 if (!$idrow['provider'] && !sqlFetchArray($idres)) {
977 $ferow = sqlQuery("SELECT count(*) AS count FROM form_encounter " .
978 "WHERE pid = '$pid' AND date < '$effective_date 00:00:00' AND " .
979 "date >= '" . $idrow['date'] . " 00:00:00'");
980 if ($ferow['count'] == 0) $replace = true;
987 // TBD: This is a bit dangerous in that a typo in entering the effective
988 // date can wipe out previous insurance history. So we want some data
989 // entry validation somewhere.
990 sqlStatement("DELETE FROM insurance_data WHERE " .
991 "pid = '$pid' AND type = '$type' AND date >= '$effective_date' AND " .
992 "id != " . $idrow['id']);
995 $data['type'] = $type;
996 $data['provider'] = $provider;
997 $data['policy_number'] = $policy_number;
998 $data['group_number'] = $group_number;
999 $data['plan_name'] = $plan_name;
1000 $data['subscriber_lname'] = $subscriber_lname;
1001 $data['subscriber_mname'] = $subscriber_mname;
1002 $data['subscriber_fname'] = $subscriber_fname;
1003 $data['subscriber_relationship'] = $subscriber_relationship;
1004 $data['subscriber_ss'] = $subscriber_ss;
1005 $data['subscriber_DOB'] = $subscriber_DOB;
1006 $data['subscriber_street'] = $subscriber_street;
1007 $data['subscriber_postal_code'] = $subscriber_postal_code;
1008 $data['subscriber_city'] = $subscriber_city;
1009 $data['subscriber_state'] = $subscriber_state;
1010 $data['subscriber_country'] = $subscriber_country;
1011 $data['subscriber_phone'] = $subscriber_phone;
1012 $data['subscriber_employer'] = $subscriber_employer;
1013 $data['subscriber_employer_city'] = $subscriber_employer_city;
1014 $data['subscriber_employer_street'] = $subscriber_employer_street;
1015 $data['subscriber_employer_postal_code'] = $subscriber_employer_postal_code;
1016 $data['subscriber_employer_state'] = $subscriber_employer_state;
1017 $data['subscriber_employer_country'] = $subscriber_employer_country;
1018 $data['copay'] = $copay;
1019 $data['subscriber_sex'] = $subscriber_sex;
1020 $data['pid'] = $pid;
1021 $data['date'] = $effective_date;
1022 $data['accept_assignment'] = $accept_assignment;
1023 updateInsuranceData($idrow['id'], $data);
1024 return $idrow['id'];
1027 return sqlInsert("INSERT INTO insurance_data SET
1029 provider = '$provider',
1030 policy_number = '$policy_number',
1031 group_number = '$group_number',
1032 plan_name = '$plan_name',
1033 subscriber_lname = '$subscriber_lname',
1034 subscriber_mname = '$subscriber_mname',
1035 subscriber_fname = '$subscriber_fname',
1036 subscriber_relationship = '$subscriber_relationship',
1037 subscriber_ss = '$subscriber_ss',
1038 subscriber_DOB = '$subscriber_DOB',
1039 subscriber_street = '$subscriber_street',
1040 subscriber_postal_code = '$subscriber_postal_code',
1041 subscriber_city = '$subscriber_city',
1042 subscriber_state = '$subscriber_state',
1043 subscriber_country = '$subscriber_country',
1044 subscriber_phone = '$subscriber_phone',
1045 subscriber_employer = '$subscriber_employer',
1046 subscriber_employer_city = '$subscriber_employer_city',
1047 subscriber_employer_street = '$subscriber_employer_street',
1048 subscriber_employer_postal_code = '$subscriber_employer_postal_code',
1049 subscriber_employer_state = '$subscriber_employer_state',
1050 subscriber_employer_country = '$subscriber_employer_country',
1052 subscriber_sex = '$subscriber_sex',
1054 date = '$effective_date',
1055 accept_assignment = '$accept_assignment'
1060 // This is used internally only.
1061 function updateInsuranceData($id, $new)
1063 $fields = sqlListFields("insurance_data");
1066 while(list($key, $value) = each ($new)) {
1067 if (in_array($key, $fields)) {
1068 $use[$key] = $value;
1072 $sql = "UPDATE insurance_data SET ";
1073 while(list($key, $value) = each($use))
1074 $sql .= "`$key` = '$value', ";
1075 $sql = substr($sql, 0, -2) . " WHERE id = '$id'";
1080 function newHistoryData($pid, $new=false) {
1081 $sql = "insert into history_data set pid = '$pid', date = NOW()";
1083 while(list($key, $value) = each($new)) {
1084 if (!get_magic_quotes_gpc()) $value = addslashes($value);
1085 $sql .= ", `$key` = '$value'";
1088 return sqlInsert($sql);
1091 function updateHistoryData($pid,$new)
1093 $real = getHistoryData($pid);
1094 while(list($key, $value) = each ($new))
1095 $real[$key] = $value;
1096 $real['date'] = "'+NOW()+'";
1099 $sql = "insert into history_data set ";
1100 while(list($key, $value) = each($real))
1101 $sql .= "`$key` = '$value', ";
1102 $sql = substr($sql, 0, -2);
1104 return sqlInsert($sql);
1107 function sync_patient($id,$fname,$lname,$street,$city,$postal_code,$state,$phone_home,
1108 $phone_biz,$phone_cell,$email,$pid="")
1110 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) return;
1111 if (!$GLOBALS['oer_config']['ws_accounting']['enabled']) return;
1113 $db = $GLOBALS['adodb']['db'];
1114 $customer_info = array();
1116 $sql = "SELECT foreign_id,foreign_table FROM integration_mapping where local_table = 'patient_data' and local_id = '" . $id . "'";
1117 $result = $db->Execute($sql);
1118 if ($result && !$result->EOF) {
1119 $customer_info['foreign_update'] = true;
1120 $customer_info['foreign_id'] = $result->fields['foreign_id'];
1121 $customer_info['foreign_table'] = $result->fields['foreign_table'];
1124 ///xml rpc code to connect to accounting package and add user to it
1125 $customer_info['firstname'] = $fname;
1126 $customer_info['lastname'] = $lname;
1127 $customer_info['address'] = $street;
1128 $customer_info['suburb'] = $city;
1129 $customer_info['state'] = $state;
1130 $customer_info['postcode'] = $postal_code;
1132 //ezybiz wants state as a code rather than abbreviation
1133 $customer_info['geo_zone_id'] = "";
1134 $sql = "SELECT zone_id from geo_zone_reference where zone_code = '" . strtoupper($state) . "'";
1135 $db = $GLOBALS['adodb']['db'];
1136 $result = $db->Execute($sql);
1137 if ($result && !$result->EOF) {
1138 $customer_info['geo_zone_id'] = $result->fields['zone_id'];
1141 //ezybiz wants country as a code rather than abbreviation
1142 $customer_info['geo_country_id'] = "";
1143 $sql = "SELECT countries_id from geo_country_reference where countries_iso_code_2 = '" . strtoupper($country_code) . "'";
1144 $db = $GLOBALS['adodb']['db'];
1145 $result = $db->Execute($sql);
1146 if ($result && !$result->EOF) {
1147 $customer_info['geo_country_id'] = $result->fields['countries_id'];
1150 $customer_info['phone1'] = $phone_home;
1151 $customer_info['phone1comment'] = "Home Phone";
1152 $customer_info['phone2'] = $phone_biz;
1153 $customer_info['phone2comment'] = "Business Phone";
1154 $customer_info['phone3'] = $phone_cell;
1155 $customer_info['phone3comment'] = "Cell Phone";
1156 $customer_info['email'] = $email;
1157 $customer_info['customernumber'] = $pid;
1159 $function['ezybiz.add_customer'] = array(new xmlrpcval($customer_info,"struct"));
1160 $ws = new WSWrapper($function);
1162 // if the remote patient was added make an entry in the local mapping table to that updates can be made correctly
1163 if (is_numeric($ws->value)) {
1164 $sql = "REPLACE INTO integration_mapping set id = '" . $db->GenID("sequences") . "', foreign_id ='" . $ws->value . "', foreign_table ='customer', local_id = '" . $id . "', local_table = 'patient_data' ";
1165 $db->Execute($sql) or die ("error: " . $db->ErrorMsg());
1170 // in months if < 2 years old
1171 // in years if > 2 years old
1172 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1173 // (optional) nowYMD is a date in YYYYMMDD format
1174 function getPatientAge($dobYMD, $nowYMD=null)
1176 // strip any dashes from the DOB
1177 $dobYMD = preg_replace("/-/", "", $dobYMD);
1178 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1180 // set the 'now' date values
1181 if ($nowYMD == null) {
1182 $nowDay = date("d");
1183 $nowMonth = date("m");
1184 $nowYear = date("Y");
1187 $nowDay = substr($nowYMD,6,2);
1188 $nowMonth = substr($nowYMD,4,2);
1189 $nowYear = substr($nowYMD,0,4);
1192 $dayDiff = $nowDay - $dobDay;
1193 $monthDiff = $nowMonth - $dobMonth;
1194 $yearDiff = $nowYear - $dobYear;
1196 $ageInMonths = (($nowYear * 12) + $nowMonth) - (($dobYear*12) + $dobMonth);
1198 if ( $ageInMonths > 24 ) {
1200 if (($monthDiff == 0) && ($dayDiff < 0)) { $age -= 1; }
1201 else if ($monthDiff < 0) { $age -= 1; }
1204 $age = "$ageInMonths month";
1211 // Returns Age in days
1212 // in months if < 2 years old
1213 // in years if > 2 years old
1214 // given YYYYMMDD from MySQL DATE_FORMAT(DOB,'%Y%m%d')
1215 // (optional) nowYMD is a date in YYYYMMDD format
1216 function getPatientAgeInDays($dobYMD, $nowYMD=null) {
1219 // strip any dashes from the DOB
1220 $dobYMD = preg_replace("/-/", "", $dobYMD);
1221 $dobDay = substr($dobYMD,6,2); $dobMonth = substr($dobYMD,4,2); $dobYear = substr($dobYMD,0,4);
1223 // set the 'now' date values
1224 if ($nowYMD == null) {
1225 $nowDay = date("d");
1226 $nowMonth = date("m");
1227 $nowYear = date("Y");
1230 $nowDay = substr($nowYMD,6,2);
1231 $nowMonth = substr($nowYMD,4,2);
1232 $nowYear = substr($nowYMD,0,4);
1236 $dobtime = strtotime($dobYear."-".$dobMonth."-".$dobDay);
1237 $nowtime = strtotime($nowYear."-".$nowMonth."-".$nowDay);
1238 $timediff = $nowtime - $dobtime;
1239 $age = $timediff / 86400;
1244 function dateToDB ($date)
1246 $date=substr ($date,6,4)."-".substr ($date,3,2)."-".substr($date, 0,2);
1251 // ----------------------------------------------------------------------------
1253 * DROPDOWN FOR COUNTRIES
1255 * build a dropdown with all countries from geo_country_reference
1257 * @param int $selected - id for selected record
1258 * @param string $name - the name/id for select form
1259 * @return void - just echo the html encoded string
1261 function dropdown_countries($selected = 0, $name = 'country_code') {
1262 $r = sqlStatement("SELECT * FROM geo_country_reference ORDER BY countries_name");
1264 $string = "<select name='$name' id='$name'>";
1265 while ( $row = sqlFetchArray($r) ) {
1266 $sufix = ( $selected == $row['countries_id']) ? 'selected="selected"' : '';
1267 $string .= "<option value='{$row['countries_id']}' $sufix>{$row['countries_name']}</option>";
1270 $string .= '</select>';
1275 // ----------------------------------------------------------------------------
1277 * DROPDOWN FOR YES/NO
1279 * build a dropdown with two options (yes - 1, no - 0)
1281 * @param int $selected - id for selected record
1282 * @param string $name - the name/id for select form
1283 * @return void - just echo the html encoded string
1285 function dropdown_yesno($selected = 0, $name = 'yesno') {
1286 $string = "<select name='$name' id='$name'>";
1288 $selected = (int)$selected;
1289 if ( $selected == 0) { $sel1 = 'selected="selected"'; $sel2 = ''; }
1290 else { $sel2 = 'selected="selected"'; $sel1 = ''; }
1292 $string .= "<option value='0' $sel1>" .xl('No'). "</option>";
1293 $string .= "<option value='1' $sel2>" .xl('Yes'). "</option>";
1294 $string .= '</select>';
1299 // ----------------------------------------------------------------------------
1301 * DROPDOWN FOR MALE/FEMALE options
1303 * build a dropdown with three options (unselected/male/female)
1305 * @param int $selected - id for selected record
1306 * @param string $name - the name/id for select form
1307 * @return void - just echo the html encoded string
1309 function dropdown_sex($selected = 0, $name = 'sex') {
1310 $string = "<select name='$name' id='$name'>";
1312 if ( $selected == 1) { $sel1 = 'selected="selected"'; $sel2 = ''; $sel0 = ''; }
1313 else if ($selected == 2) { $sel2 = 'selected="selected"'; $sel1 = ''; $sel0 = ''; }
1314 else { $sel0 = 'selected="selected"'; $sel1 = ''; $sel2 = ''; }
1316 $string .= "<option value='0' $sel0>" .xl('Unselected'). "</option>";
1317 $string .= "<option value='1' $sel1>" .xl('Male'). "</option>";
1318 $string .= "<option value='2' $sel2>" .xl('Female'). "</option>";
1319 $string .= '</select>';
1324 // ----------------------------------------------------------------------------
1326 * DROPDOWN FOR MARITAL STATUS
1328 * build a dropdown with marital status
1330 * @param int $selected - id for selected record
1331 * @param string $name - the name/id for select form
1332 * @return void - just echo the html encoded string
1334 function dropdown_marital($selected = 0, $name = 'status') {
1335 $string = "<select name='$name' id='$name'>";
1337 $statii = array('married','single','divorced','widowed','separated','domestic partner');
1339 foreach ( $statii as $st ) {
1340 $sel = ( $st == $selected ) ? 'selected="selected"' : '';
1341 $string .= '<option value="' .$st. '" '.$sel.' >' .xl($st). '</option>';
1344 $string .= '</select>';
1349 // ----------------------------------------------------------------------------
1351 * DROPDOWN FOR PROVIDERS
1353 * build a dropdown with all providers
1355 * @param int $selected - id for selected record
1356 * @param string $name - the name/id for select form
1357 * @return void - just echo the html encoded string
1359 function dropdown_providers($selected = 0, $name = 'status') {
1360 $provideri = getProviderInfo();
1362 $string = "<select name='$name' id='$name'>";
1363 $string .= '<option value="">' .xl('Unassigned'). '</option>';
1364 foreach ( $provideri as $s ) {
1365 $sel = ( $s['id'] == $selected ) ? 'selected="selected"' : '';
1366 $string .= '<option value="' .$s['id']. '" '.$sel.' >' .ucwords($s['fname']." ".$s['lname']). '</option>';
1369 $string .= '</select>';
1374 // ----------------------------------------------------------------------------
1376 * DROPDOWN FOR INSURANCE COMPANIES
1378 * build a dropdown with all insurers
1380 * @param int $selected - id for selected record
1381 * @param string $name - the name/id for select form
1382 * @return void - just echo the html encoded string
1384 function dropdown_insurance($selected = 0, $name = 'iprovider') {
1385 $insurancei = getInsuranceProviders();
1387 $string = "<select name='$name' id='$name'>";
1388 $string .= '<option value="0">Onbekend</option>';
1389 foreach ( $insurancei as $iid => $iname ) {
1390 $sel = ( strtolower($iid) == strtolower($selected) ) ? 'selected="selected"' : '';
1391 $string .= '<option value="' .$iid. '" '.$sel.' >' .$iname. '(' .$iid. ')</option>';
1394 $string .= '</select>';
1400 // ----------------------------------------------------------------------------
1404 * return the name or the country code, function of arguments
1406 * @param int $country_code
1407 * @param string $country_name
1408 * @return string | int - name or code
1410 function country_code($country_code = 0, $country_name = '') {
1412 if ( $country_code ) {
1413 $sql = "SELECT countries_name AS res FROM geo_country_reference WHERE countries_id = '$country_code'";
1415 $sql = "SELECT countries_id AS res FROM geo_country_reference WHERE countries_name = '$country_name'";
1418 $db = $GLOBALS['adodb']['db'];
1419 $result = $db->Execute($sql);
1420 if ($result && !$result->EOF) {
1421 $strint = $result->fields['res'];
1427 // ----------------------------------------------------------------------------
1429 * GET INSURANCE DATA
1432 * return the insurer(s) and some patient
1434 * @param int $pid - patient id
1435 * @param int $current 1-current 0-all insurers
1438 function get_insurers_nl($pid = 0, $current = 1) {
1439 if ( !$pid ) return FALSE;
1441 $join = 'insurance_companies ic ON ic.id = pi.pin_provider';
1442 $r = dsql_select('*', 'patient_insurers_NL pi', array('pin_pid' => $pid), 'pin_date DESC', $join);
1444 while ( $row = mysql_fetch_array($r) ) {
1448 return ( $current ? $rez[0] : $rez );
1451 // ----------------------------------------------------------------------------
1453 * SET INSURANCE DATA
1456 * set the insurer for a patient
1458 * @param int $pid - patient id
1459 * @param int $insid - insurer id
1462 function set_insurer_nl($pid = 0, $insid = 0, $date = '', $policy = '') {
1463 if ( !$pid || !$insid || ($date == '0000-00-00') ) return FALSE;
1465 $fields = array('pin_pid', 'pin_provider', 'pin_date', 'pin_policy');
1466 $values = array($pid, $insid, $date, $policy);
1467 dsql_insert('patient_insurers_NL', $fields, $values);
1470 // ----------------------------------------------------------------------------
1472 * FIND THE INSURERS STATUS FOR A PATIENT
1475 * return the answer for the question: is this the first insurer or not?
1477 * @param int $pid - patient id
1478 * @return int - the number of insurer records ( 0 - no insurer; >0 some insurers)
1480 function total_insurers($pid = 0) {
1481 if ( !$pid ) return FALSE;
1483 $r = dsql_select('COUNT(*) AS c', 'patient_insurers_NL', array('pin_pid' => $pid));
1484 $row = mysql_fetch_array($r);
1489 function DBToDate ($date)
1491 $date=substr ($date,5,2)."/".substr ($date,8,2)."/".substr($date, 0,4);
1495 function get_patient_balance($pid) {
1496 if ($GLOBALS['oer_config']['ws_accounting']['enabled'] === 2) {
1497 $brow = sqlQuery("SELECT SUM(fee) AS amount FROM billing WHERE " .
1498 "pid = '$pid' AND activity = 1");
1499 $srow = sqlQuery("SELECT SUM(fee) AS amount FROM drug_sales WHERE " .
1501 $drow = sqlQuery("SELECT SUM(pay_amount) AS payments, " .
1502 "SUM(adj_amount) AS adjustments FROM ar_activity WHERE " .
1504 return sprintf('%01.2f', $brow['amount'] + $srow['amount']
1505 - $drow['payments'] - $drow['adjustments']);
1507 else if ($GLOBALS['oer_config']['ws_accounting']['enabled']) {
1508 // require_once($GLOBALS['fileroot'] . "/library/classes/WSWrapper.class.php");
1509 $conn = $GLOBALS['adodb']['db'];
1510 $customer_info['id'] = 0;
1511 $sql = "SELECT foreign_id FROM integration_mapping AS im " .
1512 "LEFT JOIN patient_data AS pd ON im.local_id = pd.id WHERE " .
1513 "pd.pid = '" . $pid . "' AND im.local_table = 'patient_data' AND " .
1514 "im.foreign_table = 'customer'";
1515 $result = $conn->Execute($sql);
1516 if($result && !$result->EOF) {
1517 $customer_info['id'] = $result->fields['foreign_id'];
1519 $function['ezybiz.customer_balance'] = array(new xmlrpcval($customer_info,"struct"));
1520 $ws = new WSWrapper($function);
1521 if(is_numeric($ws->value)) {
1522 return sprintf('%01.2f', $ws->value);