示例#1
0
 protected function _createAudit($providerId, $personId, $visitId, $type)
 {
     $providerId = (int) $providerId;
     $personId = (int) $personId;
     $visitId = (int) $visitId;
     $audit = array();
     $audit['objectClass'] = 'GenericAccessAudit';
     $audit['objectId'] = $personId . ';' . $visitId;
     $audit['type'] = (int) $type;
     $audit['userId'] = $providerId;
     $audit['patientId'] = $personId;
     $values = array();
     $provider = new Provider();
     $provider->personId = $audit['userId'];
     $provider->populate();
     $values['provider'] = $provider->toArray();
     $patient = new Patient();
     $patient->personId = $personId;
     $patient->populate();
     $values['patient'] = $patient->toArray();
     $values['personId'] = $patient->personId;
     $visit = new Visit();
     $visit->visitId = $visitId;
     $visit->populate();
     $values['visit'] = $visit->toArray();
     $values['visitId'] = $visit->visitId;
     $audit['auditValues'] = $values;
     Audit::persistManualAuditArray($audit);
 }
 public function myAlertsAction()
 {
     $personId = Zend_Auth::getInstance()->getIdentity()->personId;
     $team = new TeamMember();
     $teamId = $team->getTeamByPersonId($personId);
     $rows = array();
     if (true) {
         $alertMsg = new GeneralAlert();
         $alertMsgIterator = $alertMsg->getIteratorByTeam($teamId);
         foreach ($alertMsgIterator as $alert) {
             $tmp = array();
             $tmp['id'] = $alert->generalAlertId;
             $tmp['data'][] = '<img src="' . $this->view->baseUrl . '/img/medium.png' . '" alt="' . $alert->urgency . '" /> ' . $alert->urgency;
             // below are temporary data
             $objectClass = $alert->objectClass;
             if (!class_exists($objectClass)) {
                 continue;
             }
             $obj = new $objectClass();
             foreach ($obj->_primaryKeys as $key) {
                 $obj->{$key} = $alert->objectId;
             }
             $obj->populate();
             $patient = new Patient();
             $patient->personId = $obj->personId;
             $patient->populate();
             $tmp['data'][] = $patient->person->getDisplayName();
             // patient
             $tmp['data'][] = '';
             // location
             $tmp['data'][] = date('m/d/Y H:i', strtotime($alert->dateTime));
             $tmp['data'][] = $alert->message;
             $forwardedBy = '';
             if ($alert->forwardedBy > 0) {
                 $person = new Person();
                 $person->personId = (int) $alert->forwardedBy;
                 $person->populate();
                 $forwardedBy = $person->displayName;
             }
             $tmp['data'][] = $forwardedBy;
             // forwarded
             $tmp['data'][] = $alert->comment;
             // comment
             $controllerName = call_user_func($objectClass . "::" . "getControllerName");
             $jumpLink = call_user_func_array($controllerName . "::" . "buildJSJumpLink", array($alert->objectId, $alert->userId, $objectClass));
             $js = "function jumpLink{$objectClass}(objectId,patientId) {\n{$jumpLink}\n}";
             $tmp['data'][] = $js;
             $tmp['data'][] = $objectClass . ':' . $alert->objectId . ':' . $patient->personId;
             $rows[] = $tmp;
         }
     }
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct(array('rows' => $rows));
 }
 public function _setActivePatient($personId)
 {
     if (!$personId > 0) {
         return;
     }
     $patient = new Patient();
     $patient->personId = (int) $personId;
     $patient->populate();
     $patient->person->populate();
     $this->_patient = $patient;
     //$this->_visit = null;
     $this->view->patient = $this->_patient;
 }
示例#4
0
 public function pidLookupAction()
 {
     $hl7 = $this->_getParam('DATA');
     $fields = split("\\|", $hl7);
     $personId = 0;
     if (count($fields) > 18) {
         $personId = (int) $fields[19];
         //field containing the MRN
     }
     $patient = new Patient();
     $patient->personId = $personId;
     if ($personId > 0 && $patient->populate()) {
         urlencode($this->render('pid-lookup.phtml'));
     }
     return urlencode($this->render('not-found'));
 }
 public function detailAction()
 {
     $personId = (int) $this->_getParam('personId');
     if (!$personId > 0) {
         $this->_helper->autoCompleteDojo($personId);
     }
     $db = Zend_Registry::get('dbAdapter');
     $patient = new Patient();
     $patient->personId = (int) $personId;
     $patient->populate();
     $patient->person->populate();
     $outputArray = $patient->toArray();
     $outputArray['displayGender'] = $patient->displayGender;
     $outputArray['age'] = $patient->age;
     $acj = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $acj->suppressExit = true;
     $acj->direct($outputArray);
 }
 public function indexAction()
 {
     $this->view->filterDates = $this->_filterDates;
     $this->view->filterGraphs = $this->_filterGraphs;
     $this->view->labelKeyValues = $this->getVitalSignsTemplateKeyValue();
     $this->render('index');
     return;
     exit;
     $pat = new Patient();
     $pat->personId = 1983;
     $pat->populate();
     echo $pat->bmi;
     //var_dump(VitalSignGroup::getBMIVitalsForPatientId(1983));
     exit;
     $vitals = new VitalSignGroup();
     $vitalsIter = $vitals->getIterator();
     foreach ($vitalsIter as $vitals) {
         print_r($vitals->toString());
     }
     $this->render();
 }
 public function flowSheetTemplateAction()
 {
     $personId = (int) $this->_getParam('personId');
     $patient = new Patient();
     $patient->personId = $personId;
     $patient->populate();
     $vitalSignIter = new VitalSignGroupsIterator();
     $vitalSignIter->setFilter(array("personId" => $personId));
     $xmlData = PdfController::toXML($patient, 'Patient', null);
     $xmlData .= "<VitalSignGroups>";
     $loop = 0;
     foreach ($vitalSignIter as $vitalGroup) {
         $xmlData .= PdfController::toXML($vitalGroup, 'VitalSignGroup', null);
         if ($loop > 5) {
             exit;
         }
         $loop++;
     }
     $xmlData .= "</VitalSignGroups>";
     //header('Content-type: text/xml;');
     //echo $xmlData;exit;
     $this->_forward('pdf-merge-attachment', 'pdf', null, array('attachmentReferenceId' => '5', 'xmlData' => $xmlData));
 }
 public function _setActivePatient($personId, $visitId)
 {
     if (!$personId > 0) {
         return;
     }
     $memcache = Zend_Registry::get('memcache');
     $patient = new Patient();
     $patient->personId = (int) $personId;
     $patient->populate();
     $patient->person->populate();
     $this->_patient = $patient;
     $this->view->patient = $this->_patient;
     $mostRecentRaw = $memcache->get('mostRecent');
     $currentUserId = (int) Zend_Auth::getInstance()->getIdentity()->personId;
     $personId = $patient->personId;
     $teamId = $patient->teamId;
     if ($mostRecentRaw === false) {
         $mostRecent = array();
     } else {
         $mostRecent = unserialize($mostRecentRaw);
     }
     if (!array_key_exists($currentUserId, $mostRecent)) {
         $mostRecent[$currentUserId] = array();
     }
     if (array_key_exists($personId, $mostRecent[$currentUserId])) {
         unset($mostRecent[$currentUserId][$personId]);
     }
     $name = $patient->person->last_name . ', ' . $patient->person->first_name . ' ' . substr($patient->person->middle_name, 0, 1) . ' #' . $patient->record_number;
     $mostRecent[$currentUserId][$patient->personId] = array('name' => $name, 'teamId' => $teamId);
     $memcache->set('mostRecent', serialize($mostRecent));
     if (strlen($patient->teamId) > 0) {
         $name = TeamMember::ENUM_PARENT_NAME;
         $enumeration = new Enumeration();
         $enumeration->populateByEnumerationName($name);
         $enumerationsClosure = new EnumerationsClosure();
         $rowset = $enumerationsClosure->getAllDescendants($enumeration->enumerationId, 1);
         $patientEnumerationId = 0;
         foreach ($rowset as $row) {
             if ($patient->teamId == $row->key) {
                 $patientEnumerationId = $row->enumerationId;
                 break;
             }
         }
         if ($patientEnumerationId !== 0) {
             $this->view->team = TeamMember::generateTeamTree($patientEnumerationId);
         }
     }
     // POSTINGS
     $allergies = array();
     $patientAllergy = new PatientAllergy();
     $patientAllergyIterator = $patientAllergy->getIteratorByPatient($personId);
     foreach ($patientAllergyIterator as $allergy) {
         if ($allergy->noKnownAllergies) {
             continue;
         }
         $allergies[] = $allergy->toArray();
     }
     $this->view->allergies = $allergies;
     $notes = array();
     $patientNote = new PatientNote();
     $patientNoteIterator = $patientNote->getIterator();
     $filters = array();
     $filters['patient_id'] = $personId;
     $filters['active'] = 1;
     $filters['posting'] = 1;
     $patientNoteIterator->setFilters($filters);
     foreach ($patientNoteIterator as $note) {
         $notes[] = $note->toArray();
     }
     $this->view->notes = $notes;
     //REMINDERS
     $ctr = 0;
     $hsa = new HealthStatusAlert();
     $hsaIterator = $hsa->getIteratorByStatusWithPatientId('active', $personId);
     foreach ($hsaIterator as $row) {
         $ctr++;
     }
     if ($ctr > 0) {
         $this->view->reminders = $ctr;
     }
     // VISITS
     //$this->_visit = null;
     if (!$visitId > 0) {
         return;
     }
     $visit = new Visit();
     $visit->encounter_id = (int) $visitId;
     $visit->populate();
     $this->_visit = $visit;
     $this->view->visit = $this->_visit;
 }
 public function listTeamJsonAction()
 {
     $this->_helper->autoCompleteDojo(array());
     $patientId = (int) $this->_getParam("patientId");
     $patient = new Patient();
     $patient->personId = $patientId;
     $patient->populate();
     $patient->person->populate();
     $db = Zend_Registry::get("dbAdapter");
     $dbSelect = $db->select()->from("patient")->where("teamId = ?", $patient->teamId);
     $patientIterator = $patient->getIterator($dbSelect);
     foreach ($patientIterator as $pat) {
         $tmp = array();
         $tmp['id'] = $pat->person_id;
         $tmp['data'][] = $pat->person->getDisplayName();
         $tmp['data'][] = $pat->email;
         $tmp['data'][] = $pat->phone_number;
         $rows[] = $tmp;
     }
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct(array('rows' => $rows));
 }
 public function processDetailsAction()
 {
     $retval = false;
     $params = $this->_getParam('patient');
     $patientId = (int) $params['personId'];
     if ($patientId > 0) {
         if (!(int) $params['person']['personId'] > 0) {
             $params['person']['personId'] = $patientId;
         }
         if (isset($params['person']['active']) && $params['person']['active']) {
             $params['person']['active'] = 1;
         } else {
             $params['person']['active'] = 0;
         }
         $patient = new Patient();
         $patient->person_id = $patientId;
         $patient->populate();
         $patient->populateWithArray($params);
         $patient->person->person_id = $patientId;
         $patient->person->populate();
         $patient->person->populateWithArray($params['person']);
         $patient->persist();
         $retval = true;
     }
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $data = __('Record updated successfully.');
     if ($retval == false) {
         $data = __('There was an error attempting to update patient details.');
     }
     $json->direct($data);
 }
 protected function _populateAppointmentRow(Appointment $app, array &$columnData, $colIndex, $index, $rowsLen)
 {
     $startToTime = strtotime($app->start);
     $endToTime = strtotime($app->end);
     $tmpStart = date('H:i', $startToTime);
     $tmpEnd = date('H:i', $endToTime);
     $timeLen = ceil(($endToTime - $startToTime) / 60 / self::FILTER_MINUTES_INTERVAL);
     $appointmentId = (int) $app->appointmentId;
     $patientId = (int) $app->patientId;
     $providerId = (int) $app->providerId;
     $roomId = (int) $app->roomId;
     $patient = new Patient();
     $patient->personId = $patientId;
     $patient->populate();
     $id = isset($columnData[$colIndex]['id']) ? $columnData[$colIndex]['id'] : '';
     $columnData[$colIndex]['id'] = $appointmentId;
     if (strlen($id) > 0) {
         $columnData[$colIndex]['id'] .= 'i' . $id;
     }
     $visit = new Visit();
     $visit->appointmentId = $appointmentId;
     $visit->populateByAppointmentId();
     $visitIcon = $visit->visitId > 0 ? '<img src="' . $this->view->baseUrl . '/img/appointment_visit.png" alt="' . __('Visit') . '" title="' . __('Visit') . '" style="border:0px;height:18px;width:18px;margin-left:5px;" />' : '';
     $routingStatuses = array();
     if (strlen($app->appointmentCode) > 0) {
         $routingStatuses[] = __('Mark') . ': ' . $app->appointmentCode;
     }
     $routing = new Routing();
     $routing->personId = $patientId;
     $routing->appointmentId = $appointmentId;
     $routing->providerId = $providerId;
     $routing->roomId = $roomId;
     $routing->populateByAppointments();
     if (strlen($routing->stationId) > 0) {
         $routingStatuses[] = __('Station') . ': ' . $routing->stationId;
     }
     $routingStatus = implode(' ', $routingStatuses);
     $nameLink = $patientId > 0 ? "<a href=\"javascript:showPatientDetails({$patientId});\">{$patient->person->displayName} (#{$patient->recordNumber})</a>" : '';
     $cellRow = 20;
     $height = $cellRow * $timeLen * 1.1;
     $marginTop = 2;
     // compute and adjust margin top and height
     $heightPerMinute = $cellRow / self::FILTER_MINUTES_INTERVAL;
     $map = $columnData[$colIndex]['map'];
     $diff = ($startToTime - $map['start']) / 60;
     if ($diff > 0) {
         $marginTop += $diff * $heightPerMinute;
         $height -= $marginTop;
     }
     $marginLeft = $rowsLen > 1 && $index > 0 ? $index * 250 : 8;
     $zIndex = $colIndex . $index;
     $columnData[$colIndex]['data'][0] .= "<div onmousedown=\"calendarSetAppointmentId('{$appointmentId}')\" ondblclick=\"timeSearchDoubleClicked(this,event)\" appointmentId=\"{$appointmentId}\" visitId=\"{$visit->visitId}\" style=\"float:left;position:absolute;margin-top:{$marginTop}px;height:{$height}px;width:230px;overflow:hidden;border:thin solid black;margin-left:{$marginLeft}px;padding-left:2px;background-color:lightgrey;z-index:{$zIndex};\" class=\"dataForeground\" id=\"event{$appointmentId}\" onmouseover=\"calendarExpandAppointment({$appointmentId},this,{$height});\" onmouseout=\"calendarShrinkAppointment({$appointmentId},this,{$height},{$zIndex});\">{$tmpStart}-{$tmpEnd} {$nameLink} {$visitIcon} <br />{$routingStatus}<div class=\"bottomInner\" id=\"bottomInnerId{$appointmentId}\" style=\"white-space:normal;\">{$app->title}</div></div>";
     $columnData[$colIndex]['userdata']['visitId'] = $visit->visitId;
     $columnData[$colIndex]['userdata']['appointmentId'] = $appointmentId;
     $columnData[$colIndex]['userdata']['length'] = $timeLen;
 }
 public static function refillRequestDatasourceHandler(Audit $auditOrm, $eachTeam = true)
 {
     $ret = array();
     if ($auditOrm->objectClass != 'MedicationRefillRequest') {
         WebVista::debug('Audit:objectClass is not MedicationRefillRequest');
         return $ret;
     }
     $orm = new self();
     $orm->messageId = $auditOrm->objectId;
     if (!$orm->populate()) {
         WebVista::debug('Failed to populate');
         return $ret;
     }
     $objectClass = get_class($orm);
     $messaging = new Messaging();
     $messaging->messagingId = $orm->messageId;
     $messaging->populate();
     $medicationId = (int) $orm->medicationId;
     $providerId = (int) $messaging->providerId;
     $personId = (int) $messaging->personId;
     //if (!$personId > 0 || !$medicationId > 0) {
     if (!$personId > 0) {
         WebVista::debug('Refill request needs manual matching');
         return $ret;
     }
     $patient = new Patient();
     $patient->personId = $personId;
     $patient->populate();
     $teamId = (string) $patient->teamId;
     $alert = new GeneralAlert();
     $alertTable = $alert->_table;
     $msgTable = $messaging->_table;
     $db = Zend_Registry::get('dbAdapter');
     $sqlSelect = $db->select()->from($msgTable, null)->join($alertTable, $alertTable . '.objectId = ' . $msgTable . '.messagingId')->where($msgTable . '.objectType = ?', Messaging::TYPE_EPRESCRIBE)->where($msgTable . '.messageType = ?', 'RefillRequest')->where("{$alertTable}.status = 'new'")->where($alertTable . '.objectClass = ?', $objectClass)->where($alertTable . '.userId = ?', $providerId)->where($msgTable . '.personId = ?', $personId)->limit(1);
     if ($eachTeam) {
         $sqlSelect->where($alertTable . '.teamId = ?', $teamId);
     }
     $alert->populateWithSql($sqlSelect->__toString());
     $messages = array();
     if ($alert->generalAlertId > 0) {
         // existing general alert
         $messages[] = $alert->message;
     } else {
         // new general alert
         $alert->urgency = 'High';
         $alert->status = 'new';
         $alert->dateTime = date('Y-m-d H:i:s');
         $alert->objectClass = $objectClass;
         $alert->objectId = $auditOrm->objectId;
         $alert->userId = (int) $providerId;
         if ($eachTeam) {
             $alert->teamId = $teamId;
         }
     }
     $messages[] = 'Refill request pending. ' . $orm->details;
     $alert->message = implode("\n", $messages);
     return $alert->toArray();
 }
示例#13
0
 public static function generatePID($patient)
 {
     if (!$patient instanceof Patient) {
         $patientId = (int) $patient;
         $patient = new Patient();
         $patient->personId = (int) $patientId;
         $patient->populate();
     }
     $patientId = (int) $patient->personId;
     $person = $patient->person;
     $statistics = PatientStatisticsDefinition::getPatientStatistics($patientId);
     $raceCode = '';
     $race = 'Unknown';
     if (isset($statistics['Race'])) {
         $race = $statistics['Race'];
     }
     if (isset($statistics['race'])) {
         $race = $statistics['race'];
     }
     if (strlen($statistics['Race']) > 0) {
         $race = $statistics['Race'];
         foreach (PatientStatisticsDefinition::listRaceCodes() as $key => $value) {
             if (strtolower($value) == strtolower($race)) {
                 $raceCode = $key;
                 break;
             }
         }
     }
     $addr = new Address();
     foreach ($addr->getIteratorByPersonId($patient->personId) as $address) {
         break;
     }
     $phoneHome = '';
     $phoneBusiness = '';
     $phoneNumber = new PhoneNumber();
     $phoneNumber->personId = $patient->personId;
     foreach ($phoneNumber->phoneNumbers as $phone) {
         if ($phoneHome == '' && $phone['type'] == 'HP') {
             $phoneHome = $phone['number'];
         }
         if ($phoneBusiness == '' && $phone['type'] == 'TE') {
             $phoneBusiness = $phone['number'];
         }
     }
     if ($phoneHome) {
         $phone = $phoneHome;
     }
     if ($phoneBusiness) {
         $phone = $phoneBusiness;
     }
     if (is_array($phone)) {
         $phone = $phone['number'];
     }
     if (substr($phone, 0, 1) == 1) {
         $phone = substr($phone, 1);
     }
     $areaCode = substr($phone, 0, 3);
     $localNumber = substr($phone, 3);
     $ethnic = 'Unknown';
     if (isset($statistics['Ethnicity'])) {
         $ethnic = $statistics['Ethnicity'];
     }
     if (isset($statistics['ethnicity'])) {
         $ethnic = $statistics['ethnicity'];
     }
     $ethnicId = strtoupper(substr($ethnic, 0, 1));
     if ($ethnicId != 'H' && $ethnicId != 'N' && $ethnicId != 'U') {
         $ethnicId = 'U';
     }
     return 'PID|||' . $patient->recordNumber . '^^^MPI&2.16.840.1.113883.19.3.2.1&ISO^MR||' . $person->lastName . '^' . $person->firstName . '||' . date('Ymd', strtotime($person->dateOfBirth)) . '|' . $person->gender . '||' . $raceCode . '^' . $race . '^HL70005|' . $address->line1 . '^^' . $address->city . '^' . $address->state . '^' . $address->zipCode . '^USA^M||^PRN^^^^' . $areaCode . '^' . $localNumber . '|||||||||' . $ethnicId . '^' . $ethnic . '^HL70189';
 }
示例#14
0
 public static function pull()
 {
     $ch = curl_init();
     $ePrescribeURL = Zend_Registry::get('config')->healthcloud->URL;
     $ePrescribeURL .= 'ss-manager.raw/pull-inbounds?apiKey=' . Zend_Registry::get('config')->healthcloud->apiKey;
     curl_setopt($ch, CURLOPT_URL, $ePrescribeURL);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     $output = curl_exec($ch);
     $error = '';
     $ret = 0;
     if (!curl_errno($ch)) {
         try {
             $xml = new SimpleXMLElement($output);
             foreach ($xml->data as $messages) {
                 foreach ($messages as $key => $message) {
                     $rawMessage = base64_decode((string) $message->rawMessage);
                     if ($key == 'refillRequest') {
                         $messageId = (string) $message->messageId;
                         $rxReferenceNumber = (string) $message->rxReferenceNumber;
                         $prescriberOrderNumber = (string) $message->prescriberOrderNumber;
                         $auditId = 0;
                         $medicationId = 0;
                         $xmlMessage = new SimpleXMLElement($rawMessage);
                         $lastName = (string) $xmlMessage->Body->RefillRequest->Patient->Name->LastName;
                         $firstName = (string) $xmlMessage->Body->RefillRequest->Patient->Name->FirstName;
                         $messageInfo = ' for ' . $lastName . ', ' . $firstName;
                         $description = (string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->DrugDescription;
                         $datePrescribed = date('m/d/Y', strtotime((string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->WrittenDate));
                         $messageInfo .= ' - ' . $description . ' #' . $datePrescribed;
                         if (strlen($prescriberOrderNumber) > 0) {
                             // currently check for medicationId using the prescriberOrderNumber medication_audit
                             $medAudit = explode('_', $prescriberOrderNumber);
                             $medicationId = (int) $medAudit[0];
                             $auditId = isset($medAudit[1]) ? (int) $medAudit[1] : 0;
                         }
                         $medication = new Medication();
                         $medication->medicationId = $medicationId;
                         $medication->populate();
                         $patientId = (int) $medication->personId;
                         $unresolved = 0;
                         // retrieve providerId using SPI
                         $SPI = (string) $xmlMessage->Body->RefillRequest->Prescriber->Identification->SPI;
                         $eprescriber = new EPrescriber();
                         $eprescriber->populateBySPI($SPI);
                         $providerId = (int) $eprescriber->providerId;
                         if (!$patientId > 0) {
                             // PON not set or invalid PON, try to automatch based on name, dob, medication and dates in the refreq, if only one match automatically link with correct PON
                             // retrieve pharmacyId using NCPDPID
                             $NCPDPID = (string) $xmlMessage->Body->RefillRequest->Pharmacy->Identification->NCPDPID;
                             $pharmacy = new Pharmacy();
                             $pharmacy->NCPDPID = $NCPDPID;
                             $pharmacy->populatePharmacyIdWithNCPDPID();
                             $pharmacyId = (string) $pharmacy->pharmacyId;
                             $gender = (string) $xmlMessage->Body->RefillRequest->Patient->Gender;
                             $dob = (string) $xmlMessage->Body->RefillRequest->Patient->DateOfBirth;
                             // retrieve patientId using LastName, FirstName, Gender and DOB
                             $db = Zend_Registry::get('dbAdapter');
                             $sqlSelect = $db->select()->from('person', 'person_id')->where('last_name = ?', $lastName)->where('first_name = ?', $firstName)->where('date_of_birth = ?', date('Y-m-d', strtotime($dob)))->limit(1);
                             if ($row = $db->fetchRow($sqlSelect)) {
                                 $patientId = $row['person_id'];
                             }
                             //trigger_error($sqlSelect->__toString());
                             // $qualifiers = Medication::listQuantityQualifiersMapping(); TODO: since qualifier are ambiguous, temporarily not to use this qualifier
                             $quantity = (string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->Quantity->Value;
                             $sqlSelect = $db->select()->from('medications')->where('description = ?', $description)->where('quantity = ?', $quantity)->where('personId = ?', (int) $patientId)->where('prescriberPersonId = ?', (int) $providerId)->where('pharmacyId = ?', (int) $pharmacyId);
                             $writtenDate = (string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->WrittenDate;
                             if (strlen($writtenDate) > 0) {
                                 $sqlSelect->where('datePrescribed LIKE ?', date('Y-m-d', strtotime($writtenDate)) . '%');
                             }
                             $medicationMatched = false;
                             //trigger_error($sqlSelect->__toString());
                             $rows = $db->fetchAll($sqlSelect);
                             if (count($rows) == 1) {
                                 $medication = new Medication();
                                 $medication->populateWithArray($rows[0]);
                                 $medicationId = $medication->medicationId;
                                 $auditId = Medication::getAuditId($medicationId);
                                 if ($auditId > 0) {
                                     $xmlMessage->Body->RefillRequest->PrescriberOrderNumber = $medicationId . '_' . $auditId;
                                     $rawMessage = $xmlMessage->asXML();
                                 }
                                 //trigger_error($sqlSelect->__toString());
                                 $medicationMatched = true;
                             }
                             $messageInfo = ' (Invalid/Missing PON';
                             if ($patientId > 0 && $medicationMatched) {
                                 $patient = new Patient();
                                 $patient->personId = $patientId;
                                 $patient->populate();
                                 $messageInfo .= ' - automatched to \'' . $patient->displayName . '\' MRN#' . $patient->recordNumber;
                             } else {
                                 $unresolved = 1;
                             }
                             $messageInfo .= ')';
                         }
                         $refillRequest = new MedicationRefillRequest();
                         $refillRequest->messageId = $messageId;
                         $refillRequest->medicationId = $medicationId;
                         $refillRequest->action = '';
                         $refillRequest->status = '';
                         $refillRequest->dateStart = '';
                         $refillRequest->details = 'Re: ' . $rxReferenceNumber;
                         $refillRequest->dateTime = date('Y-m-d H:i:s');
                         // disable audits autoprocess, this was set at CHProcessingDaemon
                         $processedAudits = Audit::$_processedAudits;
                         Audit::$_processedAudits = false;
                         $refillRequest->persist();
                         Audit::$_processedAudits = $processedAudits;
                         $messaging = new Messaging();
                         $messaging->messagingId = $messageId;
                         $messaging->populate();
                         $messaging->messageType = 'RefillRequest';
                         $messaging->objectId = $refillRequest->messageId;
                         $messaging->objectClass = 'MedicationRefillRequest';
                         $messaging->note = 'Refill request received - Re:' . $rxReferenceNumber . $messageInfo;
                         $messaging->auditId = $auditId;
                         $messaging->refills = (string) $message->refills;
                         $messaging->personId = $patientId;
                         $messaging->providerId = $providerId;
                         $messaging->unresolved = $unresolved;
                     } else {
                         if ($key == 'status') {
                             $relatesToMessageId = (string) $message->relatesToMessageId;
                             $messageId = (string) $message->messageId;
                             $code = (string) $message->code;
                             $description = (string) $message->description;
                             $messaging = new Messaging();
                             $messaging->messageType = 'Status';
                             $messaging->note = 'Status received for unknown messageId: ' . $relatesToMessageId;
                             $tmpMsg = new Messaging();
                             $tmpMsg->messagingId = $relatesToMessageId;
                             if ($tmpMsg->populate()) {
                                 // populate for newRx details
                                 $tmpMsg->status = 'Sent and Verified';
                                 $x = explode('(', $tmpMsg->note);
                                 $tmpMsg->note = 'newRx';
                                 if ($tmpMsg->objectClass == 'MedicationRefillResponse') {
                                     $tmpMsg->note = 'Refill response';
                                 }
                                 $tmpMsg->note .= ' sent and verified';
                                 if (isset($x[1])) {
                                     unset($x[0]);
                                     $tmpMsg->note .= ' (' . implode('(', $x);
                                 }
                                 $tmpMsg->unresolved = 0;
                                 $tmpMsg->persist();
                                 $messaging->auditId = $tmpMsg->auditId;
                                 $messaging->objectId = $tmpMsg->objectId;
                                 $messaging->objectClass = $tmpMsg->objectClass;
                                 $messaging->personId = $tmpMsg->personId;
                                 $messaging->providerId = $tmpMsg->providerId;
                                 $xmlTmpMessage = new SimpleXMLElement($tmpMsg->rawMessage);
                                 $lastName = (string) $xmlTmpMessage->Body->NewRx->Patient->Name->LastName;
                                 $firstName = (string) $xmlTmpMessage->Body->NewRx->Patient->Name->FirstName;
                                 $messageInfo = $lastName . ', ' . $firstName;
                                 $drugDescription = (string) $xmlTmpMessage->Body->NewRx->MedicationPrescribed->DrugDescription;
                                 $datePrescribed = date('m/d/Y', strtotime((string) $xmlTmpMessage->Body->NewRx->MedicationPrescribed->WrittenDate));
                                 $messageInfo .= ' - ' . $drugDescription . ' #' . $datePrescribed;
                                 $messaging->note = 'Status received for ' . $messageInfo;
                             }
                             $messaging->note .= "\n" . $code . ':' . $description;
                         } else {
                             if ($key == 'error') {
                                 $relatesToMessageId = (string) $message->relatesToMessageId;
                                 $messageId = (string) $message->messageId;
                                 $code = (string) $message->code;
                                 $description = (string) $message->description;
                                 $messaging = new Messaging();
                                 $messaging->messageType = 'Error';
                                 $messaging->note = 'Error received for unknown messageId: ' . $relatesToMessageId;
                                 $tmpMsg = new Messaging();
                                 $tmpMsg->messagingId = $relatesToMessageId;
                                 if ($tmpMsg->populate()) {
                                     // populate for newRx details
                                     $tmpMsg->status = 'Sent and Verified';
                                     $x = explode('(', $tmpMsg->note);
                                     $tmpMsg->note = 'newRx';
                                     if ($tmpMsg->objectClass == 'MedicationRefillResponse') {
                                         $tmpMsg->note = 'Refill response';
                                     }
                                     $tmpMsg->note .= ' sent and verified';
                                     if (isset($x[1])) {
                                         unset($x[0]);
                                         $tmpMsg->note .= ' (' . implode('(', $x);
                                     }
                                     $tmpMsg->unresolved = 0;
                                     $tmpMsg->persist();
                                     $messaging->auditId = $tmpMsg->auditId;
                                     $messaging->objectId = $tmpMsg->objectId;
                                     $messaging->objectClass = $tmpMsg->objectClass;
                                     $messaging->personId = $tmpMsg->personId;
                                     $messaging->providerId = $tmpMsg->providerId;
                                     $xmlTmpMessage = new SimpleXMLElement($tmpMsg->rawMessage);
                                     $lastName = (string) $xmlTmpMessage->Body->NewRx->Patient->Name->LastName;
                                     $firstName = (string) $xmlTmpMessage->Body->NewRx->Patient->Name->FirstName;
                                     $messageInfo = $lastName . ', ' . $firstName;
                                     $drugDescription = (string) $xmlTmpMessage->Body->NewRx->MedicationPrescribed->DrugDescription;
                                     $datePrescribed = date('m/d/Y', strtotime((string) $xmlTmpMessage->Body->NewRx->MedicationPrescribed->WrittenDate));
                                     $messageInfo .= ' - ' . $drugDescription . ' #' . $datePrescribed;
                                     $messaging->note = 'Error received for ' . $messageInfo;
                                 }
                                 $messaging->note .= "\n" . $code . ':' . $description;
                             } else {
                                 continue;
                             }
                         }
                     }
                     $messaging->rawMessage = $rawMessage;
                     $messaging->rawMessageResponse = base64_decode((string) $message->rawMessageResponse);
                     $messaging->status = 'Received';
                     $messaging->dateStatus = date('Y-m-d H:i:s');
                     $messaging->persist();
                     $ret++;
                 }
             }
             if ($ret > 0) {
                 self::sendPullResponse();
             }
         } catch (Exception $e) {
             $error = __('There was an error, the response couldn\'t be parsed as XML: ' . $output);
             trigger_error($error, E_USER_NOTICE);
         }
     } else {
         $error = __('There was an error connecting to HealthCloud. Please try again or contact the system administrator.');
         trigger_error('Curl error connecting to healthcare: ' . curl_error($ch), E_USER_NOTICE);
     }
     curl_close($ch);
     return $ret;
 }
 public function newRxAction()
 {
     $medicationId = 1077476;
     $data = array();
     $medication = new Medication();
     $medication->medicationId = $medicationId;
     $medication->populate();
     $data['PrescriberOrderNumber'] = $medication->medicationId;
     $medData = array();
     $medData['DrugDescription'] = $medication->description;
     $medData['Strength'] = $medication->strength;
     $medData['StrengthUnits'] = $medication->unit;
     $medData['Quantity'] = $medication->quantity;
     $medData['Directions'] = $medication->directions;
     $medData['Refills'] = $medication->refills;
     $medData['Substitutions'] = $medication->substitution;
     $medData['WrittenDate'] = date('Ymd', strtotime($medication->datePrescribed));
     $data['medication'] = $medData;
     $pharmacy = new Pharmacy();
     $pharmacy->pharmacyId = $medication->pharmacyId;
     $pharmacy->populate();
     $pharmacyData = array();
     $pharmacyData['NCPDPID'] = $pharmacy->NCPDPID;
     $pharmacyData['StoreName'] = $pharmacy->StoreName;
     $pharmacyData['AddressLine1'] = $pharmacy->AddressLine1 . ' ' . $pharmacy->AddressLine2;
     $pharmacyData['City'] = $pharmacy->City;
     $pharmacyData['State'] = $pharmacy->State;
     $pharmacyData['ZipCode'] = $pharmacy->Zip;
     $pharmacyData['PhoneNumber'] = $pharmacy->PhonePrimary;
     $data['pharmacy'] = $pharmacyData;
     $provider = new Provider();
     $provider->personId = $medication->prescriberPersonId;
     $provider->populate();
     $prescriberData = array();
     $prescriberData['DEANumber'] = $provider->deaNumber;
     $prescriberData['SPI'] = $provider->sureScriptsSPI;
     $prescriberData['ClinicName'] = '';
     $prescriberData['LastName'] = $provider->person->lastName;
     $prescriberData['FirstName'] = $provider->person->firstName;
     $prescriberData['Suffix'] = '';
     $address = new Address();
     $address->personId = $provider->personId;
     $address->populateWithPersonId();
     $prescriberData['AddressLine1'] = $address->line1 . ' ' . $address->line2;
     $prescriberData['City'] = $address->city;
     $prescriberData['State'] = 'AZ';
     //$address->state;
     $prescriberData['ZipCode'] = $address->zipCode;
     $phoneNumber = new PhoneNumber();
     $phoneNumber->personId = $provider->personId;
     $phoneNumber->populateWithPersonId();
     $prescriberData['PhoneNumber'] = $phoneNumber->number;
     $data['prescriber'] = $prescriberData;
     $patient = new Patient();
     $patient->personId = $medication->personId;
     $patient->populate();
     $patientData = array();
     $patientData['LastName'] = $patient->person->lastName;
     $patientData['FirstName'] = $patient->person->firstName;
     $patientData['Gender'] = $patient->person->gender;
     $patientData['DateOfBirth'] = date('Ymd', strtotime($patient->person->dateOfBirth));
     $address = new Address();
     $address->personId = $patient->personId;
     $address->populateWithPersonId();
     $patientData['AddressLine1'] = $address->line1 . ' ' . $address->line2;
     $patientData['City'] = $address->city;
     $patientData['State'] = 'AZ';
     //$address->state;
     $patientData['ZipCode'] = $address->zipCode;
     $phoneNumber = new PhoneNumber();
     $phoneNumber->personId = $patient->personId;
     $phoneNumber->populateWithPersonId();
     $patientData['PhoneNumber'] = $phoneNumber->number;
     $data['patient'] = $patientData;
     $postFields = array();
     foreach ($data as $type => $row) {
         if (is_array($row)) {
             foreach ($row as $field => $value) {
                 $key = $type . '[' . $field . ']';
                 $postFields[$key] = $value;
             }
         } else {
             $postFields[$type] = $row;
         }
     }
     $ch = curl_init();
     $ePrescribeURL = Zend_Registry::get('config')->healthcloud->URL;
     $ePrescribeURL .= 'ss-manager.raw/new-rx?apiKey=' . Zend_Registry::get('config')->healthcloud->apiKey;
     curl_setopt($ch, CURLOPT_URL, $ePrescribeURL);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_USERPWD, 'admin:ch3!');
     $output = curl_exec($ch);
     trigger_error('OUTPUT: ' . $output, E_USER_NOTICE);
     $error = "";
     if (!curl_errno($ch)) {
         try {
             $responseXml = simplexml_load_string($output);
             if (isset($responseXml->error)) {
                 $errorCode = (string) $responseXml->error->code;
                 $errorMsg = (string) $responseXml->error->message;
                 if (isset($responseXml->error->errorCode)) {
                     $errorCode = (string) $responseXml->error->errorCode;
                 }
                 if (isset($responseXml->error->errorMsg)) {
                     $errorMsg = (string) $responseXml->error->errorMsg;
                 }
                 $error = $errorMsg;
                 trigger_error('There was an error prescribing new medication, Error code: ' . $errorCode . ' Error Message: ' . $errorMsg, E_USER_NOTICE);
             }
         } catch (Exception $e) {
             $error = __("There was an error connecting to HealthCloud to prescribe new medication. Please try again or contact the system administrator.");
             trigger_error("There was an error prescribeing new medication, the response couldn't be parsed as XML: " . $output, E_USER_NOTICE);
         }
     } else {
         $error = __("There was an error connecting to HealthCloud to prescribe new medication. Please try again or contact the system administrator.");
         trigger_error("Curl error connecting to healthcare prescribed new medication: " . curl_error($ch), E_USER_NOTICE);
     }
     curl_close($ch);
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     if (strlen($error) > 0) {
         $this->getResponse()->setHttpResponseCode(500);
         $json->direct(array('error' => $error));
         return;
     }
     $json->direct(true);
 }
 protected function export2PublicHealth($ids)
 {
     $data = array();
     $data[] = 'FHS|^~\\&';
     $data[] = 'BHS|^~\\&';
     $ctr = count($ids);
     for ($i = 0; $i < $ctr; $i++) {
         $id = (int) $ids[$i];
         if (!isset($this->_session->patientList[$id])) {
             continue;
         }
         $problemList = isset($this->_session->patientList[$id]['problemList']) ? $this->_session->patientList[$id]['problemList'] : array();
         $patient = new Patient();
         $patient->personId = $id;
         $patient->populate();
         $person = $patient->person;
         $dateTime = date('YmdHi');
         $messageDateTime = date('YmdHiO');
         $data[] = 'MSH|^~\\&|CLEARHEALTH||||' . $dateTime . '||ADT^A04|' . $messageDateTime . '|P|2.3.1';
         $dateOfOnset = isset($problemList[0]['dateOfOnset']) ? $problemList[0]['dateOfOnset'] : date('YmdHis');
         $data[] = 'EVN||' . date('YmdHi', strtotime($dateOfOnset));
         // Address
         $address = new Address();
         $address->personId = $id;
         $addressIterator = $address->getIteratorByPersonId();
         foreach ($addressIterator as $address) {
             break;
             // retrieves the top address
         }
         // Telecom
         $phone = null;
         $phoneNumber = new PhoneNumber();
         $phoneNumber->personId = $id;
         foreach ($phoneNumber->getPhoneNumbers(false) as $phone) {
             break;
             // retrieves the top phone
         }
         $telecom = '';
         if ($phone && strlen($phone['number']) > 0) {
             $telecom = $phone['number'];
         }
         $data[] = 'PID|1||' . $patient->recordNumber . '||' . strtoupper($person->lastName) . '^' . strtoupper($person->firstName) . '^' . strtoupper($person->middleName) . '||' . date('Ymd', strtotime($person->dateOfBirth)) . '|' . $person->gender . '||U|' . $address->line1 . '^' . $address->line2 . '^' . $address->city . '^' . $address->state . '^' . $address->zipCode . '^US||' . $telecom;
         $visit = new Visit();
         $visit->patientId = $id;
         $visit->populateLatestVisit();
         $data[] = 'PV1|1|O||R||||||||||||||||||||||||||||||||||||||||' . date('YmdHis', strtotime($visit->dateOfTreatment));
         foreach ($problemList as $key => $problem) {
             $data[] = 'DG1|' . ($key + 1) . '||' . $problem['code'] . '^' . $problem['code'] . ' ' . $problem['codeTextShort'] . '^I9C|||F|||||||||1';
         }
     }
     $data[] = 'BTS|' . $ctr;
     $data[] = 'FTS|1';
     $filename = 'ph_' . uniqid('') . '.er7';
     return array('filename' => $filename, 'data' => $data);
 }
 protected function generateEventColumnData($columnIndex)
 {
     $columnIndex = (int) $columnIndex;
     $columnData = array();
     $scheduleEventIterator = new ScheduleEventIterator();
     $appointmentIterator = new AppointmentIterator();
     if (!isset($this->getCurrentDisplayFilter()->columns[$columnIndex])) {
         throw new Exception(__("Cannot generate column with that index, there is no filter defined for that column Index: ") . $columnIndex);
     }
     $this->_session->currentAppointments[$columnIndex] = array();
     $filter = $this->getCurrentDisplayFilter();
     $filterTimeStart = strtotime($filter->start);
     $filterTimeEnd = strtotime($filter->end);
     $paramFilters = $filter->columns[$columnIndex];
     if (isset($paramFilters['dateFilter'])) {
         $filter->date = date('Y-m-d', strtotime($paramFilters['dateFilter']));
     }
     $paramFilters['start'] = $filter->date . ' ' . $filter->start;
     $paramFilters['end'] = $filter->date . ' ' . $filter->end;
     $paramFilters['start'] = $filter->date . ' ' . $filter->start;
     $paramFilters['end'] = $filter->date . ' 23:59:59';
     $scheduleEventIterator->setFilter($paramFilters);
     // we need to get the length of time to create number of rows in the grid
     $timeLen = ($filterTimeEnd - $filterTimeStart) / 60 / $filter->increment;
     for ($i = 0; $i <= $timeLen; $i++) {
         $row = array();
         // assign row id as rowNumber and columnIndex
         $row['id'] = $i . $columnIndex;
         $row['data'][0] = '';
         $columnData[$i] = $row;
     }
     $filterToTimeStart = strtotime($paramFilters['start']);
     $appointmentIterator->setFilter($paramFilters);
     // hold the temporary data counter
     $tmpDataCtr = array();
     $colMultiplier = 1;
     $patient = new Patient();
     $room = new Room();
     $zIndex = 0;
     foreach ($appointmentIterator as $row) {
         $startToTime = strtotime($row->start);
         $endToTime = strtotime($row->end);
         $tmpStart = date('H:i', $startToTime);
         $tmpEnd = date('H:i', $endToTime);
         $timeLen = ($endToTime - $startToTime) / 60 / $filter->increment;
         $tmpIndex = ($startToTime - $filterToTimeStart) / 60 / $filter->increment;
         if (!isset($columnData[$tmpIndex])) {
             break;
         }
         $index = $tmpIndex;
         for ($j = 1; $j <= $timeLen; $j++) {
             if (!isset($columnData[$index])) {
                 break;
             }
             $index++;
         }
         $j--;
         $height = 20 * $j * 1.1;
         $marginLeft = 8;
         $multiplier = 1;
         // generate ranges code inside if ($multiplier === 1) block
         $incTime = $startToTime;
         $ranges = array();
         for ($ctr = 1; $ctr <= $timeLen; $ctr++) {
             $ranges[] = date('H:i', $incTime);
             $incTime = strtotime("+{$filter->increment} minutes", $incTime);
         }
         // check for appointment intersection
         foreach ($tmpDataCtr as $keyCtr => $dataCtr) {
             if (in_array($tmpStart, $dataCtr['ranges'])) {
                 // merge the ranges if we need to have a nested multiple bookings
                 // uncomment if this is not the case and move the generate ranges to its proper location for code optimization
                 $tmpDataCtr[$keyCtr]['ranges'] = array_merge($dataCtr['ranges'], $ranges);
                 $tmpDataCtr[$keyCtr]['multiplier']++;
                 $multiplier = $tmpDataCtr[$keyCtr]['multiplier'];
                 break;
             }
         }
         if ($multiplier === 1) {
             $tmpDataCtr[] = array('ranges' => $ranges, 'multiplier' => $multiplier);
         } else {
             $marginLeft = ($multiplier - 1) * 250;
         }
         if ($multiplier > $colMultiplier) {
             $colMultiplier = $multiplier;
         }
         $patient->setPersonId($row->patientId);
         $patient->populate();
         $person = $patient->person;
         $room->setRoomId($row->roomId);
         $room->populate();
         $this->_session->currentAppointments[$columnIndex][$row->appointmentId] = $row;
         $mark = '';
         if (strlen($row->appointmentCode) > 0) {
             $mark = "({$row->appointmentCode})";
         }
         $zIndex++;
         // where to use room?
         $columnData[$tmpIndex]['id'] = $row->appointmentId . 'i' . $columnData[$tmpIndex]['id'];
         $appointmentId = $row->appointmentId;
         $columnData[$tmpIndex]['data'][0] .= "<div style=\"float:left;position:absolute;margin-top:-11.9px;height:{$height}px;width:230px;overflow:hidden;border:thin solid black;margin-left:{$marginLeft}px;padding-left:2px;background-color:lightgrey;z-index:{$zIndex};\" class=\"dataForeground\" id=\"event{$appointmentId}\" onmouseover=\"expandAppointment({$appointmentId},this);\" onmouseout=\"shrinkAppointment({$appointmentId},this,{$height},{$zIndex});\">{$tmpStart}-{$tmpEnd} <a href=\"\">{$person->last_name}, {$person->first_name} (#{$row->patientId})</a> <div class=\"bottomInner\" id=\"bottomInnerId{$appointmentId}\">{$row->title} {$mark}</div></div>";
         $columnData[$tmpIndex]['userdata']['appointmentId'] = $row->appointmentId;
     }
     $columnData[0]['userdata']['colMultiplier'] = $colMultiplier;
     $columnData[0]['userdata']['providerId'] = $paramFilters['providerId'];
     $roomId = 0;
     if (isset($paramFilters['roomId'])) {
         $roomId = $paramFilters['roomId'];
     }
     $columnData[0]['userdata']['roomId'] = $roomId;
     foreach ($scheduleEventIterator as $event) {
         $x = explode(' ', $event->start);
         $eventTimeStart = strtotime($x[1]);
         $x = explode(' ', $event->end);
         $eventTimeEnd = strtotime($x[1]);
         // get the starting index
         $index = ($eventTimeStart - $filterTimeStart) / 60 / $filter->increment;
         $tmpIndex = $index;
         $color = $event->provider->color;
         if ($event->roomId > 0 && strlen($event->room->color) > 0) {
             $color = $event->room->color;
         }
         if (substr($color, 0, 1) != '#') {
             $color = '#' . $color;
         }
         while ($eventTimeStart < $eventTimeEnd) {
             $eventDateTimeStart = date('Y-m-d H:i:s', $eventTimeStart);
             $eventTimeStart = strtotime("+{$filter->increment} minutes", $eventTimeStart);
             $columnData[$tmpIndex]['style'] = 'background-color:' . $color . ';border-color:lightgrey;';
             $columnData[$index]['userdata']['title'] = $event->title;
             $tmpIndex++;
         }
     }
     $ret = array();
     $ret['rows'] = $columnData;
     return $ret;
 }
示例#18
0
 protected static function generateRowData($patientId)
 {
     $patient = new Patient();
     $patient->personId = (int) $patientId;
     $patient->populate();
     $person = $patient->person;
     $row = array();
     $row['MRN'] = $patient->recordNumber;
     $row['lastName'] = $person->lastName;
     $row['firstName'] = $person->firstName;
     $row['middleName'] = $person->middleName;
     return $row;
 }
示例#19
0
 public function paymentReceiptAction()
 {
     // d96de46c-be90-45b0-b5f9-0b4abee76483
     $referenceId = $this->_getParam('referenceId');
     $personId = (int) $this->_getParam('personId');
     $visitId = (int) $this->_getParam('visitId');
     $data = $this->_getAttachmentData($referenceId);
     $patient = new Patient();
     $patient->personId = $personId;
     if ($personId > 0) {
         $patient->populate();
     }
     $person = $patient->person;
     $visit = new Visit();
     $visit->visitId = $visitId;
     if ($visitId > 0) {
         $visit->populate();
     }
     $practiceId = (int) $visit->practiceId;
     if (!$practiceId > 0) {
         $buildingId = (int) $visit->buildingId;
         if ($buildingId > 0) {
             $building = new Building();
             $building->buildingId = $buildingId;
             $building->populate();
             $practiceId = (int) $building->practiceId;
         } else {
             $roomId = (int) $visit->roomId;
             if ($roomId > 0) {
                 $room = new Room();
                 $room->roomId = $roomId;
                 $room->populate();
                 $practiceId = (int) $room->building->practiceId;
             }
         }
     }
     $practice = new Practice();
     $practice->practiceId = $practiceId;
     if ($practiceId > 0) {
         $practice->populate();
     }
     $primaryAddress = $practice->primaryAddress;
     $xml = new SimpleXMLElement('<data/>');
     $xmlPractice = $xml->addChild('practice');
     $this->_addChild($xmlPractice, 'name', $practice->name);
     $this->_addChild($xmlPractice, 'primaryLine1', $primaryAddress->line1);
     $primaryCityStateZip = $primaryAddress->city . ' ' . $primaryAddress->state . ' ' . $primaryAddress->postalCode;
     $this->_addChild($xmlPractice, 'primaryCityStateZip', $primaryCityStateZip);
     $this->_addChild($xmlPractice, 'mainPhone', $practice->mainPhone->number);
     $xmlPatient = $xml->addChild('patient');
     $name = $person->firstName . ' ' . $person->middleName . ' ' . $person->lastName;
     $this->_addChild($xmlPatient, 'name', $name);
     $addresses = Address::listAddresses($personId);
     if (isset($addresses[Address::TYPE_BILLING])) {
         $address = $addresses[Address::TYPE_BILLING];
     } else {
         if (isset($addresses[Address::TYPE_HOME])) {
             $address = $addresses[Address::TYPE_HOME];
         } else {
             if (isset($addresses[Address::TYPE_MAIN])) {
                 $address = $addresses[Address::TYPE_MAIN];
             } else {
                 if (isset($addresses[Address::TYPE_SEC])) {
                     $address = $addresses[Address::TYPE_SEC];
                 } else {
                     if (isset($addresses[Address::TYPE_OTHER])) {
                         $address = $addresses[Address::TYPE_OTHER];
                     } else {
                         $address = array_pop($addresses);
                     }
                 }
             }
         }
     }
     $billingCityStateZip = $address->city . ' ' . $address->state . ' ' . $address->postalCode;
     $this->_addChild($xmlPatient, 'billingLine1', $address->line1);
     $this->_addChild($xmlPatient, 'billingCityStateZip', $billingCityStateZip);
     $iterator = new PatientProcedureIterator();
     $iterator->setFilters(array('visitId' => $visitId));
     $procedures = array();
     foreach ($iterator as $row) {
         $procedures[] = $row->code;
     }
     $iterator = new PatientDiagnosisIterator();
     $iterator->setFilters(array('visitId' => $visitId));
     $diagnoses = array();
     foreach ($iterator as $row) {
         $diagnoses[] = $row->code;
     }
     $xmlNotes = $xmlPatient->addChild('notes');
     $note = implode(',', $procedures) . " \t " . implode(',', $diagnoses) . " \t " . date('m/d/y', strtotime($visit->dateOfTreatment));
     $this->_addChild($xmlNotes, 'note', $note);
     $today = date('Y-m-d');
     $todaysTotal = 0;
     $iterator = new PaymentIterator();
     $iterator->setFilters(array('visitId' => $visitId, 'company' => 'System', 'paymentDate' => $today));
     $payments = array();
     foreach ($iterator as $row) {
         $payments[] = $row;
     }
     $iterator->setFilters(array('personId' => $personId, 'unallocated' => true, 'paymentDate' => $today));
     foreach ($iterator as $row) {
         $payments[] = $row;
     }
     foreach ($payments as $row) {
         $xmlPayment = $xmlPatient->addChild('payments');
         $paymentDate = date('m/d/y', strtotime($row->paymentDate));
         $this->_addChild($xmlPayment, 'date', $paymentDate);
         $this->_addChild($xmlPayment, 'description', $row->title . ' .... Thank You');
         $this->_addChild($xmlPayment, 'method', $row->paymentType);
         $amount = (double) $row->amount;
         $todaysTotal += $amount;
         $this->_addChild($xmlPayment, 'amount', '-' . number_format($amount, 2));
         $this->_addChild($xmlPayment, 'insurance', $row->insuranceDisplay);
     }
     $fees = $visit->calculateFees();
     $previousBalance = $fees['total'];
     $this->_addChild($xmlPatient, 'previousBalance', number_format($previousBalance, 2));
     $this->_addChild($xmlPatient, 'todaysTotal', '-' . number_format($todaysTotal, 2));
     $totalDue = $previousBalance - $todaysTotal;
     $this->_addChild($xmlPatient, 'totalDue', number_format($totalDue, 2));
     $totalDueFromPatient = $previousBalance;
     $this->_addChild($xmlPatient, 'totalDueFromPatient', number_format($totalDueFromPatient, 2));
     try {
         $content = ReportBase::mergepdfset($xml, $data);
         $this->getResponse()->setHeader('Content-Type', 'application/pdf');
     } catch (Exception $e) {
         $content = '<script>alert("' . $e->getMessage() . '")</script>';
     }
     $this->view->content = $content;
     $this->render('binary-template');
 }
示例#20
0
 public static function generatePID($patientId, $raw = false)
 {
     $patientId = (int) $patientId;
     $patient = new Patient();
     $patient->personId = $patientId;
     $patient->populate();
     // Patient Statistics
     $statistics = PatientStatisticsDefinition::getPatientStatistics($patientId);
     $pid = array('PID');
     $pid[1] = '';
     // empty
     $pid[2] = '';
     // empty
     $pid3 = array();
     // PID‐3: Patient Identifier List
     $pid3[1] = $patient->recordNumber;
     // PID‐3.1: ID Number
     $pid3[2] = '';
     // empty
     $pid3[3] = '';
     // empty
     $pid34 = array();
     // PID-3.4: Assigning Authority
     $pid34[] = 'MPI';
     // PID-3.4.1: Namespace ID
     $pid34[] = '2.16.840.1.113883.19.3.2.1';
     // PID-3.4.2: Universal ID
     $pid34[] = 'ISO';
     // PID-3.4.3: Universal ID Type
     $pid3[4] = implode('&', $pid34);
     $pid3[5] = 'MR';
     // PID-3.5: ID Number Type
     $pid[3] = implode('^', $pid3);
     $pid[4] = '';
     // empty
     $pid5 = array();
     $pid51 = array();
     // PID-5.1: Family Name
     $pid51[] = $patient->lastName;
     // PID-5.1.1: Surname
     $pid5[] = implode('^', $pid51);
     $pid5[] = $patient->firstName;
     // PID-5.2: Given Name
     $pid[5] = implode('^', $pid5);
     $pid[6] = '';
     // empty
     $pid7 = array();
     $pid7[] = date('Ymd', strtotime($patient->dateOfBirth));
     // PID-7.1: Date of Birth
     $pid[7] = implode('^', $pid7);
     $pid[8] = $patient->gender;
     // PID-8: Administrative Sex
     $pid[9] = '';
     // empty
     $race = '';
     $raceCode = 'HL70005';
     if (isset($statistics['Race'])) {
         $race = $statistics['Race'];
     }
     if (isset($statistics['race'])) {
         $race = $statistics['race'];
     }
     $raceId = '';
     foreach (explode(' ', $race) as $val) {
         $raceId .= strtoupper(substr($val, 0, 1));
     }
     $pid10 = array();
     // PID-10: Race
     $pid10[] = $raceId;
     // PID-10.1: Identifier
     $pid10[] = $race;
     // PID-10.2: Text
     $pid10[] = $raceCode;
     // PID-10.3: Name of Coding System
     $pid[10] = implode('^', $pid10);
     $addr = new Address();
     foreach ($addr->getIteratorByPersonId($patientId) as $address) {
         break;
     }
     $street = $address->line1;
     if (strlen($address->line2) > 0) {
         $street .= ' ' . $address->line2;
     }
     $pid11 = array();
     // PID-11: Patient Address
     $pid111 = array();
     // PID-11.1: Street Address
     $pid111[] = $street;
     // PID-11.1.1: Street or Mailing Address
     $pid11[] = implode('^', $pid111);
     // PID-11.1: Street Address
     $pid11[] = '';
     // empty
     $pid11[] = $address->city;
     // PID-11.3: City
     $pid11[] = $address->state;
     // PID-11.4: State
     $pid11[] = $address->zipCode;
     // PID-11.5: Zip Code
     $pid11[] = 'USA';
     // PID-11.6: Country
     $pid11[] = substr($address->type, 0, 1);
     // PID-11.7: Address Type
     $pid[11] = implode('^', $pid11);
     $pid[12] = '';
     // empty
     $pid13 = array();
     // PID-13: Phone Number-Home
     $pid13[] = '';
     // empty
     $pid13[] = 'PRN';
     // PID-13.2: Telecommunication Use Code = PRN?
     $pid13[] = '';
     // empty
     $pid13[] = '';
     // empty
     $pid13[] = '';
     // empty
     $phoneHome = '';
     $phoneBusiness = '';
     $phoneNumber = new PhoneNumber();
     $phoneNumber->personId = $patient->personId;
     foreach ($phoneNumber->phoneNumbers as $phone) {
         if ($phoneHome == '' && $phone['type'] == 'HP') {
             $phoneHome = $phone['number'];
         }
         if ($phoneBusiness == '' && $phone['type'] == 'TE') {
             $phoneBusiness = $phone['number'];
         }
     }
     if ($phoneHome) {
         $phone = $phoneHome;
     }
     if ($phoneBusiness) {
         $phone = $phoneBusiness;
     }
     if (is_array($phone)) {
         $phone = $phone['number'];
     }
     if (substr($phone, 0, 1) == 1) {
         $phone = substr($phone, 1);
     }
     $areaCode = substr($phone, 0, 3);
     $localNumber = substr($phone, 3);
     $pid13[] = $areaCode;
     // PID-13.6: Area/City Code
     $pid13[] = $localNumber;
     // PID-13.7: Local Number
     $pid[13] = implode('^', $pid13);
     $pid[14] = '';
     // empty
     $pid[15] = '';
     // empty
     $pid[16] = '';
     // empty
     $pid[17] = '';
     // empty
     $pid[18] = '';
     // empty
     $pid[19] = '';
     // empty
     $pid[20] = '';
     // empty
     $pid[21] = '';
     // empty
     $ethnic = 'Unknown';
     $ethnicCode = 'HL70189';
     if (isset($statistics['Ethnicity'])) {
         $ethnic = $statistics['Ethnicity'];
     }
     if (isset($statistics['ethnicity'])) {
         $ethnic = $statistics['ethnicity'];
     }
     $ethnicId = substr($ethnic, 0, 1);
     if ($ethnicId != 'H' && $ethnicId != 'N' && $ethnicId != 'U') {
         $ethnicId = 'U';
     }
     $pid22 = array();
     // PID-22: Ethnic Group
     $pid22[] = $ethnicId;
     // PID-22.1: Identifier (H, N, U)
     $pid22[] = $ethnic;
     // PID-22.2: Text
     $pid22[] = $ethnicCode;
     // PID-22.3: Name of Coding System
     $pid[22] = implode('^', $pid22);
     if ($raw) {
         return $pid;
     }
     return implode('|', $pid);
 }
示例#21
0
    function listItemsAction()
    {
        $eSignIterator = new ESignatureIterator();
        $objectId = (int) $this->_getParam('objectId');
        if ($objectId > 0) {
            $eSignIterator->setFilter($objectId, 'objectId');
        } else {
            $eSignIterator->setFilter((int) Zend_Auth::getInstance()->getIdentity()->personId, 'signList');
        }
        //var_dump($db->query($cnSelect)->fetchAll());exit;
        $baseStr = "<?xml version='1.0' standalone='yes'?><rows></rows>";
        $xml = new SimpleXMLElement($baseStr);
        $currentCat = null;
        $category = null;
        // override the include_path to include controllers path
        set_include_path(realpath(Zend_Registry::get('basePath') . '/application/controllers') . PATH_SEPARATOR . get_include_path());
        foreach ($eSignIterator as $row) {
            $row = $row->toArray();
            $obj = new $row['objectClass']();
            foreach ($obj->_primaryKeys as $key) {
                $obj->{$key} = $row['objectId'];
            }
            if (!$obj->populate()) {
                continue;
            }
            // signing but actual object does not exists
            if ($currentCat != $row['objectClass']) {
                $currentCat = $row['objectClass'];
                $category = $xml->addChild("row");
                $category->addAttribute("style", 'height:20px;');
                $category->addAttribute("id", $row['objectClass']);
                $cell = $category->addChild("cell", call_user_func($currentCat . "::" . "getPrettyName", array()));
                $cell = $category->addChild("cell", '');
                $controllerName = call_user_func($currentCat . "::" . "getControllerName");
                $jumpLink = call_user_func_array($controllerName . "::" . "buildJSJumpLink", array($row['objectId'], $row['signingUserId'], $row['objectClass']));
                //$jumpLink = $this->buildJSJumpLink($row['objectId'],$row['signingUserId'],$row['objectClass']);
                $js = "function jumpLink{$row['objectClass']}(objectId,patientId) {\n{$jumpLink}\n}";
                //				$cell = $category->addChild('cell',$js);
                $userdata = $category->addChild('userdata', $js);
                $userdata->addAttribute('name', 'js');
            }
            $leaf = $category->addChild("row");
            $leaf->addAttribute('id', $row['eSignatureId']);
            $leaf->addChild('cell', $row['dateTime'] . " " . preg_replace('/[<>]/', '', $row['summary']));
            $leaf->addChild('cell', '');
            $userdata = $leaf->addChild('userdata', $row['objectId']);
            $userdata->addAttribute('name', 'objectId');
            // hidden column that will load the correct tab
            //			$leaf->addChild('cell',$row['objectId']); // temporary set to objectId
            //$leaf->addChild('cell',$this->buildJSJumpLink($row['objectId'],$row['signingUserId']));
            // for patientId hidden column, not sure if this is the correct field.
            //$leaf->addChild('cell',$row['signingUserId']);
            $patientId = $obj->personId;
            $userdata = $leaf->addChild('userdata', $patientId);
            $userdata->addAttribute('name', 'patientId');
            //$leaf->addChild('cell',$patientId);
            // add a subrow for other info
            if ($row['objectClass'] == 'Medication') {
                $pharmacyInfo = array();
                // $obj refers to Medication ORM
                if ($obj->isScheduled()) {
                    $pharmacyInfo[] = 'Medication is a controlled substance, it cannot be sent electronically. The Rx will be printed and needs a wet signature before it can be faxed to the pharmacy or handed to the patient.';
                } else {
                    $pharmacy = $obj->pharmacy;
                    if (strlen($pharmacy->StoreName) > 0) {
                        $pharmacyInfo[] = $pharmacy->StoreName;
                        $address = $pharmacy->AddressLine1;
                        if (strlen($pharmacy->AddressLine2) > 0) {
                            $address .= ' ' . $pharmacy->AddressLine2;
                        }
                        $address .= ', ' . $pharmacy->City;
                        $address .= ', ' . $pharmacy->State;
                        $address .= ', ' . $pharmacy->Zip;
                        $pharmacyInfo[] = $address;
                        $phones = array();
                        $phones[] = $pharmacy->PhonePrimary;
                        if (strlen($pharmacy->Fax) > 0) {
                            $phones[] = $pharmacy->Fax;
                        }
                        if (strlen($pharmacy->PhoneAlt1) > 0) {
                            $phones[] = $pharmacy->PhoneAlt1;
                        }
                        if (strlen($pharmacy->PhoneAlt2) > 0) {
                            $phones[] = $pharmacy->PhoneAlt2;
                        }
                        if (strlen($pharmacy->PhoneAlt3) > 0) {
                            $phones[] = $pharmacy->PhoneAlt3;
                        }
                        if (strlen($pharmacy->PhoneAlt4) > 0) {
                            $phones[] = $pharmacy->PhoneAlt4;
                        }
                        if (strlen($pharmacy->PhoneAlt5) > 0) {
                            $phones[] = $pharmacy->PhoneAlt5;
                        }
                        $pharmacyInfo[] = implode(', ', $phones);
                    } else {
                        $pharmacyInfo[] = 'No pharmacy selected';
                    }
                }
                $pharmacyInfo = implode(" <br /> ", $pharmacyInfo);
                $patient = new Patient();
                $patient->personId = $obj->personId;
                $patient->populate();
                $patientInfo = $patient->lastName . ", " . $patient->firstName . " " . strtoupper(substr($patient->middleName, 0, 1)) . " #" . $patient->recordNumber;
                $qualifiers = Medication::listQuantityQualifiersMapping();
                $medicationInfo = array();
                $rxn = $obj->rxReferenceNumber;
                if (strlen($rxn) > 0) {
                    $medicationInfo[] = 'Rx Reference Number: ' . $rxn;
                }
                $medicationInfo[] = 'Description: ' . htmlspecialchars($obj->description);
                $medicationInfo[] = 'Directions: ' . htmlspecialchars($obj->directions);
                $medicationInfo[] = 'Quantity: ' . $obj->quantity . ' ' . $qualifiers[$obj->quantityQualifier];
                //$medicationInfo[] = 'Quantity: '.$obj->quantity.' '.$obj->quantityQualifier;
                $medicationInfo[] = 'Strength: ' . $obj->dose . ' ' . $qualifiers[$obj->quantityQualifier];
                //$medicationInfo[] = 'Strength: '.$obj->dose.' '.$obj->quantityQualifier;
                $medicationInfo[] = 'Days Supply: ' . $obj->daysSupply;
                $refills = $obj->refills;
                if ($obj->prn) {
                    $refills = 'PRN';
                }
                $medicationInfo[] = 'Refills: ' . $refills;
                $substitution = 'Permitted';
                if ($obj->substitution == 0) {
                    $substitution = 'Not Permitted';
                }
                $medicationInfo[] = 'Substitutions: ' . $substitution;
                $medicationInfo[] = 'Date Prescribed: ' . date('Y-m-d', strtotime($obj->datePrescribed));
                //$medicationInfo[] = 'NDC: '.$obj->hipaaNDC;
                //$medicationInfo[] = 'Dosage Form: '.DataTables::getDosageForm($obj->chmedDose);
                //$medicationInfo[] = 'DB Code: '.$obj->pkey;
                $medicationInfo[] = 'Note: ' . htmlspecialchars($obj->comment);
                $medicationInfo = implode(' <br /> ', $medicationInfo);
                $info = '<div style="margin-left:75px;margin-top:-18px;margin-bottom:5px;">
					<fieldset>
						<legend title="' . htmlspecialchars($patientInfo) . '">' . __('Patient') . '</legend>' . htmlspecialchars($patientInfo) . '
					</fieldset>
					<fieldset>
						<legend title="' . htmlspecialchars($pharmacyInfo) . '">' . __('Pharmacy') . '</legend>' . htmlspecialchars($pharmacyInfo) . '
					</fieldset>
					<fieldset title="' . htmlspecialchars($medicationInfo) . '">
						<legend>' . __('Medication') . '</legend>' . htmlspecialchars($medicationInfo) . '
					</fieldset></div>';
                $node = $leaf->addChild('row');
                $guid = NSDR::create_guid();
                $node->addAttribute('id', $guid);
                //				$node->addAttribute('style','vertical-align:top;height:50px;');
                $node->addChild('cell', '<![CDATA[' . $info . ']]>');
                $node->addChild('cell', '');
                $node->addChild('cell', '');
                $node->addChild('cell', '');
            }
        }
        header('content-type: text/xml');
        $this->view->content = $xml->asXml();
        $this->view->content = html_entity_decode($this->view->content);
        file_put_contents('/tmp/esign.xml', $this->view->content);
        $this->render();
    }
示例#22
0
 protected static function _getPatientData($patient, $includeProvider = true, $providerId = null, $roomId = null)
 {
     $maritalStatusMap = array('SEPARATED' => 'A', 'DIVORCED' => 'D', 'MARRIED' => 'M', 'SINGLE' => 'S', 'WIDOWED' => 'W');
     if (!$patient instanceof Patient) {
         $patientId = (int) $patient;
         $patient = new Patient();
         $patient->personId = $patientId;
         $patient->populate();
     }
     $personId = (int) $patient->personId;
     $person = $patient->person;
     $maritalStatus = $person->maritalStatus;
     if (isset($maritalStatusMap[$maritalStatus])) {
         $maritalStatus = $maritalStatusMap[$maritalStatus];
     }
     $ethnicities = array();
     $ethnicities['1'] = 1;
     $ethnicities['Hispanic/Latino'] = 1;
     $ethnicities['2'] = 2;
     $ethnicities['Not Hispanic/Latino'] = 2;
     $ethnicities['3'] = 3;
     $ethnicities['Unreported / Refused to Report'] = 3;
     $races = array();
     $races['A'] = 'A';
     $races['Asian'] = 'A';
     $races['N'] = 'N';
     $races['Native Hawaiian'] = 'N';
     $races['P'] = 'P';
     $races['Other Pacific Islander'] = 'P';
     $races['B'] = 'B';
     $races['Black / African American'] = 'B';
     $races['I'] = 'I';
     $races['American Indian / Alaska Native'] = 'I';
     $races['W'] = 'C';
     $races['White'] = 'C';
     $races['M'] = 'M';
     $races['More than one race'] = 'M';
     $races['E'] = 'E';
     $races['Unreported / Refused to Report'] = 'E';
     $statistics = PatientStatisticsDefinition::getPatientStatistics($personId);
     $race = '';
     if (isset($statistics['Race'])) {
         $race = $statistics['Race'];
     }
     if (isset($statistics['race'])) {
         $race = $statistics['race'];
     }
     $race = isset($races[$race]) ? $races[$race] : 'E';
     $ethnicity = '';
     if (isset($statistics['Ethnicity'])) {
         $ethnicity = $statistics['Ethnicity'];
     }
     if (isset($statistics['ethnicity'])) {
         $ethnicity = $statistics['ethnicity'];
     }
     $ethnicity = isset($ethnicities[$ethnicity]) ? $ethnicities[$ethnicity] : '3';
     $language = '';
     if (isset($statistics['Language'])) {
         $language = $statistics['Language'];
     }
     if (isset($statistics['language'])) {
         $language = $statistics['language'];
     }
     $language = '';
     // temporarily set to empty
     $patientData = array();
     $patientData['recordNumber'] = $patient->recordNumber;
     $patientData['lastName'] = $person->lastName;
     $patientData['firstName'] = $person->firstName;
     $patientData['middleName'] = $person->middleName;
     $patientData['suffix'] = $person->suffix;
     $patientData['dateOfBirth'] = date('Ymd', strtotime($person->dateOfBirth));
     $patientData['gender'] = $person->gender;
     $patientData['race'] = $race;
     $patientData['ethnicity'] = $ethnicity;
     $address = $person->address;
     $patientData['line1'] = $address->line1;
     $patientData['line2'] = $address->line2;
     $patientData['city'] = $address->city;
     $patientData['state'] = $address->state;
     $patientData['zip'] = $address->postalCode;
     $homePhone = '';
     $businessPhone = '';
     $phoneNumber = new PhoneNumber();
     $phoneNumber->personId = $personId;
     $phones = $phoneNumber->getPhoneNumbers(false);
     foreach ($phones as $phone) {
         if ($homePhone == '' && $phone['type'] == 'HP') {
             $homePhone = $phone['number'];
         }
         if ($businessPhone == '' && $phone['type'] == 'TE') {
             $businessPhone = $phone['number'];
         }
         if ($homePhone != '' && $businessPhone != '') {
             break;
         }
     }
     $patientData['homePhone'] = $homePhone;
     $patientData['businessPhone'] = $businessPhone;
     $patientData['language'] = $language;
     $patientData['maritalStatus'] = $maritalStatus;
     $patientData['accountNumber'] = '';
     $patientData['ssn'] = $patient->person->identifierType == 'SSN' ? $patient->identifier : '';
     if (!$includeProvider) {
         return $patientData;
     }
     $data = array();
     $data['patient'] = $patientData;
     if ($providerId === null) {
         $providerId = (int) $patient->defaultProvider;
     }
     $provider = new Provider();
     $provider->personId = $providerId;
     $provider->populate();
     $provider->populate();
     $providerData = array();
     $providerData['id'] = $provider->personId;
     $providerData['lastName'] = $provider->person->lastName;
     $providerData['firstName'] = $provider->person->firstName;
     $providerData['middleName'] = $provider->person->middleName;
     $providerData['suffix'] = $provider->person->suffix;
     $room = new Room();
     if ($roomId !== null && $roomId > 0) {
         $room->roomId = (int) $roomId;
         $room->populate();
         $building = $room->building;
         $practice = $building->practice;
         //trigger_error('room: '.$roomId.':'.$room->name);
     } else {
         $practice = new Practice();
         $building = new Building();
         $practiceId = (int) $patient->person->primaryPracticeId;
         $practice->practiceId = $practiceId;
         $practice->populate();
         //trigger_error('primary practice: '.$practiceId.':'.$practice->name);
     }
     $providerData['practice'] = $practice->name;
     $providerData['building'] = $building->name;
     $providerData['room'] = $room->name;
     $data['provider'] = $providerData;
     return $data;
 }
示例#23
0
 public function populate($patientId, $userId, $visitId)
 {
     $this->_patientId = (int) $patientId;
     $patient = new Patient();
     $patient->personId = $this->_patientId;
     $patient->populate();
     $this->_title = $patient->displayName . ' Healthcare Record';
     $this->patient = $patient;
     $this->_userId = (int) $userId;
     $user = new User();
     $user->personId = $this->_userId;
     $user->populate();
     $this->user = $user;
     $visit = new Visit();
     $visit->visitId = (int) $visitId;
     if ($visit->visitId > 0 && $visit->populate()) {
         $this->visit = $visit;
     }
     $this->building = Building::getBuildingDefaultLocation($this->user->personId);
     $performers = array();
     $problemList = new ProblemList();
     $filters = array();
     $filters['personId'] = $this->_patientId;
     $this->setFiltersDateRange($filters);
     $problems = array();
     $problemListIterator = new ProblemListIterator();
     $problemListIterator->setFilters($filters);
     foreach ($problemListIterator as $problem) {
         $problems[] = $problem;
         $providerId = (int) $problem->providerId;
         if (!isset($performers[$providerId])) {
             $provider = new Provider();
             $provider->personId = $providerId;
             $provider->populate();
             $performers[$providerId] = $provider;
         }
     }
     $this->problemLists = $problems;
     unset($filters['personId']);
     $filters['patientId'] = $this->_patientId;
     $labResults = array();
     $labTests = array();
     $labOrderTests = array();
     $labsIterator = new LabsIterator();
     $labsIterator->setFilters($filters);
     foreach ($labsIterator as $lab) {
         // get the lab order
         $labTestId = (int) $lab->labTestId;
         if (!isset($labTests[$labTestId])) {
             $labTest = new LabTest();
             $labTest->labTestId = (int) $lab->labTestId;
             $labTest->populate();
             $labTests[$labTestId] = $labTest;
         }
         $labTest = $labTests[$labTestId];
         $orderId = (int) $labTest->labOrderId;
         if (!isset($labOrderTests[$orderId])) {
             $orderLabTest = new OrderLabTest();
             $orderLabTest->orderId = $orderId;
             $orderLabTest->populate();
             $labOrderTests[$orderId] = $orderLabTest;
         }
         $orderLabTest = $labOrderTests[$orderId];
         $providerId = (int) $orderLabTest->order->providerId;
         if (!isset($performers[$providerId])) {
             $provider = new Provider();
             $provider->personId = $providerId;
             $provider->populate();
             $performers[$providerId] = $provider;
         }
         if (!isset($labResults[$orderId])) {
             $labResults[$orderId] = array();
             $labResults[$orderId]['results'] = array();
             $labResults[$orderId]['labTest'] = $labTest;
             $labResults[$orderId]['orderLabTest'] = $orderLabTest;
         }
         $labResults[$orderId]['results'][] = $lab;
     }
     $this->labResults = $labResults;
     $this->performers = $performers;
     $this->populateHeader($this->_xml);
     $this->populateBody($this->_xml);
     return $this->_xml->asXML();
 }
示例#24
0
 protected static function _generate4010A1($claimId, array $claim)
 {
     static $ctr = 0;
     static $visits = array();
     static $practices = array();
     static $insurancePrograms = array();
     static $providers = array();
     static $patients = array();
     $claimId = (int) $claimId;
     $claimLine = new ClaimLine();
     $claimLine->populateByClaimId($claimId);
     $visitId = (int) $claimLine->visitId;
     if (!isset($visits[$visitId])) {
         $visit = new Visit();
         $visit->visitId = $visitId;
         $visit->populate();
         $visits[$visitId] = $visit;
     }
     $visit = $visits[$visitId];
     $patientId = (int) $visit->patientId;
     if (!isset($patients[$patientId])) {
         $patient = new Patient();
         $patient->personId = $patientId;
         $patient->populate();
         $patients[$patientId] = $patient;
     }
     $patient = $patients[$patientId];
     $practiceId = (int) $visit->practiceId;
     if (!isset($practices[$practiceId])) {
         $practice = new Practice();
         $practice->practiceId = $practiceId;
         $practice->populate();
         $practices[$practiceId] = $practice;
     }
     $practice = $practices[$practiceId];
     $insuranceProgramId = (int) $visit->activePayerId;
     if (!isset($insurancePrograms[$insuranceProgramId])) {
         $insurance = new InsuranceProgram();
         $insurance->insuranceProgramId = $insuranceProgramId;
         $insurance->populate();
         $insurancePrograms[$insuranceProgramId] = $insurance;
     }
     $insuranceProgram = $insurancePrograms[$insuranceProgramId];
     $providerId = (int) $visit->treatingPersonId;
     if (!isset($providers[$providerId])) {
         $provider = new Provider();
         $provider->personId = $providerId;
         $provider->populate();
         $providers[$providerId] = $provider;
     }
     $provider = $providers[$providerId];
     $billAs = (int) $provider->billAs;
     if ($billAs > 0) {
         $providerId = $billAs;
         if (!isset($providers[$providerId])) {
             $provider = new Provider();
             $provider->personId = $providerId;
             $provider->populate();
             $providers[$providerId] = $provider;
         }
         $provider = $providers[$providerId];
     }
     $subscribers = array();
     $enumeration = new Enumeration();
     $enumeration->populateByUniqueName(InsuranceProgram::INSURANCE_ENUM_NAME);
     $enumerationClosure = new EnumerationClosure();
     foreach ($enumerationClosure->getAllDescendants($enumeration->enumerationId, 1, true) as $enum) {
         $rowset = $enumerationClosure->getAllDescendants($enum->enumerationId, 1, true);
         if ($enum->key == InsuranceProgram::INSURANCE_SUBSCRIBER_ENUM_KEY) {
             foreach ($rowset as $row) {
                 $subscribers[$row->key] = $row->name;
             }
             break;
         }
     }
     $insuredRelationship = new InsuredRelationship();
     $db = Zend_Registry::get('dbAdapter');
     $sqlSelect = $db->select()->from($insuredRelationship->_table)->where('insurance_program_id = ?', (int) $insuranceProgram->insuranceProgramId)->where('person_id = ?', (int) $patientId)->where('active = 1')->order('program_order')->limit(1);
     if ($row = $db->fetchRow($sqlSelect)) {
         $insuredRelationship->populateWithArray($row);
     }
     $subs = $insuredRelationship->subscriber;
     $subscriberAddr = $subs->address;
     $relationship = null;
     $relationshipCode = $insuredRelationship->subscriberToPatientRelationship;
     if (isset($subscribers[$relationshipCode])) {
         $relationship = $subscribers[$relationshipCode];
     }
     if ($relationship === null) {
         $relationship = 'Self';
         $relationshipCode = 18;
         $subs = new Person();
         $subs->personId = $insuredRelationship->personId;
         $subs->populate();
     }
     $subscriber = array('id' => (int) $subs->personId, 'relationship_code' => $relationshipCode, 'group_number' => $insuredRelationship->groupNumber, 'group_name' => $insuredRelationship->groupName, 'relationship' => $relationship, 'last_name' => $subs->lastName, 'first_name' => $subs->firstName, 'middle_name' => $subs->middleName, 'address' => array('line1' => $subscriberAddr->line1, 'line2' => $subscriberAddr->line2, 'city' => $subscriberAddr->city, 'state' => $subscriberAddr->state, 'zip' => $subscriberAddr->zipCode), 'date_of_birth' => date('Ymd', strtotime($subs->dateOfBirth)), 'gender' => $subs->gender, 'contract_type_code' => '', 'contract_amount' => '', 'contract_percent' => '', 'contract_code' => '', 'contract_discount_percent' => '', 'contract_version' => '');
     $practiceAddr = $practice->primaryAddress;
     $room = new Room();
     $room->roomId = (int) $visit->roomId;
     $room->populate();
     $facility = $room->building;
     $phoneNumber = PhoneNumber::autoFixNumber($practice->mainPhone->number);
     $phoneLen = strlen($phoneNumber);
     if ($phoneLen < 10) {
         $phoneNumber = str_pad($phoneNumber, 10, '0', STR_PAD_LEFT);
     } else {
         if ($phoneLen > 10) {
             $phoneNumber = substr($phoneNumber, -10);
         }
     }
     $identifierType = '';
     $identifier = $practice->identifier;
     if (strlen($identifier) > 0) {
         $identifierType = 'XX';
     }
     //24';
     $data = array('hlCount' => ++$ctr);
     $data['practice'] = array('name' => $practice->name, 'identifier_type' => $identifierType, 'identifier' => $identifier, 'address' => array('line1' => $practiceAddr->line1, 'line2' => $practiceAddr->line2, 'city' => $practiceAddr->city, 'state' => $practiceAddr->state, 'zip' => $practiceAddr->zipCode), 'phoneNumber' => $phoneNumber);
     $data['treating_facility'] = array('identifier' => $facility->identifier);
     $dateOfTreatment = date('Ymd', strtotime($visit->dateOfTreatment));
     $payer2Id = $insuranceProgram->insuranceProgramId;
     if (strlen($payer2Id) < 2) {
         $payer2Id = str_pad($payer2Id, 2, '0', STR_PAD_LEFT);
     }
     $identifierType = '';
     $identifier = $provider->person->identifier;
     if (strlen($identifier) > 0) {
         $identifierType = 'XX';
     }
     //34';
     $claimData = array('claim' => $claim, 'patient' => array('date_of_initial_treatment' => $dateOfTreatment, 'date_of_onset' => $dateOfTreatment, 'comment_type' => '', 'comment' => ''), 'treating_facility' => array('facility_code' => $facility->facilityCodeId, 'name' => $facility->name, 'address' => array('line1' => $facility->line1, 'line2' => $facility->line2, 'city' => $facility->city, 'state' => $facility->state, 'zip' => $facility->zipCode)), 'provider' => array('signature_on_file' => 'Y', 'accepts_assignment' => 'A', 'last_name' => $provider->person->lastName, 'first_name' => $provider->person->firstName, 'identifier_type' => $identifierType, 'identifier' => $identifier, 'identifier_2' => ''), 'billing_facility' => array('clia_number' => ''), 'subscriber' => $subscriber, 'clearing_house' => array('credit_max_amount' => '', 'repricing_method' => '', 'allowed_amount' => '', 'savings_amount' => '', 'identifier' => '', 'rate' => '', 'apg_code' => '', 'apg_amount' => '', 'reject_code' => '', 'compliance_code' => '', 'exception_code' => ''), 'referring_provider' => array('last_name' => '', 'first_name' => '', 'referral_type' => '', 'identifier_type' => '', 'identifier' => '', 'taxonomy_code' => ''), 'supervising_provider' => array('last_name' => '', 'first_name' => '', 'identifier_type' => '', 'identifier' => ''), 'payer2' => array('id' => $payer2Id, 'name' => $insuranceProgram->name));
     $clm = array();
     $iterator = new ClaimLineIterator();
     $iterator->setFilters(array('claimId' => $claimId));
     foreach ($iterator as $row) {
         $baseFee = (double) $row->baseFee;
         $adjustedFee = (double) $row->adjustedFee;
         $paid = (double) $row->paid;
         $billed = $row->totalMiscCharge;
         if ($baseFee > 0) {
             $billed += $baseFee - $adjustedFee;
         }
         $balance = abs($billed) - $paid;
         $clm[] = array('claim' => $claimData['claim'], 'patient' => $claimData['patient'], 'claim_line' => array('amount' => $balance, 'diagnosis1' => preg_replace('/[\\.]/', '', $row->diagnosisCode1), 'diagnosis2' => preg_replace('/[\\.]/', '', $row->diagnosisCode2), 'diagnosis3' => preg_replace('/[\\.]/', '', $row->diagnosisCode3), 'diagnosis4' => preg_replace('/[\\.]/', '', $row->diagnosisCode4), 'diagnosis5' => preg_replace('/[\\.]/', '', $row->diagnosisCode5), 'diagnosis6' => preg_replace('/[\\.]/', '', $row->diagnosisCode6), 'diagnosis7' => preg_replace('/[\\.]/', '', $row->diagnosisCode7), 'diagnosis8' => preg_replace('/[\\.]/', '', $row->diagnosisCode8), 'procedure' => $row->procedureCode, 'modifier1' => $row->modifier1, 'modifier2' => $row->modifier2, 'modifier3' => $row->modifier3, 'modifier4' => $row->modifier4, 'units' => str_replace('.00', '', $row->units), 'date_of_treatment' => $dateOfTreatment, 'clia_number' => ''), 'treating_facility' => $claimData['treating_facility'], 'provider' => $claimData['provider'], 'billing_facility' => $claimData['billing_facility'], 'subscriber' => $subscriber, 'clearing_house' => $claimData['clearing_house'], 'referring_provider' => $claimData['referring_provider'], 'supervising_provider' => $claimData['supervising_provider'], 'payer2' => $claimData['payer2']);
     }
     $hl2 = array();
     $hl2[] = array('hlCount' => $ctr, 'hlCount2' => ++$ctr, 'payer' => array('responsibility' => 'P'), 'subscriber' => $subscriber, 'patient' => array('weight' => '', 'last_name' => $patient->lastName, 'first_name' => $patient->firstName), 'responsible_party' => array('last_name' => '', 'first_name' => '', 'address' => array('line1' => '', 'line2' => '', 'city' => '', 'state' => '', 'zip' => '')), 'CLM' => $clm);
     $data['HL2'] = $hl2;
     return $data;
 }
示例#25
0
 public static function handlereFaxSourceData(Audit $audit)
 {
     $data = array();
     if ($audit->objectClass != 'ESignature') {
         return $data;
     }
     $eSignature = new ESignature();
     $eSignature->eSignatureId = $audit->objectId;
     $eSignature->populate();
     if ($eSignature->objectClass != 'Medication') {
         return $data;
     }
     $data['_audit'] = $audit;
     $medication = new Medication();
     $medication->medicationId = $eSignature->objectId;
     $medication->populate();
     $data['transmissionId'] = (int) $medication->medicationId;
     $data['recipients'] = array();
     $patient = new Patient();
     $patient->personId = $medication->personId;
     $patient->populate();
     $pharmacyId = $patient->defaultPharmacyId;
     $provider = new Provider();
     $provider->personId = $medication->prescriberPersonId;
     $provider->populate();
     // recipients MUST be a pharmacy?
     $pharmacy = new Pharmacy();
     $pharmacy->pharmacyId = $pharmacyId;
     $pharmacy->populate();
     //$data['recipients'][] = array('fax'=>$pharmacy->Fax,'name'=>$pharmacy->StoreName,'company'=>$pharmacy->StoreName);
     // temporarily comment out the above recipient and use the hardcoded recipient
     $data['recipients'][] = array('fax' => '6022976632', 'name' => 'Jay Walker', 'company' => 'ClearHealth Inc.');
     $prescription = new Prescription();
     $prescription->prescriberName = $provider->firstName . ' ' . $provider->lastName . ' ' . $provider->title;
     $prescription->prescriberStateLicenseNumber = $provider->stateLicenseNumber;
     $prescription->prescriberDeaNumber = $provider->deaNumber;
     // Practice Info
     $primaryPracticeId = $provider->primaryPracticeId;
     $practice = new Practice();
     $practice->id = $primaryPracticeId;
     $practice->populate();
     $address = $practice->primaryAddress;
     $prescription->practiceName = $practice->name;
     $prescription->practiceAddress = $address->line1 . ' ' . $address->line2;
     $prescription->practiceCity = $address->city;
     $prescription->practiceState = $address->state;
     $prescription->practicePostalCode = $address->postalCode;
     $attachment = new Attachment();
     $attachment->attachmentReferenceId = $provider->personId;
     $attachment->populateWithAttachmentReferenceId();
     if ($attachment->attachmentId > 0) {
         $db = Zend_Registry::get('dbAdapter');
         $sqlSelect = $db->select()->from('attachmentBlobs')->where('attachmentId = ?', (int) $attachment->attachmentId);
         if ($row = $db->fetchRow($sqlSelect)) {
             $tmpFile = tempnam('/tmp', 'ch30_sig_');
             file_put_contents($tmpFile, $row['data']);
             $signatureFile = $tmpFile;
             $prescription->prescriberSignature = $signatureFile;
         }
     }
     $prescription->patientName = $patient->lastName . ', ' . $patient->firstName;
     $address = $patient->homeAddress;
     $prescription->patientAddress = $address->line1 . ' ' . $address->line2;
     $prescription->patientCity = $address->city;
     $prescription->patientState = $address->state;
     $prescription->patientPostalCode = $address->postalCode;
     $prescription->patientDateOfBirth = date('m/d/Y', strtotime($patient->dateOfBirth));
     $prescription->medicationDatePrescribed = date('m/d/Y', strtotime($medication->datePrescribed));
     $prescription->medicationDescription = $medication->description;
     $prescription->medicationComment = $medication->comment;
     $prescription->medicationQuantity = $medication->quantity;
     $prescription->medicationRefills = $medication->refills;
     $prescription->medicationDirections = $medication->directions;
     $prescription->medicationSubstitution = $medication->substitution;
     $prescription->create();
     $filename = $prescription->imageFile;
     $fileType = pathinfo($filename, PATHINFO_EXTENSION);
     $data['files'] = array();
     $contents = file_get_contents($filename);
     unlink($filename);
     $data['files'][] = array('contents' => base64_encode($contents), 'type' => $fileType);
     return $data;
 }
示例#26
0
 public function getClaimDetailsAction()
 {
     $claimId = (int) $this->_getParam('claimId');
     $data = array();
     $claimLine = new ClaimLine();
     $claimLine->claimId = $claimId;
     $claimLine->populateByClaimId();
     $visitId = (int) $claimLine->visitId;
     $visit = new Visit();
     $visit->visitId = $visitId;
     $visit->populate();
     $personId = (int) $visit->patientId;
     $data['claimId'] = $claimId;
     $data['dos'] = substr($visit->dateOfTreatment, 0, 10);
     $data['dateBilled'] = substr($claimLine->dateTime, 0, 10);
     $patient = new Patient();
     $patient->personId = $personId;
     $patient->populate();
     $data['patientId'] = $personId;
     $data['patient'] = $patient->displayName;
     $data['payerId'] = $claimLine->insuranceProgramId;
     $data['facility'] = $visit->facility;
     $checkNos = array('' => array('checkNo' => '', 'unallocated' => ''));
     foreach ($claimLine->checkNumbers as $chk) {
         $checkNos[(int) $chk['paymentId']] = array('checkNo' => $chk['checkNo'], 'unallocated' => (double) $chk['unallocated']);
     }
     $data['checkNos'] = $checkNos;
     $insured = new InsuredRelationship();
     $insured->personId = $personId;
     $data['listPayers'] = $insured->programList;
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct($data);
 }
 public function viewInboundFaxAction()
 {
     $messagingId = (int) $this->_getParam('messagingId');
     $messaging = new Messaging();
     $messaging->messagingId = $messagingId;
     $messaging->populate();
     $inboundFax = $messaging->object;
     if (!$inboundFax instanceof MessagingInboundFax) {
         $this->view->error = __('No additional details');
     } else {
         $this->view->messaging = $messaging;
         $personId = (int) $inboundFax->personId;
         $patient = new Patient();
         if ($personId > 0) {
             $patient->personId = $personId;
             $patient->populate();
         }
         $this->view->patient = $patient;
         $attachment = new Attachment();
         $attachment->attachmentId = $messaging->attachmentId;
         $attachment->populate();
         $this->view->attachment = $attachment;
     }
     $this->render('view-inbound-fax');
 }
 public function transmitEprescriptionAction()
 {
     $medicationId = (int) $this->_getParam('medicationId');
     $medication = new Medication();
     $medication->medicationId = $medicationId;
     $medication->populate();
     //echo $medication->toString();
     //echo $medicationId;
     $data = $medication->toArray();
     $practice = new Practice();
     $practice->practiceId = MainController::getActivePractice();
     $practice->populate();
     $data['practiceName'] = $practice->name;
     $pharmacy = new Pharmacy();
     $pharmacy->pharmacyId = $medication->pharmacyId;
     $pharmacy->populate();
     $data['pharmacy'] = $pharmacy->toArray();
     $prescriber = new Provider();
     $prescriber->personId = $medication->prescriberPersonId;
     $prescriber->populate();
     $prescriber->person->populate();
     $data['prescriber'] = $prescriber->toArray();
     $data['prescriber']['agentFirstName'] = '';
     $data['prescriber']['agentLastName'] = '';
     $data['prescriber']['agentSuffix'] = '';
     $addressIterator = new AddressIterator();
     $addressIterator->setFilters(array('class' => 'person', 'personId' => $prescriber->personId));
     $data['prescriber']['address'] = $addressIterator->first()->toArray();
     $phoneIterator = new PhoneNumberIterator();
     $phoneIterator->setFilters(array('class' => 'person', 'personId' => $prescriber->personId));
     $data['prescriber']['phone'] = $phoneIterator->first()->toArray();
     $patient = new Patient();
     $patient->personId = $medication->personId;
     $patient->populate();
     $data['patient'] = $patient->toArray();
     $phoneIterator->setFilters(array('class' => 'person', 'personId' => $patient->personId));
     $data['patient']['phone'] = $phoneIterator->first()->toArray();
     //var_dump($data);exit;
     $data = $this->makePostArray($data);
     //var_dump($this->makePostArray($data));exit;
     //var_dump($data);exit;
     $transmitEPrescribeURL = Zend_Registry::get('config')->healthcloud->URL;
     $transmitEPrescribeURL .= "SSRX/NewRx?apiKey=" . Zend_Registry::get('config')->healthcloud->apiKey;
     $cookieFile = tempnam(sys_get_temp_dir(), "ssddcookies_");
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $transmitEPrescribeURL);
     curl_setopt($ch, CURLOPT_POST, TRUE);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
     curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
     $output = curl_exec($ch);
     echo $output;
     exit;
 }
示例#29
0
 public function getDetailsAction()
 {
     $personId = (int) $this->_getParam('personId');
     $data = false;
     if ($personId > 0) {
         $patient = new Patient();
         $patient->personId = $personId;
         $patient->populate();
         $data = $patient->toArray();
         $data['phoneNumber'] = $patient->person->phoneNumber->toArray();
         $data['address'] = $patient->person->address->toArray();
         $phones = array();
         foreach ($patient->person->getPhoneNumbers() as $phone) {
             $phones[] = $phone->number;
         }
         $data['phones'] = implode(',', $phones);
         $data['age'] = $patient->person->age;
     }
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct($data);
 }
示例#30
0
 public static function listCharges(array $filters)
 {
     $db = Zend_Registry::get('dbAdapter');
     $sqlSelect = $db->select()->from('claimLines')->join('encounter', 'encounter.encounter_id = claimLines.visitId', array('SUM(claimLines.baseFee) AS totalBaseFee', 'SUM(claimLines.adjustedFee) AS totalAdjustedFee'))->order('claimLines.dateTime DESC')->order('claimLines.claimId DESC')->order('encounter.appointmentId')->group('encounter.encounter_id');
     $sqlSelect = $db->select()->from('encounter')->order('encounter.date_of_treatment DESC');
     $mscSelect = $db->select()->from('misc_charge', array('misc_charge.misc_charge_id AS id', 'misc_charge.amount AS billed', 'CONCAT(\'0\') AS paid', 'CONCAT(\'0\') AS writeOff', 'CONCAT(\'Misc Charge\') AS payer', 'encounter.date_of_treatment AS dateOfTreatment', 'misc_charge.charge_date AS dateBilled', 'CONCAT(patient.last_name,\', \',patient.first_name,\' \',patient.middle_name) AS patientName', 'CONCAT(\'\') AS facility', 'CONCAT(provider.last_name,\', \',provider.first_name,\' \',provider.middle_name) AS providerName'))->join('encounter', 'encounter.encounter_id = misc_charge.encounter_id')->join(array('patient' => 'person'), 'patient.person_id = encounter.patient_id')->join(array('provider' => 'person'), 'provider.person_id = encounter.treating_person_id')->order('misc_charge.charge_date DESC');
     foreach ($filters as $key => $value) {
         switch ($key) {
             case 'dateRange':
                 $sqlSelect->where("encounter.date_of_treatment BETWEEN '{$value['start']} 00:00:00' AND '{$value['end']} 23:59:59'");
                 $mscSelect->where("encounter.date_of_treatment BETWEEN '{$value['start']} 00:00:00' AND '{$value['end']} 23:59:59'");
                 break;
             case 'facilities':
                 // practice, building, room
                 if (!is_array($value)) {
                     $value = array($value);
                 }
                 $facilities = array();
                 foreach ($value as $val) {
                     $facilities[] = 'encounter.practice_id = ' . (int) $val['practice'] . ' AND encounter.building_id = ' . (int) $val['building'] . ' AND encounter.room_id = ' . (int) $val['room'];
                 }
                 $sqlSelect->where(implode(' OR ', $facilities));
                 $mscSelect->where(implode(' OR ', $facilities));
                 break;
             case 'payers':
                 $payers = array();
                 foreach ($value as $payerId) {
                     $payers[] = (int) $payerId;
                 }
                 $payers = implode(',', $payers);
                 $sqlSelect->where('encounter.activePayerId IN (' . $payers . ')');
                 $mscSelect->where('encounter.activePayerId IN (' . $payers . ')');
                 break;
             case 'facility':
                 // practice, building, room
                 $sqlSelect->where('encounter.practice_id = ?', (int) $value['practice']);
                 $sqlSelect->where('encounter.building_id = ?', (int) $value['building']);
                 $sqlSelect->where('encounter.room_id = ?', (int) $value['room']);
                 // practice, building, room
                 $mscSelect->where('encounter.practice_id = ?', (int) $value['practice']);
                 $mscSelect->where('encounter.building_id = ?', (int) $value['building']);
                 $mscSelect->where('encounter.room_id = ?', (int) $value['room']);
                 break;
             case 'insurer':
                 $sqlSelect->where('encounter.activePayerId = ?', (int) $value);
                 $mscSelect->where('encounter.activePayerId = ?', (int) $value);
                 break;
             case 'visitId':
                 $sqlSelect->where('encounter.encounter_id = ?', (int) $value);
                 $mscSelect->where('encounter.encounter_id = ?', (int) $value);
                 break;
             case 'provider':
                 $value = array($value);
             case 'providers':
                 $providers = array();
                 foreach ($value as $providerId) {
                     $providers[] = (int) $providerId;
                 }
                 $providers = implode(',', $providers);
                 $sqlSelect->where('encounter.treating_person_id IN (' . $providers . ')');
                 $mscSelect->where('encounter.treating_person_id IN (' . $providers . ')');
                 break;
             case 'closed':
                 $sqlSelect->where('encounter.closed = ?', (int) $value);
                 $mscSelect->where('encounter.closed = ?', (int) $value);
                 break;
             case 'void':
                 $sqlSelect->where('encounter.void = ?', (int) $value);
                 $mscSelect->where('encounter.void = ?', (int) $value);
                 break;
         }
     }
     $rows = array();
     $visits = array();
     $payers = array();
     $facilities = array();
     $patients = array();
     $providers = array();
     $stmt = $db->query($sqlSelect);
     $stmt->setFetchMode(Zend_Db::FETCH_ASSOC);
     while ($row = $stmt->fetch()) {
         $visit = new Visit();
         $visit->populateWithArray($row);
         $visitId = (int) $visit->visitId;
         $acct = $visit->accountSummary;
         $paid = $acct['payment'];
         $writeoff = $acct['writeoff'];
         $total = $acct['total'];
         $billed = $acct['billed'];
         $balance = $acct['balance'];
         $payerId = isset($acct['claimLine']) ? $acct['claimLine']->insuranceProgramId : $visit->activePayerId;
         if (!isset($payers[$payerId])) {
             $payers[$payerId] = InsuranceProgram::getInsuranceProgram($payerId);
         }
         $patientId = (int) $visit->patientId;
         if (!isset($patients[$patientId])) {
             $patient = new Patient();
             $patient->personId = $patientId;
             $patient->populate();
             $patients[$patientId] = $patient;
         }
         $facilityId = (int) $visit->roomId;
         if (!isset($facilities[$facilityId])) {
             $facilities[$facilityId] = $visit->facility;
         }
         $providerId = (int) $visit->providerId;
         if (!isset($providers[$providerId])) {
             $provider = new Provider();
             $provider->personId = $providerId;
             $provider->populate();
             $providers[$providerId] = $provider;
         }
         $tmp = array();
         $tmp['id'] = $visitId;
         $tmp['total'] = $total;
         $tmp['billed'] = $billed;
         $tmp['paid'] = $paid;
         $tmp['writeOff'] = $writeoff;
         $tmp['balance'] = $balance;
         $tmp['payer'] = $payers[$payerId];
         $tmp['dateOfTreatment'] = $visit->dateOfTreatment;
         $tmp['dateBilled'] = isset($acct['claimLine']) ? $acct['claimLine']->dateTime : $visit->dateOfTreatment;
         $patientName = $patients[$patientId]->personId > 0 ? $patients[$patientId]->person->displayName : '';
         $tmp['patientName'] = $patientName;
         $tmp['facility'] = $facilities[$facilityId];
         $providerName = $providers[$providerId]->personId > 0 ? $providers[$providerId]->person->displayName : '';
         $tmp['providerName'] = $providerName;
         $rows[] = $tmp;
     }
     $stmt = $db->query($mscSelect);
     $stmt->setFetchMode(Zend_Db::FETCH_ASSOC);
     while ($row = $stmt->fetch()) {
         $row['balance'] = (double) $row['billed'] - ((double) $row['paid'] + (double) $row['writeOff']);
         $rows[] = $row;
     }
     return $rows;
 }