convertNHS2MySQL() public static méthode

Strings that do not match the NHS format are returned unchanged or are not valid dates.
public static convertNHS2MySQL ( string | array $data, array $fields = null ) : string | array
$data string | array Data containing one or more NHS dates
$fields array Fields (keys) to convert (optional, if empty then all fields are checked for dates)
Résultat string | array
Exemple #1
0
 /**
  * Convert NHS dates to MySQL format.
  * Strings that do not match the NHS format are returned unchanged or are not valid dates.
  *
  * @param string|array $data Data containing one or more NHS dates
  * @param array $fields Fields (keys) to convert (optional, if empty then all fields are checked for dates)
  * @return string|array
  */
 public static function convertNHS2MySQL($data, $fields = null)
 {
     if ($is_string = !is_array($data)) {
         $data = array('dummy' => $data);
     }
     $list = $fields ? $fields : array_keys($data);
     foreach ($list as $key) {
         if (isset($data[$key])) {
             // traverse down arrays to convert nested structures
             if (is_array($data[$key])) {
                 $data[$key] = Helper::convertNHS2MySQL($data[$key], $fields);
             } elseif (is_string($data[$key]) && preg_match(self::NHS_DATE_REGEX, $data[$key])) {
                 $check_date = date_parse_from_format('j M Y', $data[$key]);
                 if (checkdate($check_date['month'], $check_date['day'], $check_date['year'])) {
                     $data[$key] = date('Y-m-d', strtotime($data[$key]));
                 }
             }
         }
     }
     if ($is_string) {
         return $data['dummy'];
     } else {
         return $data;
     }
 }
 /**
  * Perform form data validation.
  *
  * @param $form_data
  *
  * @return array
  */
 public function validate($form_data)
 {
     $errs = array();
     if (!@$form_data['appointment_date']) {
         $errs['appointment_date'] = 'Please enter an appointment date';
     }
     $appointment_date = \Helper::convertNHS2MySQL($form_data['appointment_date']);
     $date_validator = new \OEDateValidator();
     if (!$date_validator->validateValue($appointment_date)) {
         if (strtotime($appointment_date) != false) {
             $errs['appointment_date'] = 'Appointment date is not in valid format';
         } else {
             $errs['appointment_date'] = 'Appointment date is not a valid date';
         }
     } else {
         $not_historical_validator = new \OEDateValidatorNotHistorical();
         if ($not_historical_validator->validateValue($appointment_date) == false) {
             $errs['appointment_date'] = 'Appointment date cannot be in the past';
         }
     }
     if ($appointment_time = @$form_data['appointment_time']) {
         $time_validator = new \OETimeValidator();
         if (!$time_validator->validateValue($appointment_time)) {
             $errs['appointment_time'] = 'Appointment time is not valid';
         }
     }
     return $errs;
 }
 /**
  * Get all the operations that have TCI requirements based on the given criteria.
  *
  * @param $data
  * @param bool $all
  *
  * @return Element_OphTrOperationbooking_Operation[]
  */
 public function getTransportList($data, $all = false)
 {
     if (!empty($data)) {
         if (preg_match('/^[0-9]+ [a-zA-Z]{3} [0-9]{4}$/', @$data['date_from']) && preg_match('/^[0-9]+ [a-zA-Z]{3} [0-9]{4}$/', @$data['date_to'])) {
             $date_from = Helper::convertNHS2MySQL($data['date_from']) . ' 00:00:00';
             $date_to = Helper::convertNHS2MySQL($data['date_to']) . ' 23:59:59';
         }
     }
     !isset($data['include_bookings']) and $data['include_bookings'] = 1;
     !isset($data['include_reschedules']) and $data['include_reschedules'] = 1;
     !isset($data['include_cancellations']) and $data['include_cancellations'] = 1;
     if (!@$data['include_bookings'] && !@$data['include_reschedules'] && !@$data['include_cancellations']) {
         $data['include_bookings'] = 1;
     }
     $criteria = new CDbCriteria();
     $criteria->addCondition('transport_arranged = :zero or transport_arranged_date = :today');
     $criteria->params[':zero'] = 0;
     $criteria->params[':today'] = date('Y-m-d');
     $criteria->params[':six'] = 6;
     if (@$date_from && @$date_to) {
         $criteria->addCondition('session_date >= :fromDate and session_date <= :toDate');
         $criteria->params[':fromDate'] = $date_from;
         $criteria->params[':toDate'] = $date_to;
     }
     if (!$data['include_bookings']) {
         $criteria->addCondition('latestBooking.booking_cancellation_date is not null or status_id != :two');
         $criteria->params[':two'] = 2;
     }
     if (!$data['include_reschedules']) {
         $criteria->addCondition('latestBooking.booking_cancellation_date is not null or status_id = :two');
         $criteria->params[':two'] = 2;
     }
     if (!$data['include_cancellations']) {
         $criteria->addCondition('latestBooking.booking_cancellation_date is null');
     }
     if (!empty(Yii::app()->params['transport_exclude_sites'])) {
         $criteria->addNotInCondition('site.id', Yii::app()->params['transport_exclude_sites']);
     }
     if (!empty(Yii::app()->params['transport_exclude_theatres'])) {
         $criteria->addNotInCondition('theatre_id', Yii::app()->params['transport_exclude_theatres']);
     }
     $criteria->addCondition('session.date >= :today');
     $criteria->addCondition('event.deleted = 0 and episode.deleted = 0');
     $this->total_items = Element_OphTrOperationbooking_Operation::model()->with(array('latestBooking' => array('with' => array('session' => array('with' => array('theatre' => array('with' => 'site'))))), 'event' => array('joinType' => 'JOIN', 'with' => array('episode' => array('joinType' => 'JOIN')))))->count($criteria);
     $this->pages = ceil($this->total_items / $this->items_per_page);
     if (!$all) {
         $criteria->limit = $this->items_per_page;
         $criteria->offset = $this->items_per_page * ($this->page - 1);
     }
     $criteria->order = 'session_date, session_start_time, decision_date';
     Yii::app()->event->dispatch('start_batch_mode');
     return Element_OphTrOperationbooking_Operation::model()->with(array('latestBooking' => array('with' => array('session', 'theatre' => array('with' => 'site'), 'ward')), 'event' => array('joinType' => 'JOIN', 'with' => array('episode' => array('joinType' => 'JOIN', 'with' => array('patient' => array('with' => 'contact'), 'firm' => array('with' => array('serviceSubspecialtyAssignment' => array('with' => 'subspecialty'))))))), 'priority'))->findAll($criteria);
 }
 /**
  * Set the attributes of the given $elements from the given structured array.
  * Returns any validation errors that arise.
  *
  * @param array $data
  * @throws Exception
  * @return array $errors
  */
 protected function setAndValidateElementsFromData($data)
 {
     $errors = array();
     $elements = array();
     // only process data for elements that are part of the element type set for the controller event type
     foreach ($this->event_type->getAllElementTypes() as $element_type) {
         $el_cls_name = $element_type->class_name;
         $f_key = CHtml::modelName($el_cls_name);
         if (isset($data[$f_key])) {
             $keys = array_keys($data[$f_key]);
             if (is_array($data[$f_key][$keys[0]]) && !count(array_filter(array_keys($data[$f_key]), 'is_string'))) {
                 // there is more than one element of this type
                 $pk_field = $el_cls_name::model()->tableSchema->primaryKey;
                 foreach ($data[$f_key] as $i => $attrs) {
                     if (!$this->event->isNewRecord && !isset($attrs[$pk_field])) {
                         throw new Exception("missing primary key field for multiple elements for editing an event");
                     }
                     if ($pk = @$attrs[$pk_field]) {
                         $element = $el_cls_name::model()->findByPk($pk);
                     } else {
                         $element = $element_type->getInstance();
                     }
                     $element->attributes = Helper::convertNHS2MySQL($attrs);
                     $this->setElementComplexAttributesFromData($element, $data, $i);
                     $element->event = $this->event;
                     $elements[] = $element;
                 }
             } else {
                 if ($this->event->isNewRecord || !($element = $el_cls_name::model()->find('event_id=?', array($this->event->id)))) {
                     $element = $element_type->getInstance();
                 }
                 $element->attributes = Helper::convertNHS2MySQL($data[$f_key]);
                 $this->setElementComplexAttributesFromData($element, $data);
                 $element->event = $this->event;
                 $elements[] = $element;
             }
         } elseif ($element_type->required) {
             $errors['Event'][] = $element_type->name . ' is required';
             $elements[] = $element_type->getInstance();
         }
     }
     if (!count($elements)) {
         $errors['Event'][] = 'Cannot create an event without at least one element';
     }
     // assign
     $this->open_elements = $elements;
     // validate
     foreach ($this->open_elements as $element) {
         $this->setValidationScenarioForElement($element);
         if (!$element->validate()) {
             $name = $element->getElementTypeName();
             foreach ($element->getErrors() as $errormsgs) {
                 foreach ($errormsgs as $error) {
                     $errors[$name][] = $error;
                 }
             }
         }
     }
     //event date
     if (isset($data['Event']['event_date'])) {
         $event = $this->event;
         $event->event_date = Helper::convertNHS2MySQL($data['Event']['event_date']);
         if (!$event->validate()) {
             foreach ($event->getErrors() as $errormsgs) {
                 foreach ($errormsgs as $error) {
                     $errors['Event'][] = $error;
                 }
             }
         }
     }
     return $errors;
 }
 /**
  * Set the patient unavailable periods for Element_OphTrOperationbooking_ScheduleOperation.
  *
  * @param $element
  * @param $data
  * @param $index
  */
 protected function saveComplexAttributes_Element_OphTrOperationbooking_ScheduleOperation($element, $data, $index)
 {
     // using the ProcedureSelection widget, so not a direct field on the operation element
     $element->updatePatientUnavailables(isset($data['Element_OphTrOperationbooking_ScheduleOperation']['patient_unavailables']) ? Helper::convertNHS2MySQL($data['Element_OphTrOperationbooking_ScheduleOperation']['patient_unavailables']) : array());
 }
 /**
  * Set the attributes of the given $elements from the given structured array.
  * Returns any validation errors that arise.
  *
  * @param array $data
  *
  * @throws Exception
  *
  * @return array $errors
  */
 protected function setAndValidateElementsFromData($data)
 {
     $errors = array();
     $elements = array();
     // only process data for elements that are part of the element type set for the controller event type
     foreach ($this->event_type->getAllElementTypes() as $element_type) {
         $from_data = $this->getElementsForElementType($element_type, $data);
         if (count($from_data) > 0) {
             $elements = array_merge($elements, $from_data);
         } elseif ($element_type->required) {
             $errors[$this->event_type->name][] = $element_type->name . ' is required';
             $elements[] = $element_type->getInstance();
         }
     }
     if (!count($elements)) {
         $errors[$this->event_type->name][] = 'Cannot create an event without at least one element';
     }
     // assign
     $this->open_elements = $elements;
     // validate
     foreach ($this->open_elements as $element) {
         $this->setValidationScenarioForElement($element);
         if (!$element->validate()) {
             $name = $element->getElementTypeName();
             foreach ($element->getErrors() as $errormsgs) {
                 foreach ($errormsgs as $error) {
                     $errors[$name][] = $error;
                 }
             }
         }
     }
     //event date
     if (isset($data['Event']['event_date'])) {
         $event = $this->event;
         $event->event_date = Helper::convertNHS2MySQL($data['Event']['event_date']);
         if (!$event->validate()) {
             foreach ($event->getErrors() as $errormsgs) {
                 foreach ($errormsgs as $error) {
                     $errors[$this->event_type->name][] = $error;
                 }
             }
         }
     }
     return $errors;
 }
 public function criteria($count = false)
 {
     $criteria = new CDbCriteria();
     if ($count) {
         $criteria->select = 'count(*) as count';
     }
     if (@$_REQUEST['site_id']) {
         $criteria->addCondition('site_id = :site_id');
         $criteria->params[':site_id'] = $_REQUEST['site_id'];
     }
     if (@$_REQUEST['firm_id']) {
         $firm = Firm::model()->findByPk($_REQUEST['firm_id']);
         $firm_ids = array();
         foreach (Firm::model()->findAll('name=?', array($firm->name)) as $firm) {
             $firm_ids[] = $firm->id;
         }
         if (!empty($firm_ids)) {
             $criteria->addInCondition('firm_id', $firm_ids);
         }
     }
     if (@$_REQUEST['user']) {
         $user_ids = array();
         $criteria2 = new CDbCriteria();
         $criteria2->addCondition(array('active = :active'));
         $criteria2->addCondition(array("LOWER(concat_ws(' ',first_name,last_name)) = :term"));
         $params[':active'] = 1;
         $params[':term'] = strtolower($_REQUEST['user']);
         $criteria2->params = $params;
         foreach (User::model()->findAll($criteria2) as $user) {
             $user_ids[] = $user->id;
         }
         $criteria->addInCondition('user_id', $user_ids);
     }
     if (@$_REQUEST['action']) {
         $criteria->addCondition('action_id=:action_id');
         $criteria->params[':action_id'] = $_REQUEST['action'];
     }
     if (@$_REQUEST['target_type']) {
         $criteria->addCondition('type_id=:type_id');
         $criteria->params[':type_id'] = $_REQUEST['target_type'];
     }
     if (@$_REQUEST['event_type_id']) {
         $criteria->addCondition('event.event_type_id=:event_type_id');
         $criteria->params[':event_type_id'] = $_REQUEST['event_type_id'];
     }
     if (@$_REQUEST['date_from']) {
         $date_from = Helper::convertNHS2MySQL($_REQUEST['date_from']) . ' 00:00:00';
         $criteria->addCondition('`t`.created_date >= :date_from');
         $criteria->params[':date_from'] = $date_from;
     }
     if (@$_REQUEST['date_to']) {
         $date_to = Helper::convertNHS2MySQL($_REQUEST['date_to']) . ' 23:59:59';
         $criteria->addCondition('`t`.created_date <= :date_to');
         $criteria->params[':date_to'] = $date_to;
     }
     if (@$_REQUEST['hos_num']) {
         if ($patient = Patient::model()->find('hos_num=?', array($_REQUEST['hos_num']))) {
             $criteria->addCondition('patient_id=' . $patient->id);
         } else {
             if ($patient = Patient::model()->find('hos_num=?', array(str_pad($_REQUEST['hos_num'], 7, '0', STR_PAD_LEFT)))) {
                 $criteria->addCondition('patient_id=' . $patient->id);
             } else {
                 $criteria->addCondition('patient_id=0');
             }
         }
     }
     !$count && ($criteria->join = 'left join event on t.event_id = event.id left join event_type on event.event_type_id = event_type.id');
     return $criteria;
 }
 /**
  * Get bookings for the given selection criteria.
  *
  * @param $data
  *
  * @return OphTrOperationbooking_Operation_Booking[] $bookings
  *
  * @throws Exception
  */
 public function getBookingList($data)
 {
     foreach (array('date-start', 'date-end', 'subspecialty-id', 'site-id') as $required) {
         if (!isset($data[$required])) {
             throw new Exception('invalid request for booking list');
         }
     }
     $criteria = new CDbCriteria();
     $criteria->addCondition('session.date >= :dateFrom and session.date <= :dateTo');
     $criteria->addInCondition('operation.status_id', array(2, 4));
     $criteria->params[':dateFrom'] = Helper::convertNHS2MySQL($data['date-start']);
     $criteria->params[':dateTo'] = Helper::convertNHS2MySQL($data['date-end']);
     if (@$data['emergency_list']) {
         $criteria->addCondition('firm.id IS NULL');
     } else {
         $criteria->addCondition('theatre.site_id = :siteId and subspecialty_id = :subspecialtyId');
         $criteria->params[':siteId'] = $data['site-id'];
         $criteria->params[':subspecialtyId'] = $data['subspecialty-id'];
     }
     if (@$data['ward-id']) {
         $criteria->addCondition('ward.id = :wardId');
         $criteria->params[':wardId'] = $data['ward-id'];
     }
     if (@$data['firm-id']) {
         $criteria->addCondition('firm.id = :firmId');
         $criteria->params[':firmId'] = $data['firm-id'];
     }
     $criteria->addCondition('`t`.booking_cancellation_date is null');
     $criteria->order = 'ward.code, patient.hos_num';
     Yii::app()->event->dispatch('start_batch_mode');
     return OphTrOperationbooking_Operation_Booking::model()->with(array('session' => array('with' => array('theatre', 'firm' => array('with' => array('serviceSubspecialtyAssignment' => array('with' => 'subspecialty'))))), 'operation' => array('with' => array('event' => array('with' => array('episode' => array('with' => array('patient' => array('with' => 'contact'))))))), 'ward'))->findAll($criteria);
 }
 /**
  * Generates a cataract outcomes report.
  *
  * inputs (all optional):
  * - firm_id
  * - surgeon_id
  * - assistant_id
  * - supervising_surgeon_id
  * - date_from
  * - date_to
  *
  * outputs:
  * - number of cataracts (number)
  * - age of patients (mean and range)
  * - eyes (numbers and percentage for left/right)
  * - final visual acuity (mean and range)
  * - pc ruptures (number and percentage)
  * - complications (number and percentage)
  *
  * @param array $params
  *
  * @return array
  */
 public function reportCataractOperations($params)
 {
     $data = array();
     $where = '';
     @$params['firm_id'] and $where .= " and f.id = {$params['firm_id']}";
     $surgeon_where = '';
     foreach (array('surgeon_id', 'assistant_id', 'supervising_surgeon_id') as $field) {
         if (@$params[$field]) {
             if ($surgeon_where) {
                 $surgeon_where .= ' or ';
             }
             $surgeon_where .= "s.{$field} = {$params[$field]}";
         }
     }
     $surgeon_where and $where .= " and ({$surgeon_where})";
     if (preg_match('/^[0-9]+[\\s\\-][a-zA-Z]{3}[\\s\\-][0-9]{4}$/', @$params['date_from'])) {
         $params['date_from'] = Helper::convertNHS2MySQL($params['date_from']);
     }
     if (preg_match('/^[0-9]+[\\s\\-][a-zA-Z]{3}[\\s\\-][0-9]{4}$/', @$params['date_to'])) {
         $params['date_to'] = Helper::convertNHS2MySQL($params['date_to']);
     }
     @$params['date_from'] and $where .= " and e.created_date >= '{$params['date_from']}'";
     @$params['date_to'] and $where .= " and e.created_date <= '{$params['date_to']}'";
     $data['cataracts'] = 0;
     $data['eyes'] = array('left' => array('number' => 0), 'right' => array('number' => 0));
     $data['age']['from'] = 200;
     // wonder if this will ever need to be changed..
     $data['age']['to'] = 0;
     $data['final_visual_acuity'] = array('from' => 0, 'to' => 0, 'mean' => 0);
     $data['pc_ruptures']['number'] = 0;
     $data['complications']['number'] = 0;
     $ages = array();
     if (!($db = Yii::app()->params['report_db'])) {
         $db = 'db';
     }
     foreach (Yii::app()->{$db}->createCommand()->select('pl.eye_id, p.dob, p.date_of_death, comp.id as comp_id, pc.id as pc_id')->from('et_ophtroperationnote_procedurelist pl')->join('et_ophtroperationnote_cataract c', 'pl.event_id = c.event_id')->join('event e', 'c.event_id = e.id')->join('et_ophtroperationnote_surgeon s', 's.event_id = e.id')->join('episode ep', 'e.episode_id = ep.id')->join('firm f', 'ep.firm_id = f.id')->join('patient p', 'ep.patient_id = p.id')->leftJoin('et_ophtroperationnote_cataract_complication comp', 'comp.cataract_id = c.id')->leftJoin('et_ophtroperationnote_cataract_complication pc', 'pc.cataract_id = c.id and pc.complication_id = 11')->where("pl.deleted = 0 and c.deleted = 0 and e.deleted = 0 and s.deleted = 0 and ep.deleted = 0 and f.deleted = 0 and p.deleted = 0 and (comp.id is null or comp.deleted = 0) and (pc.id is null or pc.deleted = 0) {$where}")->queryAll() as $row) {
         ++$data['cataracts'];
         $row['eye_id'] == 1 ? $data['eyes']['left']['number']++ : $data['eyes']['right']['number']++;
         $age = Helper::getAge($row['dob'], $row['date_of_death']);
         $ages[] = $age;
         //this is taking ages
         if ($age < $data['age']['from']) {
             $data['age']['from'] = $age;
         }
         if ($age > $data['age']['to']) {
             $data['age']['to'] = $age;
         }
         $row['pc_id'] and $data['pc_ruptures']['number']++;
         $row['comp_id'] and $data['complications']['number']++;
     }
     if (count($ages) == 0) {
         $data['age']['from'] = 0;
     }
     $data['eyes']['left']['percentage'] = $data['cataracts'] > 0 ? number_format($data['eyes']['left']['number'] / ($data['cataracts'] / 100), 2) : 0;
     $data['eyes']['right']['percentage'] = $data['cataracts'] > 0 ? number_format($data['eyes']['right']['number'] / ($data['cataracts'] / 100), 2) : 0;
     $data['age']['mean'] = count($ages) > 0 ? number_format(array_sum($ages) / count($ages), 2) : 0;
     $data['pc_ruptures']['percentage'] = $data['cataracts'] > 0 ? number_format($data['pc_ruptures']['number'] / ($data['cataracts'] / 100), 2) : 0;
     $data['complications']['percentage'] = $data['cataracts'] > 0 ? number_format($data['complications']['number'] / ($data['cataracts'] / 100), 2) : 0;
     $data['pc_rupture_average']['number'] = 0;
     $data['complication_average']['number'] = 0;
     if (!($db = Yii::app()->params['report_db'])) {
         $db = 'db';
     }
     foreach (Yii::app()->{$db}->createCommand()->select('pl.eye_id, p.dob, p.date_of_death, comp.id as comp_id, pc.id as pc_id')->from('et_ophtroperationnote_procedurelist pl')->join('et_ophtroperationnote_cataract c', 'pl.event_id = c.event_id')->join('event e', 'c.event_id = e.id')->join('et_ophtroperationnote_surgeon s', 's.event_id = e.id')->join('episode ep', 'e.episode_id = ep.id')->join('firm f', 'ep.firm_id = f.id')->join('patient p', 'ep.patient_id = p.id')->leftJoin('et_ophtroperationnote_cataract_complication comp', 'comp.cataract_id = c.id')->leftJoin('et_ophtroperationnote_cataract_complication pc', 'pc.cataract_id = c.id and pc.complication_id = 11')->where('pl.deleted = 0 and c.deleted = 0 and e.deleted = 0 and s.deleted = 0 and ep.deleted = 0 and f.deleted = 0 and p.deleted = 0 and (comp.id is null or comp.deleted = 0) and (pc.id is null or pc.deleted = 0)')->queryAll() as $i => $row) {
         $row['pc_id'] and $data['pc_rupture_average']['number']++;
         $row['comp_id'] and $data['complication_average']['number']++;
     }
     ++$i;
     $data['pc_rupture_average']['percentage'] = number_format($data['pc_rupture_average']['number'] / ($i / 100), 2);
     $data['complication_average']['percentage'] = number_format($data['complication_average']['number'] / ($i / 100), 2);
     return $data;
 }
 /**
  * @param \CDbCriteria $criteria
  * @param array $filter
  */
 private function handleDateRangeFilter(\CDbCriteria $criteria, $filter = array())
 {
     $from = null;
     if (isset($filter['date_from'])) {
         $from = \Helper::convertNHS2MySQL($filter['date_from']);
     }
     $to = null;
     if (isset($filter['date_to'])) {
         $to = \Helper::convertNHS2MySQL($filter['date_to']);
     }
     if ($from && $to) {
         if ($from > $to) {
             $criteria->addBetweenCondition('event.event_date', $to, $from);
         } else {
             $criteria->addBetweenCondition('event.event_date', $from, $to);
         }
     } elseif ($from) {
         $criteria->addCondition('event.event_date >= :from');
         $criteria->params[':from'] = $from;
     } elseif ($to) {
         $criteria->addCondition('event.event_date <= :to');
         $criteria->params[':to'] = $to;
     }
 }
 public function criteria($count = false)
 {
     $criteria = new CDbCriteria();
     if (@$_REQUEST['hos_num']) {
         $criteria->addCondition('`dil`.`patient_number` = :hos_num');
         $criteria->params[':hos_num'] = $_REQUEST['hos_num'];
     }
     if (@$_REQUEST['file_name']) {
         $criteria->addCondition('file_name = :file_name');
         $criteria->params[':file_name'] = $_REQUEST['file_name'];
     }
     if (@$_REQUEST['firm_id']) {
         $firm = Firm::model()->findByPk($_REQUEST['firm_id']);
         $firm_ids = array();
         foreach (Firm::model()->findAll('name=?', array($firm->name)) as $firm) {
             $firm_ids[] = $firm->id;
         }
         if (!empty($firm_ids)) {
             $criteria->addInCondition('firm_id', $firm_ids);
         }
     }
     if (@$_REQUEST['action']) {
         $criteria->addCondition('action_id=:action_id');
         $criteria->params[':action_id'] = $_REQUEST['action'];
     }
     if (@$_REQUEST['target_type']) {
         $criteria->addCondition('type_id=:type_id');
         $criteria->params[':type_id'] = $_REQUEST['target_type'];
     }
     if (@$_REQUEST['event_type_id']) {
         $criteria->addCondition('event_type_id=:event_type_id');
         $criteria->params[':event_type_id'] = $_REQUEST['event_type_id'];
     }
     if (@$_REQUEST['date_from']) {
         $date_from = Helper::convertNHS2MySQL($_REQUEST['date_from']) . ' 00:00:00';
         $criteria->addCondition('`t`.created_date >= :date_from');
         $criteria->params[':date_from'] = $date_from;
     }
     if (@$_REQUEST['date_to']) {
         $date_to = Helper::convertNHS2MySQL($_REQUEST['date_to']) . ' 23:59:59';
         $criteria->addCondition('`t`.created_date <= :date_to');
         $criteria->params[':date_to'] = $date_to;
     }
     //  !($count) && $criteria->join = 'left join event on t.event_id = event.id left join event_type on event.event_type_id = event_type.id';
     return $criteria;
 }
 /**
  * Get sent messages.
  * 
  * @param CWebUser $user
  *
  * @return array title and content for the widget
  */
 public function getSentMessages($user = null)
 {
     if (is_null($user)) {
         $user = \Yii::app()->user;
     }
     $sort = new \CSort();
     $sort->attributes = array('priority' => array('asc' => 'urgent asc', 'desc' => 'urgent desc'), 'event_date' => array('asc' => 't.created_date asc', 'desc' => 't.created_date desc'), 'patient_name' => array('asc' => 'lower(contact.last_name) asc, lower(contact.first_name) asc', 'desc' => 'lower(contact.last_name) desc, lower(contact.first_name) desc'), 'hos_num' => array('asc' => 'patient.hos_num asc', 'desc' => 'patient.hos_num desc'), 'dob' => array('asc' => 'patient.dob asc', 'desc' => 'patient.dob desc'), 'user' => array('asc' => 'lower(for_the_attention_of_user.last_name) asc, lower(for_the_attention_of_user.first_name) asc', 'desc' => 'lower(for_the_attention_of_user.last_name) desc, lower(for_the_attention_of_user.first_name) desc'));
     $sort->defaultOrder = 'event_date desc';
     $from = \Yii::app()->request->getQuery('OphCoMessaging_sent_from', '');
     $to = \Yii::app()->request->getQuery('OphCoMessaging_sent_to', '');
     $params = array(':uid' => $user->id);
     $criteria = new \CDbCriteria();
     $criteria->select = array('*');
     $criteria->addCondition('t.created_user_id = :uid');
     $criteria->with = array('event', 'for_the_attention_of_user', 'message_type', 'event.episode', 'event.episode.patient', 'event.episode.patient.contact');
     $criteria->together = true;
     if ($from) {
         $criteria->addCondition('DATE(t.created_date) >= :from');
         $params[':from'] = \Helper::convertNHS2MySQL($from);
     }
     if ($to) {
         $criteria->addCondition('DATE(t.created_date) <= :to');
         $params[':to'] = \Helper::convertNHS2MySQL($to);
     }
     $criteria->addCondition('event.deleted = 0');
     $criteria->addCondition('episode.deleted = 0');
     $criteria->params = $params;
     $dataProvider = new \CActiveDataProvider('OEModule\\OphCoMessaging\\models\\Element_OphCoMessaging_Message', array('sort' => $sort, 'criteria' => $criteria, 'pagination' => array('pageSize' => 10)));
     $messages = Element_OphCoMessaging_Message::model()->findAll($criteria);
     \Yii::app()->getAssetManager()->registerCssFile('module.css', 'application.modules.OphCoMessaging.assets.css');
     $inbox_view = \Yii::app()->controller->renderPartial('OphCoMessaging.views.sent.grid', array('messages' => $messages, 'dataProvider' => $dataProvider), true);
     return array('title' => 'Sent Messages', 'content' => $inbox_view, 'options' => array('container-id' => \Yii::app()->user->id . '-sent-container', 'js-toggle-open' => \Yii::app()->request->cookies->contains(\Yii::app()->user->id . '-sent-container-state') ? (bool) \Yii::app()->request->cookies[\Yii::app()->user->id . '-sent-container-state']->value : false));
 }
 public function confirmLetterPrinted($confirmto = null, $confirmdate = null)
 {
     // admin users can set confirmto and confirm up to a specific point, steamrollering whatever else is in there
     if (!is_null($confirmto)) {
         if (!($dls = $this->date_letter_sent)) {
             $dls = new OphTrOperationbooking_Operation_Date_Letter_Sent();
             $dls->element_id = $this->id;
         }
         if ($confirmto == self::LETTER_GP) {
             $dls->date_invitation_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_1st_reminder_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_2nd_reminder_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_gp_letter_sent = Helper::convertNHS2MySQL($confirmdate);
         }
         if ($confirmto == self::LETTER_INVITE) {
             $dls->date_invitation_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_1st_reminder_letter_sent = null;
             $dls->date_2nd_reminder_letter_sent = null;
             $dls->date_gp_letter_sent = null;
         }
         if ($confirmto == self::LETTER_REMINDER_1) {
             $dls->date_invitation_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_1st_reminder_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_2nd_reminder_letter_sent = null;
             $dls->date_gp_letter_sent = null;
         }
         if ($confirmto == self::LETTER_REMINDER_2) {
             $dls->date_invitation_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_1st_reminder_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_2nd_reminder_letter_sent = Helper::convertNHS2MySQL($confirmdate);
             $dls->date_gp_letter_sent = null;
         }
         if ($confirmto == 'noletters') {
             $dls->date_invitation_letter_sent = null;
             $dls->date_1st_reminder_letter_sent = null;
             $dls->date_2nd_reminder_letter_sent = null;
             $dls->date_gp_letter_sent = null;
         }
         if (!$dls->save()) {
             throw new Exception('Unable to save date letter sent: ' . print_r($dls->getErrors(), true));
         }
         OELog::log("Letter print confirmed, datelettersent={$dls->id} confirmdate='{$confirmdate}'");
         // Only confirm if letter is actually due
     } elseif ($this->getDueLetter() !== $this->getLastLetter()) {
         if ($dls = $this->date_letter_sent) {
             if ($dls->date_invitation_letter_sent == null) {
                 $dls->date_invitation_letter_sent = date('Y-m-d H:i:s');
             } elseif ($dls->date_1st_reminder_letter_sent == null) {
                 $dls->date_1st_reminder_letter_sent = date('Y-m-d H:i:s');
             } elseif ($dls->date_2nd_reminder_letter_sent == null) {
                 $dls->date_2nd_reminder_letter_sent = date('Y-m-d H:i:s');
             } elseif ($dls->date_gp_letter_sent == null) {
                 $dls->date_gp_letter_sent = date('Y-m-d H:i:s');
             } elseif ($dls->date_scheduling_letter_sent == null) {
                 $dls->date_scheduling_letter_sent = date('Y-m-d H:i:s');
             }
             if (!$dls->save()) {
                 throw new SystemException("Unable to update date_letter_sent record {$dls->id}: " . print_r($dls->getErrors(), true));
             }
             OELog::log("Letter print confirmed, datelettersent={$dls->id}");
         } else {
             $dls = new OphTrOperationbooking_Operation_Date_Letter_Sent();
             $dls->element_id = $this->id;
             $dls->date_invitation_letter_sent = date('Y-m-d H:i:s');
             if (!$dls->save()) {
                 throw new SystemException('Unable to save new date_letter_sent record: ' . print_r($dls->getErrors(), true));
             }
             OELog::log("Letter print confirmed, datelettersent={$dls->id}");
         }
     }
 }