public function processPrintedRxAction()
 {
     // transmit
     // dateTransmitted
     $medicationIds = explode(',', $this->_getParam('medicationId', ''));
     foreach ($medicationIds as $medicationId) {
         $medicationId = (int) $medicationId;
         if (!$medicationId > 0) {
             continue;
         }
         $medication = new Medication();
         $medication->medicationId = $medicationId;
         $medication->populate();
         $medication->transmit = 'Print';
         $date = date('Y-m-d H:i:s');
         $medication->dateTransmitted = $date;
         $medication->dateBegan = $date;
         $medication->persist();
     }
     $rows = array();
     $rows['msg'] = __('Saved successfully.');
     $data = array();
     $data['rows'] = $rows;
     $json = Zend_Controller_Action_HelperBroker::getStaticHelper('json');
     $json->suppressExit = true;
     $json->direct($data);
 }
 public static function handlerSSAct(Audit $audit, array $sourceData)
 {
     if (!isset($sourceData['_audit']) || $audit->objectClass != 'ESignature') {
         WebVista::log('unable to send: _audit index does not exists or audit objectClass not ESignature ');
         return false;
     }
     $eSignature = new ESignature();
     $eSignature->eSignatureId = $audit->objectId;
     $eSignature->populate();
     if ($eSignature->objectClass != 'Medication' || !strlen($eSignature->signature) > 0) {
         WebVista::log('unable to send: signature is not signed or objectClass not Medication');
         return false;
     }
     $medication = new Medication();
     $medication->medicationId = (int) $eSignature->objectId;
     $medication->populate();
     $medication->dateTransmitted = date('Y-m-d H:i:s');
     $medication->persist();
     $patientInfo = $sourceData['Patient']['lastName'] . ', ' . $sourceData['Patient']['firstName'] . ' ' . $sourceData['Patient']['middleName'] . ' MRN#' . $sourceData['Patient']['fileId'];
     $patientInfo .= ' - ' . $sourceData['Medication']['description'] . ' #' . date('m/d/Y', strtotime($sourceData['Medication']['writtenDate']));
     WebVista::log('patient info: ' . $patientInfo);
     $audit = $sourceData['_audit'];
     unset($sourceData['_audit']);
     $messaging = new Messaging();
     $messaging->messagingId = $sourceData['messageId'];
     $messaging->messageType = 'NewRx';
     $messaging->populate();
     $messaging->objectId = (int) $eSignature->objectId;
     $messaging->objectClass = $audit->objectClass;
     $messaging->status = 'Sending';
     $messaging->note = 'Sending newRx (' . $patientInfo . ')';
     $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();
     if ($messaging->resend && $messaging->pharmacyId > 0) {
         // supersedes pharmacy from messaging
         $pharmacy = new Pharmacy();
         $pharmacy->pharmacyId = $messaging->pharmacyId;
         $pharmacy->populate();
         $pharmacyData = array();
         $pharmacyData['NCPDPID'] = $pharmacy->NCPDPID;
         $pharmacyData['StoreName'] = $pharmacy->StoreName;
         $pharmacyData['addressLine1'] = $pharmacy->AddressLine1;
         $pharmacyData['addressLine2'] = $pharmacy->AddressLine2;
         $pharmacyData['city'] = $pharmacy->City;
         $pharmacyData['state'] = $pharmacy->State;
         $pharmacyData['zip'] = $pharmacy->Zip;
         $pharmacyData['phone'] = $pharmacy->PhonePrimary;
         $pharmacyData['fax'] = '';
         $sourceData['Pharmacy'] = $pharmacyData;
     }
     $query = http_build_query(array('data' => $sourceData));
     $ch = curl_init();
     $ePrescribeURL = Zend_Registry::get('config')->healthcloud->URL;
     $ePrescribeURL .= 'ss-manager.raw/new-rx?apiKey=' . Zend_Registry::get('config')->healthcloud->apiKey;
     WebVista::log('SS URL: ' . $ePrescribeURL);
     WebVista::log('URL Query: ' . $query);
     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);
     curl_setopt($ch, CURLOPT_USERPWD, 'admin:ch3!');
     $output = curl_exec($ch);
     $error = '';
     $messaging->status = 'Sent';
     $messaging->note = 'newRx pending';
     $messaging->unresolved = 1;
     WebVista::log('RESPONSE: ' . $output);
     if (!curl_errno($ch)) {
         try {
             $responseXml = new SimpleXMLElement($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);
             } else {
                 if (isset($responseXml->status)) {
                     $messaging->note = 'newRx awaiting confirmation';
                     if ((string) $responseXml->status->code == '010') {
                         // value 000 is for free standing error?
                         $messaging->status .= ' and Verified';
                         $messaging->note = 'newRx sent and verified';
                         $messaging->unresolved = 0;
                     }
                 } else {
                     $error = 'Unrecognized HealthCloud response: ' . $output;
                 }
             }
             if (isset($responseXml->rawMessage)) {
                 $messaging->rawMessage = base64_decode((string) $responseXml->rawMessage);
                 $messaging->rawMessageResponse = base64_decode((string) $responseXml->rawMessageResponse);
             }
         } 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 prescribing 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);
     }
     $messaging->note .= ' (' . $patientInfo . ')';
     curl_close($ch);
     $ret = true;
     if (strlen($error) > 0) {
         $messaging->status = 'Error';
         $patientInfo = $sourceData['Patient']['lastName'] . ', ' . $sourceData['Patient']['firstName'] . ' ' . $sourceData['Patient']['middleName'] . ' MRN#' . $sourceData['Patient']['fileId'];
         $providerInfo = $sourceData['Prescriber']['lastName'] . ', ' . $sourceData['Prescriber']['firstName'] . ' ' . $sourceData['Prescriber']['middleName'];
         $medicationInfo = $sourceData['Medication']['description'] . ' #' . date('m/d/Y', strtotime($sourceData['Medication']['writtenDate']));
         $messaging->note = $error . ' Patient: ' . $patientInfo . ' Provider: ' . $providerInfo . ' Medication: ' . $medicationInfo;
         $ret = false;
     }
     if ($messaging->resend) {
         $messaging->resend = 0;
     }
     $messaging->retries++;
     $messaging->dateStatus = date('Y-m-d H:i:s');
     $messaging->persist();
     return $ret;
 }
    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;
    }