model() public static method

Returns the static model of the specified AR class.
public static model ( $className = __CLASS__ ) : Episode
return Episode the static model class
 public function findAll($attributes = '', $values = array())
 {
     // because we are working with a view, we should present the event as the last Biometry from the view
     // we need the patient ID and the last_modified date of the current event
     // $attributes == "event_id = ?" in this case
     $eventData = Event::model()->findByPk($values[0]);
     $episodeData = Episode::model()->findByPk($eventData->episode_id);
     $latestData = $this->findAllBySql("\n\t\t\t\t\t\tSELECT eob.*, '" . $values[0] . "' AS event_id FROM et_ophtroperationnote_biometry eob\n\t\t\t\t\t\t\t\t\t\tWHERE eob.patient_id=" . $episodeData->patient_id . "\n\t\t\t\t\t\t\t\t\t\tAND eob.last_modified_date <= '" . $eventData->last_modified_date . "'\n\t\t\t\t\t\t\t\t\t\tORDER BY eob.last_modified_date\n\t\t\t\t\t\t\t\t\t\tDESC LIMIT 1; ");
     return $latestData;
 }
 /**
  * Collate the data and persist it to the table.
  *
  * @param $id
  *
  * @throws CHttpException
  * @throws Exception
  */
 public function loadData($id)
 {
     $booking = Element_OphTrOperationbooking_Operation::model()->find('event_id=?', array($id));
     $eye = Eye::model()->findByPk($booking->eye_id);
     if ($eye->name === 'Both') {
         throw new CHttpException(400, 'Can\'t display whiteboard for dual eye bookings');
     }
     $eyeLabel = strtolower($eye->name);
     $event = Event::model()->findByPk($id);
     $episode = Episode::model()->findByPk($event->episode_id);
     $patient = Patient::model()->findByPk($episode->patient_id);
     $contact = Contact::model()->findByPk($patient->contact_id);
     $biometryCriteria = new CDbCriteria();
     $biometryCriteria->addCondition('patient_id = :patient_id');
     $biometryCriteria->params = array('patient_id' => $patient->id);
     $biometryCriteria->order = 'last_modified_date DESC';
     $biometryCriteria->limit = 1;
     $biometry = Element_OphTrOperationnote_Biometry::model()->find($biometryCriteria);
     $examination = $event->getPreviousInEpisode(EventType::model()->findByAttributes(array('name' => 'Examination'))->id);
     //$management = new \OEModule\OphCiExamination\models\Element_OphCiExamination_Management();
     //$anterior = new \OEModule\OphCiExamination\models\Element_OphCiExamination_AnteriorSegment();
     $risks = new \OEModule\OphCiExamination\models\Element_OphCiExamination_HistoryRisk();
     if ($examination) {
         //$management = $management->findByAttributes(array('event_id' => $examination->id));
         //$anterior = $anterior->findByAttributes(array('event_id' => $examination->id));
         $risks = $risks->findByAttributes(array('event_id' => $examination->id));
     }
     $labResult = Element_OphInLabResults_Inr::model()->findPatientResultByType($patient->id, '1');
     $allergies = Yii::app()->db->createCommand()->select('a.name as name')->from('patient_allergy_assignment pas')->leftJoin('allergy a', 'pas.allergy_id = a.id')->where("pas.patient_id = {$episode->patient_id}")->order('a.name')->queryAll();
     $allergyString = 'None';
     if ($allergies) {
         $allergyString = implode(',', array_column($allergies, 'name'));
     }
     $operation = Yii::app()->db->createCommand()->select('proc.term as term')->from('et_ophtroperationbooking_operation op')->leftJoin('ophtroperationbooking_operation_procedures_procedures opp', 'opp.element_id = op.id')->leftJoin('proc', 'opp.proc_id = proc.id')->where("op.event_id = {$id}")->queryAll();
     $this->event_id = $id;
     $this->booking = $booking;
     $this->eye_id = $eye->id;
     $this->eye = $eye;
     $this->predicted_additional_equipment = $booking->special_equipment_details;
     $this->comments = '';
     $this->patient_name = $contact['title'] . ' ' . $contact['first_name'] . ' ' . $contact['last_name'];
     $this->date_of_birth = $patient['dob'];
     $this->hos_num = $patient['hos_num'];
     $this->procedure = implode(',', array_column($operation, 'term'));
     $this->allergies = $allergyString;
     $this->iol_model = $biometry ? $biometry->attributes['lens_description_' . $eyeLabel] : 'Unknown';
     $this->iol_power = $biometry ? $biometry->attributes['iol_power_' . $eyeLabel] : 'none';
     $this->predicted_refractive_outcome = $biometry ? $biometry->attributes['predicted_refraction_' . $eyeLabel] : 'Unknown';
     $this->alpha_blockers = $patient->hasRisk('Alpha blockers');
     $this->anticoagulants = $patient->hasRisk('Anticoagulants');
     $this->alpha_blocker_name = $risks ? $risks->alpha_blocker_name : '';
     $this->anticoagulant_name = $risks ? $risks->anticoagulant_name : '';
     $this->inr = $labResult ? $labResult : 'None';
     $this->save();
 }
 /**
  * Get the current episode for the firm and patient
  *
  * @return Episode
  */
 public function getEpisode()
 {
     return Episode::model()->getCurrentEpisodeByFirm($this->patient->id, $this->firm);
 }
Ejemplo n.º 4
0
 public function save($runValidation = true, $attributes = null, $allow_overriding = false, $save_version = false)
 {
     $previous = Episode::model()->findByPk($this->id);
     if (parent::save($runValidation, $attributes, $allow_overriding, $save_version)) {
         if ($previous && $previous->episode_status_id != $this->episode_status_id) {
             $this->audit('episode', 'change-status', $this->episode_status_id);
         }
         return true;
     }
     return false;
 }
Ejemplo n.º 5
0
 public function actionUpdateepisode($id)
 {
     if (!($this->episode = Episode::model()->findByPk($id))) {
         throw new SystemException('Episode not found: ' . $id);
     }
     if (!$this->checkAccess('OprnEditEpisode', $this->firm, $this->episode) || isset($_POST['episode_cancel'])) {
         $this->redirect(array('patient/episode/' . $this->episode->id));
         return;
     }
     if (!empty($_POST)) {
         if (@$_POST['eye_id'] && !@$_POST['DiagnosisSelection']['disorder_id']) {
             $error = "Please select a disorder for the principal diagnosis";
         } elseif (!@$_POST['eye_id'] && @$_POST['DiagnosisSelection']['disorder_id']) {
             $error = "Please select an eye for the principal diagnosis";
         } else {
             if (@$_POST['eye_id'] && @$_POST['DiagnosisSelection']['disorder_id']) {
                 if ($_POST['eye_id'] != $this->episode->eye_id || $_POST['DiagnosisSelection']['disorder_id'] != $this->episode->disorder_id) {
                     $this->episode->setPrincipalDiagnosis($_POST['DiagnosisSelection']['disorder_id'], $_POST['eye_id']);
                 }
             }
             if ($_POST['episode_status_id'] != $this->episode->episode_status_id) {
                 $this->episode->episode_status_id = $_POST['episode_status_id'];
                 if (!$this->episode->save()) {
                     throw new Exception('Unable to update status for episode ' . $this->episode->id . ' ' . print_r($this->episode->getErrors(), true));
                 }
             }
             $this->redirect(array('patient/episode/' . $this->episode->id));
         }
     }
     $this->patient = $this->episode->patient;
     $this->layout = '//layouts/events_and_episodes';
     $episodes = $this->patient->episodes;
     // TODO: verify if ordered_episodes complete supercedes need for unordered $episodes
     $ordered_episodes = $this->patient->getOrderedEpisodes();
     $legacyepisodes = $this->patient->legacyepisodes;
     $supportserviceepisodes = $this->patient->supportserviceepisodes;
     $site = Site::model()->findByPk(Yii::app()->session['selected_site_id']);
     $this->title = 'Episode summary';
     $this->event_tabs = array(array('label' => 'View', 'href' => Yii::app()->createUrl('/patient/episode/' . $this->episode->id)), array('label' => 'Edit', 'active' => true));
     $status = Yii::app()->session['episode_hide_status'];
     $status[$id] = true;
     Yii::app()->session['episode_hide_status'] = $status;
     $this->editing = true;
     $this->render('episodes', array('title' => empty($episodes) ? '' : 'Episode summary', 'episodes' => $episodes, 'ordered_episodes' => $ordered_episodes, 'legacyepisodes' => $legacyepisodes, 'supportserviceepisodes' => $supportserviceepisodes, 'eventTypes' => EventType::model()->getEventTypeModules(), 'site' => $site, 'current_episode' => $this->episode, 'error' => @$error));
 }
Ejemplo n.º 6
0
 public function testGetEdr_NotSet()
 {
     Yii::app()->session['selected_firm_id'] = 1;
     $patient = Patient::model()->findByPk(1);
     $episode = Episode::model()->findByPk(1);
     $episode->setPrincipalDiagnosis(1, Eye::LEFT);
     $this->assertEquals($patient->getEdr(), 'No diagnosis');
 }
Ejemplo n.º 7
0
 /**
  * return the open episode of the given subspecialty if there is one, null otherwise
  *
  * @param $subspecialty_id
  * @return CActiveRecord|null
  */
 public function getOpenEpisodeOfSubspecialty($subspecialty_id)
 {
     return Episode::model()->getCurrentEpisodeBySubspecialtyId($this->id, $subspecialty_id);
 }
 /**
  * Reset diagnosis data on the event based on the diagnosis set on this element.
  */
 protected function afterSave()
 {
     if (!$this->event->episode->eye && !$this->event->episode->disorder_id) {
         $this->event->episode->setPrincipalDiagnosis($this->disorder_id, $this->eye_id);
         if ($sd = SecondaryDiagnosis::model()->find('patient_id=? and disorder_id=? and eye_id = ?', array($this->event->episode->patient_id, $this->disorder_id, 3))) {
             $this->event->episode->patient->removeDiagnosis($sd->id);
             if (in_array($this->eye_id, array(1, 2))) {
                 $this->event->episode->patient->addDiagnosis($this->disorder_id, $this->eye_id == 1 ? 2 : 1);
             }
         }
     } else {
         if (!SecondaryDiagnosis::model()->find('patient_id=? and disorder_id=? and eye_id in (' . $this->eye_id . ',3)', array($this->event->episode->patient_id, $this->disorder_id))) {
             if (!Episode::model()->find('patient_id=? and disorder_id=? and eye_id in (' . $this->eye_id . ',3)', array($this->event->episode->patient_id, $this->disorder_id))) {
                 $this->event->episode->patient->addDiagnosis($this->disorder_id, $this->eye_id);
             }
         }
     }
     return parent::afterSave();
 }
Ejemplo n.º 9
0
 /**
  * @covers Episode::model
  */
 public function testModel()
 {
     $this->assertEquals('Episode', get_class(Episode::model()), 'Class name should match model.');
 }
Ejemplo n.º 10
0
 /**
  * @param $episodeId
  * @param $userId
  * @param $examination
  * @param $examinationEvent
  * @throws \CDbException
  */
 protected function createMessage($episodeId, $userId, $examination, $examinationEvent)
 {
     if (isset(\Yii::app()->modules['OphCoMessaging']) && ($examination['patient']['comments'] || $examination['patient']['ready_for_second_eye'] === false)) {
         $episode = \Episode::model()->findByPk($episodeId);
         $recipient = \User::model()->findByPk($episode->firm->consultant_id);
         if ($recipient) {
             $sender = \User::model()->findByPk($userId);
             $type = OphCoMessaging_Message_MessageType::model()->findByAttributes(array('name' => 'General'));
             if ($examination['patient']['ready_for_second_eye'] === false) {
                 $ready = 'No';
             } elseif ($examination['patient']['ready_for_second_eye'] === true) {
                 $ready = 'Yes';
             } else {
                 $ready = 'Not Applicable';
             }
             $messageCreator = new MessageCreator($episode, $sender, $recipient, $type);
             $messageCreator->setMessageTemplate('application.modules.OphCoMessaging.views.templates.optom');
             $messageCreator->setMessageData(array('optom' => $examination['op_tom']['name'] . ' (' . $examination['op_tom']['goc_number'] . ')', 'ready' => $ready, 'comments' => $examination['patient']['comments'], 'patient' => $episode->patient));
             $message = $messageCreator->save('', array('event' => $examinationEvent->id));
             $emailSetting = \SettingInstallation::model()->find('`key` = "optom_comment_alert"');
             if ($emailSetting && $emailSetting->value) {
                 $recipients = explode(',', $emailSetting->value);
                 $messageCreator->emailAlert($recipients, 'New Optom Comment', $message->message_text);
             }
         }
     }
 }
Ejemplo n.º 11
0
 public function actionImport($importDir, $archiveDir, $errorDir, $dupDir, $interval = 'PT45M', $pasImport = false)
 {
     $this->importDir = $this->checkSeparator($importDir);
     $this->archiveDir = $this->checkSeparator($archiveDir);
     $this->errorDir = $this->checkSeparator($errorDir);
     $this->dupDir = $this->checkSeparator($dupDir);
     $this->interval = $interval;
     $fhirMarshal = Yii::app()->fhirMarshal;
     $eventType = EventType::model()->find('class_name=:class_name', array(':class_name' => 'OphInVisualfields'));
     if (!$eventType) {
         echo 'Cannot find OphInVisualfields event type, cannot continue' . PHP_EOL;
         die;
     }
     echo 'Processing FMES files...' . PHP_EOL;
     $filenames = glob($this->importDir . '/*.fmes');
     echo count($filenames) . " files to process\n";
     foreach ($filenames as $file) {
         try {
             $basename = basename($file);
             echo $basename . PHP_EOL;
             // First check the file has not already been imported:
             $field = file_get_contents($file);
             $fieldObject = $fhirMarshal->parseXml($field);
             if ($protected_file = ProtectedFile::model()->find('name=:name', array(':name' => $fieldObject->file_reference))) {
                 echo '- ProtectedFile exists (' . $protected_file->id . ')' . PHP_EOL;
                 $this->move($this->dupDir, $file);
                 continue;
             }
             // Extract the patient number
             $matches = array();
             preg_match('/__OE_PATIENT_ID_([0-9]*)__/', $field, $matches);
             if (count($matches) < 2) {
                 echo '- Failed to extract patient ID' . PHP_EOL;
                 $this->move($this->errorDir, $file);
                 continue;
             }
             $match = str_pad($matches[1], 7, '0', STR_PAD_LEFT);
             // Fetch the patient
             if ($pasImport) {
                 $model = new Patient(null);
                 $model->hos_num = $match;
                 $results = $model->search()->getData();
                 $patient = reset($results);
             } else {
                 $patient = Patient::model()->find('hos_num=:hos_num', array(':hos_num' => $match));
             }
             if (!$patient) {
                 echo "- Failed to find patient ({$match})" . PHP_EOL;
                 $this->move($this->errorDir, $file);
                 continue;
             }
             $pid = $patient->id;
             $field = preg_replace('/__OE_PATIENT_ID_([0-9]*)__/', $pid, $field);
             // Convert to measurement
             $resource_type = 'MeasurementVisualFieldHumphrey';
             $service = Yii::app()->service->getService($resource_type);
             $fieldObject = $fhirMarshal->parseXml($field);
             $tx = Yii::app()->db->beginTransaction();
             $ref = $service->fhirCreate($fieldObject);
             $tx->commit();
             $refId = $ref->getId();
             $measurement = OphInVisualfields_Field_Measurement::model()->findByPk($refId);
             $study_datetime = $measurement->study_datetime;
             // Check for existing legacy events
             if (!($episode = Episode::model()->find('legacy = 1 AND patient_id = :patient_id', array(':patient_id' => $pid)))) {
                 echo '- No legacy episode found, creating...';
                 $episode = new Episode();
                 $episode->legacy = 1;
                 $episode->patient_id = $pid;
                 $episode->save();
                 echo 'done' . PHP_EOL;
                 // As there are no previous legacy events, we can create a new event
                 $this->newEvent($episode, $eventType, $measurement);
                 $this->move($this->archiveDir, $file);
             } else {
                 // There is a legacy episode, so there may be unmatched legacy field events
                 $criteria = new CdbCriteria();
                 $criteria->condition = 'event_type_id = :event_type_id and t.deleted = 0 and ep.deleted = 0 and ep.legacy = 1 and ep.patient_id = :patient_id';
                 $criteria->join = 'join episode ep on ep.id = t.episode_id';
                 $criteria->order = 't.event_date desc';
                 $criteria->params = array(':patient_id' => $pid, ':event_type_id' => $eventType->id);
                 if ($this->interval) {
                     // we're looking for all events that are bound to a legacy episode,
                     // for the given patient, looking for the last created test -
                     // this accounts for multiple tests per eye - the implication
                     // being that the newest test overrides the last test for the same eye
                     // (e.g. when a mistake is made and the test is re-ran):
                     // Base time on interval defined by user, a narrow time slot that the test falls within
                     $startCreatedTime = new DateTime($study_datetime);
                     $endCreatedTime = new DateTime($study_datetime);
                     $startCreatedTime->sub(new DateInterval($this->interval));
                     $endCreatedTime->add(new DateInterval($this->interval));
                     $criteria->condition .= ' AND t.event_date >= STR_TO_DATE("' . $startCreatedTime->format('Y-m-d H:i:s') . '", "%Y-%m-%d %H:%i:%s") AND t.event_date <= STR_TO_DATE("' . $endCreatedTime->format('Y-m-d H:i:s') . '", "%Y-%m-%d %H:%i:%s")';
                 }
                 // Of events, there can only be one or none:
                 // FIXME: This can return multiple events, so how do we choose?
                 $events = Event::model()->findAll($criteria);
                 if (count($events) == 1) {
                     echo '- Found existing event (' . $events[0]->id . ')' . PHP_EOL;
                     $element = Element_OphInVisualfields_Image::model()->find('event_id = :event_id', array(':event_id' => $events[0]->id));
                     $side = strtolower($measurement->eye->name);
                     if ($existing = $element->{"{$side}_field"}) {
                         if ($measurement->study_datetime > $existing->study_datetime) {
                             echo "Newer than existing measurement on {$side}, overwriting\n";
                             $element->{"{$side}_field_id"} = $measurement->id;
                             $unattached = $existing;
                         } else {
                             echo "Older than existing measurement on {$side}, ignoring\n";
                             $unattached = $measurement;
                         }
                         // Add dummy reference for the unattached measurement
                         $ref = new MeasurementReference();
                         $ref->patient_measurement_id = $unattached->getPatientMeasurement()->id;
                         $ref->save();
                     } else {
                         echo "No existing measurement on {$side}, adding\n";
                         $element->{"{$side}_field_id"} = $measurement->id;
                     }
                     $element->save();
                     $this->move($this->archiveDir, $file);
                 } elseif (count($events) > 1) {
                     echo '- Found more than one matching event, cannot attach' . PHP_EOL;
                     $this->move($this->errorDir, $file);
                 } else {
                     // No events in match window, so we create a new one
                     $this->newEvent($episode, $eventType, $measurement);
                     $this->move($this->archiveDir, $file);
                 }
             }
         } catch (Exception $ex) {
             echo $ex . PHP_EOL;
             if (@$tx && $tx->active) {
                 echo '- rolling back tx' . PHP_EOL;
                 $tx->rollback();
             }
             $this->move($this->errorDir, $file);
         }
     }
 }
Ejemplo n.º 12
0
    /**
     * @param $patientId
     * @param $side
     * @param int $isAll
     * @return mixed
     */
    public function getOpticDisc($patientId, $side, $isAll = false)
    {
        $criteria = new \CDbCriteria();
        $criteria->select = 'event.id, ophciexamination_opticdisc_cd_ratio.name';
        if ($side == 'right') {
            $criteria->join = 'JOIN event ON event.episode_id = t.id
	JOIN et_ophciexamination_opticdisc ON et_ophciexamination_opticdisc.event_id = event.id
	JOIN ophciexamination_opticdisc_cd_ratio ON et_ophciexamination_opticdisc.right_cd_ratio_id = ophciexamination_opticdisc_cd_ratio.id';
        } elseif ($side == 'left') {
            $criteria->join = 'JOIN event ON event.episode_id = t.id
	JOIN et_ophciexamination_opticdisc ON et_ophciexamination_opticdisc.event_id = event.id
	JOIN ophciexamination_opticdisc_cd_ratio ON et_ophciexamination_opticdisc.left_cd_ratio_id = ophciexamination_opticdisc_cd_ratio.id';
        }
        if ($isAll) {
            $criteria->condition = 't.patient_id = :patient_id and event.deleted=:del';
            $criteria->params = array(":patient_id" => $patientId, ":del" => 0);
        } else {
            $criteria->condition = 't.patient_id = :patient_id and ophciexamination_opticdisc_cd_ratio.name = :name and event.deleted=:del';
            $criteria->params = array(":patient_id" => $patientId, ":name" => "No view", ":del" => 0);
            $criteria->limit = "1";
        }
        $criteria->order = "et_ophciexamination_opticdisc.last_modified_date DESC";
        return \Episode::model()->findAll($criteria);
    }