Example #1
0
 public function load(Connection $connection)
 {
     if (!$connection->isConnected) {
         $connection->Connect();
     }
     if (!$connection->query($this->medicationQuery)) {
         return false;
     } else {
         $result = null;
         $medication = null;
         while ($result = $connection->getObject()) {
             $medication = new Medication();
             $medication->setCommonDose($result->commonDose);
             $medication->setGenericName($result->genericName);
             $medication->setRoute($result->route);
             $medication->setUnit($result->unit);
             $medication->setMedicationID($result->medicationId);
             $medication->setActive($result->active);
             $medication->setConfirmed($result->confirmed);
             $medication->setConfirmedBy($result->confirmedBy);
             array_push($this->medicationList, $medication);
         }
     }
     return true;
 }
 /**
  * Get or Create a Medication instance for the given patient id and item id.
  *
  * @TODO: consider error checking for Medication already existing?
  *
  * @param $patient_id
  * @param $item_id
  *
  * @return Medication
  *
  * @throws Exception
  */
 public function getMedicationForPrescriptionItem($patient_id, $item_id)
 {
     if ($item = OphDrPrescription_Item::model()->with('prescription.event.episode')->findByPk($item_id)) {
         if ($item->prescription->event->episode->patient_id != $patient_id) {
             throw new Exception('prescription item id and patient id must match');
         }
         $medication = new Medication();
         $medication->createFromPrescriptionItem($item);
         return $medication;
     }
 }
 public function run()
 {
     $faker = Faker::create();
     foreach (range(1, 10) as $index) {
         Medication::create([]);
     }
 }
 /**
  * Display the specified patient.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($id)
 {
     $patient = Patient::findOrFail($id);
     $tests = Test::select('tests.id', 'test', 'result', 'diagnosis', 'tests.created_at', 'item')->where('patient_id', '=', $id)->join('billings', 'billings.id', '=', 'tests.test')->get();
     $medications = Medication::select('medications.id', 'prescription', 'dosage', 'start_date', 'end_date', 'item')->where('patient_id', '=', $id)->join('billings', 'billings.id', '=', 'medications.prescription')->get();
     $visit = Visit::where('patient_id', '=', $id)->first();
     return View::make('patients.show', compact('patient', 'tests', 'medications', 'visit'));
 }
 public function editAction()
 {
     $tableName = preg_replace('/[^a-zA-Z]+/', '', $this->_getParam("id", ""));
     $prettyName = preg_replace('/([A-Z]{1})/', ' \\1', substr($tableName, 9));
     $this->view->tableName = $tableName;
     $this->view->prettyName = $prettyName;
     $this->view->chBaseMed24Url = Zend_Registry::get('config')->healthcloud->CHMED->chBaseMed24Url;
     $this->view->chBaseMed24DetailUrl = Zend_Registry::get('config')->healthcloud->CHMED->chBaseMed24DetailUrl;
     $name = Medication::ENUM_ADMIN_SCHED;
     $enumeration = new Enumeration();
     $enumeration->populateByEnumerationName($name);
     $enumerationsClosure = new EnumerationsClosure();
     $rowset = $enumerationsClosure->getAllDescendants($enumeration->enumerationId, 1);
     $scheduleOptions = array();
     $adminSchedules = array();
     foreach ($rowset as $row) {
         $scheduleOptions[] = $row->key;
         $adminSchedules[$row->key] = $row->name;
     }
     $this->view->scheduleOptions = $scheduleOptions;
     $this->view->quantityQualifiers = Medication::listQuantityQualifiersMapping();
     $this->render();
 }
    public static function buildJSJumpLink($objectId, $signingUserId, $objectClass)
    {
        $objectClass = 'Medications';
        // temporarily hard code objectClass based on MainController::getMainTabs() definitions
        $medication = new Medication();
        $medication->medicationId = $objectId;
        $medication->populate();
        $patientId = $medication->personId;
        $js = parent::buildJSJumpLink($objectId, $patientId, $objectClass);
        $js .= <<<EOL

mainTabbar.setOnTabContentLoaded(function(tabId){
\tloadMedication(objectId);
\topenNewMedicationWindow(objectId);
});

EOL;
        return $js;
    }
 public function processSetPonAction()
 {
     $messagingId = $this->_getParam('messagingId');
     $medicationId = (int) $this->_getParam('medicationId');
     $personId = (int) $this->_getParam('personId');
     $ret = false;
     $messaging = new Messaging();
     $messaging->messagingId = $messagingId;
     $messaging->populate();
     //if ($medicationId > 0 && strlen($messaging->rawMessage) > 0) {
     if ($personId > 0 && strlen($messaging->rawMessage) > 0) {
         $xml = new SimpleXMLElement($messaging->rawMessage);
         $auditId = Medication::getAuditId($medicationId);
         if ($medicationId > 0) {
             $xml->Body->RefillRequest->PrescriberOrderNumber = $medicationId . '_' . $auditId;
             $messaging->rawMessage = $xml->asXML();
         } else {
             //$xml->Body->RefillRequest->PrescriberOrderNumber = $personId;
         }
         $messaging->personId = $personId;
         $messaging->auditId = $auditId;
         $messaging->unresolved = 0;
         $messaging->note = str_replace('Missing PON', 'Missing PON - fixed', $messaging->note);
         $messaging->persist();
         $refillRequest = new MedicationRefillRequest();
         $refillRequest->messageId = $messagingId;
         $refillRequest->populate();
         $refillRequest->medicationId = $medicationId;
         $refillRequest->persist();
         $ret = true;
     }
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct($ret);
 }
 public static function handlereFaxAct(Audit $audit, array $sourceData)
 {
     if ($audit->objectClass != 'ESignature') {
         return false;
     }
     $eSignature = new ESignature();
     $eSignature->eSignatureId = $audit->objectId;
     $eSignature->populate();
     if ($eSignature->objectClass != 'Medication') {
         return false;
     }
     $medication = new Medication();
     $medication->medicationId = $eSignature->objectId;
     $medication->populate();
     $audit = $sourceData['_audit'];
     $messaging = new Messaging(Messaging::TYPE_OUTBOUND_FAX);
     $messaging->messagingId = (int) $sourceData['transmissionId'];
     $messaging->transmissionId = $messaging->messagingId;
     $messaging->populate();
     $messaging->objectId = $messaging->messagingId;
     $messaging->objectClass = $audit->objectClass;
     $messaging->status = 'Faxed';
     $messaging->dateStatus = date('Y-m-d H:i:s');
     $messaging->auditId = $audit->auditId;
     // this must be required for retransmission in case of error
     $messaging->persist();
     $efax = new eFaxOutbound();
     $url = Zend_Registry::get('config')->healthcloud->eFax->outboundUrl;
     $url .= '?apiKey=' . Zend_Registry::get('config')->healthcloud->apiKey;
     $efax->setUrl($url);
     $efax->setTransmissionId($sourceData['transmissionId']);
     $efax->setNoDuplicate(eFaxOutbound::NO_DUPLICATE_ENABLE);
     $efax->setDispositionMethod('POST');
     // use the default disposition URL
     $dispositionUrl = Zend_Registry::get('config')->healthcloud->eFax->dispositionUrl;
     $efax->setDispositionUrl($dispositionUrl);
     //$efax->setDispositionMethod('EMAIL');
     //$efax->addDispositionEmail('Arthur Layese','*****@*****.**');
     foreach ($sourceData['recipients'] as $recipient) {
         if ($messaging->resend && strlen($messaging->faxNumber) > 9) {
             // supersedes fax number from messaging
             $recipient['fax'] = $messaging->faxNumber;
         }
         $efax->addRecipient($recipient['fax'], $recipient['name'], $recipient['company']);
     }
     foreach ($sourceData['files'] as $file) {
         $efax->addFile($file['contents'], $file['type']);
     }
     $ret = $efax->send();
     if (!$ret) {
         $messaging->status = 'Fax Error';
         $messaging->note = implode(PHP_EOL, $efax->getErrors());
     } else {
         $messaging->docid = $efax->getDocId();
         $messaging->status = 'Fax Sent';
         $messaging->note = '';
     }
     if ($messaging->resend) {
         $messaging->resend = 0;
     }
     $messaging->retries++;
     $messaging->dateStatus = date('Y-m-d H:i:s');
     $messaging->persist();
     return true;
 }
 /**
  * Remove the specified resource from storage.
  * DELETE /medications/{id}
  *
  * @param  int  $id
  * @return Response
  */
 public function destroy($id)
 {
     $medication = Medication::find($id);
     Medication::destroy($id);
     return Redirect::route('patient-chart-get', $medication->patient_id)->with('global', "Medication record deleted successfully");
 }
Example #10
0
 function editSignItemsAction()
 {
     $eSigIds = Zend_Json::decode($this->_getParam('electronicSignatureIds'));
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     if (strlen($eSigIds) <= 0) {
         $msg = __('No selected items to sign.');
         WebVista::log($msg);
         $this->getResponse()->setHttpResponseCode(500);
         $json->direct(array('error' => $msg));
         return;
     }
     $eSigIds = explode(',', $eSigIds);
     $signature = $this->_getParam('signature');
     foreach ($eSigIds as $eSigId) {
         if (strlen($eSigId) <= 0) {
             continue;
         }
         $esig = new ESignature();
         $esig->eSignatureId = (int) $eSigId;
         $esig->populate();
         $objectClass = $esig->objectClass;
         if ($objectClass == 'Medication') {
             // check for possible eprescribed
             $medication = new Medication();
             $medication->medicationId = (int) $esig->objectId;
             $medication->populate();
             if ($medication->transmit == 'ePrescribe') {
                 $result = $this->_checkCurrentLocation($medication);
                 if ($result !== false) {
                     $this->getResponse()->setHttpResponseCode(500);
                     $json->direct(array('error' => $result));
                     return;
                 }
             }
         }
         $signedDate = date('Y-m-d H:i:s');
         $esig->signedDateTime = $signedDate;
         $obj = new $esig->objectClass();
         $obj->documentId = $esig->objectId;
         $obj->eSignatureId = $esig->eSignatureId;
         try {
             $esig->sign($obj, $signature);
         } catch (Exception $e) {
             $this->getResponse()->setHttpResponseCode(500);
             $json->direct(array('error' => $e->getMessage()));
             return;
         }
         $esig->persist();
         $obj->populate();
         $obj->eSignatureId = $esig->eSignatureId;
         $obj->persist();
     }
 }
?>
</h1>
                    	  				</div>
                                    </td>
                                </tr>
                                
                                
                                	  <tr style="width:100%;">
                                        <td>
                                            <table  width="100%" dir="rtl">
                                                <tr>
                                                  <td style="width:25%;"></td>
                                                  <td style="width:50%;">
                        
                                                        <?php 
$med = new Medication();
echo '<form method="post" action="' . $med->addMedication() . '">';
?>
                                                                    
                                                       <table width="369">
                                                            <tr>
                                                                <td width="100">تاريخ تقديم الخدمة</td>
                                                                <td width="257">
                                                                    ajaaaaaaaaax*
                                                                </td>
                                                            </tr>
                        
                                                            <tr>
                                                              <td>الأدوية الموصوفة</td>
                                                              <td><input name="Medicine" type="text" /></td>
                                                            </tr>
Example #12
0
 protected static function _checkMedication(HealthStatusHandler $handler, $patientId, $audit)
 {
     $ret = false;
     if ($audit->objectClass != 'Medication') {
         return $ret;
     }
     $db = Zend_Registry::get('dbAdapter');
     $medication = new Medication();
     $medication->medicationId = (int) $audit->objectId;
     $medication->populate();
     $s = $medication->description;
     if (preg_match('/avandia/i', $s)) {
         $message = 'Patient may be suitable for referral to Diabetes Counseling';
     } else {
         if (preg_match('/hydrochlorothiazide/i', $s)) {
             $message = 'Patient may be suitable for treatment of hypertension with a diuretic such as Hydrochlorothiazide';
         } else {
             if (preg_match('/lipitor/i', $s)) {
                 $message = 'Patient may benefit from hypercholesteremia drug such as Lipitor';
                 $sqlSelect = $db->select()->from('chmed.basemed24', array('md5', 'vaclass'))->where('pkey = ?', $medication->pkey);
                 $hasAllergy = false;
                 if ($row = $db->fetchRow($sqlSelect)) {
                     $personId = (int) $patientId;
                     $md5 = $row['md5'];
                     $vaclass = $row['vaclass'];
                     // check for allergy interactions
                     do {
                         // regular allergies search
                         $interactionIterator = new BaseMed24InteractionIterator();
                         $interactionIterator->setFilters(array('personId' => $personId, 'md5' => $md5));
                         $regularAllergies = $interactionIterator->toJsonArray('hipaa_ndc', array('tradename', 'fda_drugname', 'notice'));
                         $tmpArray = $regularAllergies;
                         $regularAllergies = array();
                         foreach ($tmpArray as $key => $value) {
                             $hasAllergy = true;
                             break 2;
                         }
                         // drug class search
                         $patientAllergyIterator = new PatientAllergyIterator();
                         $patientAllergyIterator->setFilters(array('patientId' => $personId, 'enteredInError' => 0, 'drugAllergy' => $vaclass, 'reactionType' => 'Drug Class Allergy'));
                         $drugClassAllergies = array();
                         foreach ($patientAllergyIterator as $allergy) {
                             $hasAllergy = true;
                             break 2;
                         }
                         // specific drug search
                         $patientAllergyIterator->setFilters(array('patientId' => $personId, 'enteredInError' => 0, 'drugAllergy' => $md5, 'reactionType' => 'Specific Drug Allergy'));
                         $specificDrugAllergies = array();
                         foreach ($patientAllergyIterator as $allergy) {
                             $hasAllergy = true;
                             break 2;
                         }
                     } while (false);
                 }
                 if ($hasAllergy) {
                     $message .= '. NOTE: Consult patients allergies: Lipitor/Atorvastatin';
                 }
             } else {
                 return $ret;
             }
         }
     }
     self::createHSA($handler, $patientId, $message);
     return true;
 }
Example #13
0
 /**
  * Gets the previous medications linked with items from the prescription events.
  *
  * @return array
  */
 public function get_previous_medications()
 {
     $medicationCriteria = new CDbCriteria(array('order' => 'created_date DESC'));
     $medicationCriteria->addCondition('end_date is not null and end_date < NOW()');
     $medications = $this->patientMedications($medicationCriteria);
     $medicationsFromPrescriptions = $this->prescriptionMedicationIds();
     $prescriptionItems = $this->prescriptionItems($medicationsFromPrescriptions);
     if ($prescriptionItems) {
         foreach ($prescriptionItems as $item) {
             $medication = new Medication();
             $medication->createFromPrescriptionItem($item);
             if ($medication->isPreviousMedication()) {
                 $medications[] = $medication;
             }
         }
     }
     usort($medications, array($this, 'sortMedications'));
     return $medications;
 }
 /**
  * Medication bills helper function
  *
  * @return array
  */
 public function getMedicationBills($id)
 {
     return Medication::select('item', 'type', 'price', 'prescription', 'dosage', 'medications.created_at')->where('medications.visit_id', '=', $this->getVisit($id)->id)->join('billings', 'billings.id', '=', 'prescription')->where('medications.patient_id', '=', $id)->get();
 }
Example #15
0
 public static function sendResponse($data, Messaging $messaging)
 {
     $messageInfo = '';
     if (strlen($data['message']) > 0) {
         $xmlMessage = new SimpleXMLElement($data['message']);
         $lastName = (string) $xmlMessage->Body->RefillRequest->Patient->Name->LastName;
         $firstName = (string) $xmlMessage->Body->RefillRequest->Patient->Name->FirstName;
         $messageInfo = $lastName . ', ' . $firstName;
         $description = (string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->DrugDescription;
         $datePrescribed = date('m/d/Y', strtotime((string) $xmlMessage->Body->RefillRequest->MedicationPrescribed->WrittenDate));
         $messageInfo .= ' - ' . $description . ' #' . $datePrescribed;
     }
     $tmpMessaging = $messaging;
     $messaging = new Messaging();
     //		$messaging->messagingId = $messageId;
     //		$messaging->populate();
     $messaging->messageType = 'RefillResponse';
     $messaging->objectId = $tmpMessaging->messagingId;
     $messaging->objectClass = 'MedicationRefillResponse';
     $messaging->status = 'Sending';
     $messaging->note = 'Sending refill response (' . $messageInfo . ')';
     $messaging->dateStatus = date('Y-m-d H:i:s');
     $messaging->auditId = $tmpMessaging->auditId;
     $messaging->persist();
     if (isset($data['medicationId'])) {
         $medicationId = $data['medicationId'];
         unset($data['medicationId']);
         $medication = new Medication();
         $medication->medicationId = $medicationId;
         if ($medication->populate()) {
             $medData = array();
             $medData['description'] = $medication->description;
             $medData['strength'] = $medication->strength;
             $medData['strengthUnits'] = '00';
             //$medication->unit;
             $medData['quantity'] = $medication->quantity;
             $medData['quantityUnits'] = '00';
             $medData['directions'] = $medication->directions;
             $qualifier = 'R';
             if ($medication->prn) {
                 $qualifier = 'PRN';
             }
             $medData['refills'] = $medication->refills;
             $medData['refillsUnits'] = $qualifier;
             $medData['substitutions'] = $medication->substitution;
             $medData['writtenDate'] = date('Ymd', strtotime($medication->datePrescribed));
             $data['Medication'] = $medData;
         }
     }
     $query = http_build_query($data);
     $ch = curl_init();
     $ePrescribeURL = Zend_Registry::get('config')->healthcloud->URL;
     $ePrescribeURL .= 'ss-manager.raw/receive-response?apiKey=' . Zend_Registry::get('config')->healthcloud->apiKey;
     curl_setopt($ch, CURLOPT_URL, $ePrescribeURL);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
     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 = '';
     $rawMessage = '';
     $messaging->status = 'Sent';
     $messaging->note = 'Refill response pending';
     $messaging->unresolved = 1;
     if (!curl_errno($ch)) {
         try {
             $xml = new SimpleXMLElement($output);
             if (isset($xml->error)) {
                 $errorCode = (string) $xml->error->code;
                 $errorMsg = (string) $xml->error->message;
                 if (isset($xml->error->errorCode)) {
                     $errorCode = (string) $xml->error->errorCode;
                 }
                 if (isset($xml->error->errorMsg)) {
                     $errorMsg = (string) $xml->error->errorMsg;
                 }
                 $error = $errorMsg;
                 trigger_error('There was an error sending refill response, Error code: ' . $errorCode . ' Error Message: ' . $errorMsg, E_USER_NOTICE);
             } else {
                 if (isset($xml->status)) {
                     $messaging->note = 'Refill response awaiting confirmation';
                     if ((string) $xml->status->code == '010') {
                         // value 000 is for free standing error?
                         $messaging->status .= ' and Verified';
                         $messaging->note = 'Refill response sent and verified';
                         $messaging->unresolved = 0;
                     }
                 } else {
                     $error = 'Unrecognized HealthCloud response: ' . $output;
                 }
             }
             if (isset($xml->rawMessage)) {
                 $messaging->rawMessage = base64_decode((string) $xml->rawMessage);
                 $messaging->rawMessageResponse = base64_decode((string) $xml->rawMessageResponse);
             }
         } 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);
     }
     $messaging->note .= ' (' . $messageInfo . ')';
     curl_close($ch);
     $ret = true;
     if (strlen($error) > 0) {
         $messaging->status = 'Error';
         $messaging->note = $error;
         $ret = $error;
     }
     if ($messaging->resend) {
         $messaging->resend = 0;
     }
     $messaging->retries++;
     $messaging->dateStatus = date('Y-m-d H:i:s');
     $messaging->persist();
     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);
 }
    public static function generateTestTetanus()
    {
        $objects = array();
        $person = new Person();
        $person->last_name = 'ClearHealth';
        $person->first_name = 'Test';
        $person->middle_name = 'I';
        $person->active = 1;
        $person->persist();
        $objects['person'] = $person;
        $patient = new Patient();
        $patient->person->_cascadePersist = false;
        // to avoid persist() calls on person
        $patient->person_id = $person->person_id;
        $patient->recordNumber = 1000;
        $patient->persist();
        $objects['patient'] = $patient;
        $medication = new Medication();
        $medication->_shouldAudit = false;
        // do not audit
        $medication->hipaaNDC = 'hipaaNDC';
        $medication->personId = $patient->person_id;
        $medication->persist();
        $objects['medication'] = $medication;
        $audit = new Audit();
        $audit->_ormPersist = true;
        $audit->objectClass = get_class($medication);
        $audit->objectId = $medication->medicationId;
        $audit->dateTime = date('Y-m-d H:i:s');
        $audit->type = WebVista_Model_ORM::REPLACE;
        $audit->userId = (int) Zend_Auth::getInstance()->getIdentity()->personId;
        $audit->persist();
        $objects['audit'] = $audit;
        $handler = new HealthStatusHandler();
        $handler->name = 'Tetanus Shots Handler ' . NSDR::create_guid();
        $handler->active = 1;
        $handler->timeframe = '+1 month';
        //$handler->condition = $audit->auditId;
        $handlerName = Handler::normalizeHandlerName($handler->name);
        $handler->handlerObject = <<<EOL

class {$handlerName}HealthStatusHandlerObject extends HealthStatusHandlerObjectAbstract {
\t//abstract requires at least this method
\tpublic static function matchAudit(HealthStatusHandler \$handler,Audit \$auditOrm) {
\t\t// check if the patientId of the item referenced by the audit is subscribed to the handler, if not return false (no match)
\t\t\$objectClass = \$auditOrm->objectClass;
\t\t\$obj = new \$objectClass();
\t\tforeach (\$obj->_primaryKeys as \$key) {
\t\t\t\$obj->\$key = \$auditOrm->objectId;
\t\t}
\t\t\$obj->populate();
\t\t\$patientId = \$obj->personId;
\t\tif (!HealthStatusHandlerPatient::isPatientSubscribed(\$handler->healthStatusHandlerId,\$patientId)) {
\t\t\treturn false;
\t\t}
\t\tif (\$auditOrm->objectClass == '{$audit->objectClass}' && \$auditOrm->type == '{$audit->type}') {
\t\t\treturn true;
\t\t}
\t\treturn false;
\t}

\tpublic static function fulfill(HealthStatusHandler \$handler,\$patientId) {
\t\t// fulfill sees if current patient has any open alerts linked to this handler
\t\t\$alert = new HealthStatusAlert();
\t\t\$alert->populateByHandlerPatientId(\$handler->healthStatusHandlerId,\$patientId);
\t\t// if there are open alerts then calls patientMatch again
\t\tif (strlen(\$alert->status) > 0) {
\t\t\t// if patientMatch returns FALSE then marks alerts as fulfilled if patientMatch return non-false alerts stay as is
\t\t\t// sees if any alerts exist for the patient that are for this handler and marks then as fulfilled if the same condition in patientMatch is reversed
\t\t\tif (self::patientMatch(\$handler,\$patientId) === false) {
\t\t\t\t\$alert->status = 'fulfilled';
\t\t\t\t\$alert->persist();
\t\t\t}
\t\t}
\t}

\tpublic static function patientMatch(HealthStatusHandler \$handler,\$patientId) {
 \t\t// check if the patient does not have any record of a tetanus immunization (preferably by using NSDR)
\t\t// if it has, add the timeframe to the date of that immunization and check if that date is greater than today, if so then return true
\t\t// \$immunization = NSDR::populate(\$patientId.'::com.clearhealth.immunization');
\t\t// temporarily superseded NSDR
\t\t\$alert = new HealthStatusAlert();
\t\t\$alert->populateByHandlerPatientId(\$handler->healthStatusHandlerId,\$patientId);
\t\tif (!strlen(\$alert->status) > 0) {
\t\t\t// no existing alert, return true
\t\t\treturn true;
\t\t}
\t\t// would test to see if the date of a given patients last tetanus shot plus the timeframe is less than today
\t\t// if (strtotime(\$handler->timeframe,strtotime(\$alert->dateTime)) < strtotime(date('m/d/Y h:i A',strtotime('+1 month')))) {
\t\tif (\$alert->status == 'active') {
\t\t\tif (strtotime(\$alert->dateDue) < strtotime(date('m/d/Y h:i A',strtotime('+5 weeks')))) {
\t\t\t\t//self::fulfill(\$handler,\$patientId);
\t\t\t\treturn false;
\t\t\t}
\t\t\t// patientMatch checks if patient 1234 has NOT had a tetanus when date of last tetanus + timeframe < today and generates an alert
\t\t\treturn true;
\t\t}
\t\t/* \$alert->lastOccurence
\t\tif (\$alert->status == 'active' || \$alert->status == 'fulfilled' || \$alert->status == 'ignored') {
\t\t\t// would not match if patient already has an active, fulfilled or ignored alert
\t\t\treturn false;
\t\t}
\t\t*/
\t\treturn true;
\t}
}

EOL;
        $handler->datasource = $handler->generateDefaultDatasource();
        $handler->template = $handler->generateDefaultTemplate();
        $handler->persist();
        $objects['healthStatusHandler'] = $handler;
        // subscribe patient to handler
        $handlerPatient = new HealthStatusHandlerPatient();
        $handlerPatient->healthStatusHandlerId = $handler->healthStatusHandlerId;
        $handlerPatient->personId = $patient->personId;
        $handlerPatient->persist();
        $objects['healthStatusHandlerPatient'] = $handler;
        return $objects;
    }