/**
  * Creates a model for getModel(). Called only for each new $action.
  *
  * The parameters allow you to easily adapt the model to the current action. The $detailed
  * parameter was added, because the most common use of action is a split between detailed
  * and summarized actions.
  *
  * @param boolean $detailed True when the current action is not in $summarizedActions.
  * @param string $action The current action.
  * @return \MUtil_Model_ModelAbstract
  */
 public function createModel($detailed, $action)
 {
     //
     $model = new \Gems_Model_JoinModel('resptrack', 'gems__respondent2track');
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization'));
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code'));
     $model->addFilter(array('grc_success' => 1));
     $model->resetOrder();
     $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'));
     $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy');
     $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy');
     $filter = $this->getSearchFilter($action !== 'export');
     if (!(isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) {
         $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter()));
     }
     if (!(isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) {
         $model->setFilter(array('1=0'));
         $this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
         return $model;
     }
     // Add the period filter - if any
     if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
         $model->addFilter(array($where));
     }
     $trackId = $filter['gr2t_id_track'];
     $engine = $this->loader->getTracker()->getTrackEngine($trackId);
     $engine->addFieldsToModel($model, false);
     return $model;
 }
 /**
  * Creates a model for getModel(). Called only for each new $action.
  *
  * The parameters allow you to easily adapt the model to the current action. The $detailed
  * parameter was added, because the most common use of action is a split between detailed
  * and summarized actions.
  *
  * @param boolean $detailed True when the current action is not in $summarizedActions.
  * @param string $action The current action.
  * @return \MUtil_Model_ModelAbstract
  */
 public function createModel($detailed, $action)
 {
     $model = new \Gems_Model_JoinModel('resptrack', 'gems__respondent2track');
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user', 'gr2t_id_organization' => 'gr2o_id_organization'));
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__reception_codes', array('gr2t_reception_code' => 'grc_id_reception_code'));
     $model->addFilter(array('grc_success' => 1));
     $model->resetOrder();
     $model->set('gr2o_patient_nr', 'label', $this->_('Respondent nr'));
     $model->set('gr2t_start_date', 'label', $this->_('Start date'), 'dateFormat', 'dd-MM-yyyy');
     $model->set('gr2t_end_date', 'label', $this->_('End date'), 'dateFormat', 'dd-MM-yyyy');
     $filter = $this->getSearchFilter($action !== 'export');
     if (!(isset($filter['gr2t_id_organization']) && $filter['gr2t_id_organization'])) {
         $model->addFilter(array('gr2t_id_organization' => $this->currentUser->getRespondentOrgFilter()));
     }
     if (!(isset($filter['gr2t_id_track']) && $filter['gr2t_id_track'])) {
         $model->setFilter(array('1=0'));
         $this->autofilterParameters['onEmpty'] = $this->_('No track selected...');
         return $model;
     }
     // Add the period filter - if any
     if ($where = \Gems_Snippets_AutosearchFormSnippet::getPeriodFilter($filter, $this->db)) {
         $model->addFilter(array($where));
     }
     $select = $this->db->select();
     $select->from('gems__rounds', array('gro_id_round', 'gro_id_order', 'gro_round_description', 'gro_icon_file'))->joinInner('gems__surveys', 'gro_id_survey = gsu_id_survey', array('gsu_survey_name'))->where('gro_id_track = ?', $filter['gr2t_id_track'])->order('gro_id_order');
     if (isset($filter['gsu_id_primary_group']) && $filter['gsu_id_primary_group']) {
         $select->where('gsu_id_primary_group = ?', $filter['gsu_id_primary_group']);
     }
     $data = $this->db->fetchAll($select);
     if (!$data) {
         return $model;
     }
     $status = $this->util->getTokenData()->getStatusExpression();
     $select = $this->db->select();
     $select->from('gems__tokens', array('gto_id_respondent_track', 'gto_id_round', 'gto_id_token', 'status' => $status))->joinInner('gems__reception_codes', 'gto_reception_code = grc_id_reception_code', array())->where('gto_id_track = ?', $filter['gr2t_id_track'])->order('grc_success')->order('gto_id_respondent_track')->order('gto_round_order');
     // \MUtil_Echo::track($this->db->fetchAll($select));
     $newModel = new \MUtil_Model_SelectModel($select, 'tok');
     $newModel->setKeys(array('gto_id_respondent_track'));
     $transformer = new \MUtil_Model_Transform_CrossTabTransformer();
     $transformer->addCrosstabField('gto_id_round', 'status', 'stat_')->addCrosstabField('gto_id_round', 'gto_id_token', 'tok_');
     foreach ($data as $row) {
         $name = 'stat_' . $row['gro_id_round'];
         $transformer->set($name, 'label', \MUtil_Lazy::call('substr', $row['gsu_survey_name'], 0, 2), 'description', sprintf("%s\n[%s]", $row['gsu_survey_name'], $row['gro_round_description']), 'noSort', true, 'round', $row['gro_round_description'], 'roundIcon', $row['gro_icon_file']);
         $transformer->set('tok_' . $row['gro_id_round']);
     }
     $newModel->addTransformer($transformer);
     // \MUtil_Echo::track($data);
     $joinTrans = new \MUtil_Model_Transform_JoinTransformer();
     $joinTrans->addModel($newModel, array('gr2t_id_respondent_track' => 'gto_id_respondent_track'));
     $model->resetOrder();
     $model->set('gr2o_patient_nr');
     $model->set('gr2t_start_date');
     $model->addTransformer($joinTrans);
     return $model;
 }
 /**
  * Creates a model for getModel(). Called only for each new $action.
  *
  * The parameters allow you to easily adapt the model to the current action. The $detailed
  * parameter was added, because the most common use of action is a split between detailed
  * and summarized actions.
  *
  * @param boolean $detailed True when the current action is not in $summarizedActions.
  * @param string $action The current action.
  * @return \MUtil_Model_ModelAbstract
  */
 protected function createModel($detailed, $action)
 {
     $yesNo = $this->util->getTranslated()->getYesNo();
     $model = new \Gems_Model_JoinModel('surveys', 'gems__surveys');
     $model->addTable('gems__groups', array('gsu_id_primary_group' => 'ggp_id_group'));
     $model->addColumn("(SELECT COUNT(DISTINCT gro_id_track)\r\n                    FROM gems__tracks INNER JOIN gems__rounds ON gtr_id_track = gro_id_track\r\n                    WHERE gro_id_survey = gsu_id_survey)", 'track_count');
     $model->resetOrder();
     $model->set('gsu_survey_name', 'label', $this->_('Survey'));
     if ($detailed) {
         $model->set('gsu_survey_description', 'label', $this->_('Description'), 'formatFunction', array(__CLASS__, 'formatDescription'));
         $model->set('gsu_active', 'label', sprintf($this->_('Active in %s'), $this->project->getName()), 'elementClass', 'Checkbox', 'multiOptions', $yesNo);
     }
     $model->set('ggp_name', 'label', $this->_('By'));
     $model->set('track_count', 'label', $this->_('Usage'), 'description', $this->_('How many track definitions use this survey?'));
     $model->set('gsu_insertable', 'label', $this->_('Insertable'), 'description', $this->_('Can this survey be manually inserted into a track?'), 'multiOptions', $yesNo);
     if ($detailed) {
         $model->set('gsu_duration', 'label', $this->_('Duration description'), 'description', $this->_('Text to inform the respondent, e.g. "20 seconds" or "1 minute".'));
     }
     return $model;
 }
 /**
  * Creates a model for getModel(). Called only for each new $action.
  *
  * The parameters allow you to easily adapt the model to the current action. The $detailed
  * parameter was added, because the most common use of action is a split between detailed
  * and summarized actions.
  *
  * @param boolean $detailed True when the current action is not in $summarizedActions.
  * @param string $action The current action.
  * @return \MUtil_Model_ModelAbstract
  */
 protected function createModel($detailed, $action)
 {
     $dbLookup = $this->util->getDbLookup();
     $survey = null;
     $translated = $this->util->getTranslated();
     $yesNo = $translated->getYesNo();
     if ($detailed) {
         $surveyId = $this->_getIdParam();
         if ($surveyId) {
             $survey = $this->loader->getTracker()->getSurvey($surveyId);
         }
     }
     $model = new \Gems_Model_JoinModel('surveys', 'gems__surveys', 'gus');
     $model->addTable('gems__sources', array('gsu_id_source' => 'gso_id_source'));
     $model->setCreate(false);
     $model->addColumn("CASE WHEN gsu_survey_pdf IS NULL OR CHAR_LENGTH(gsu_survey_pdf) = 0 THEN 0 ELSE 1 END", 'gsu_has_pdf');
     $model->addColumn(sprintf("CASE WHEN (gsu_status IS NULL OR gsu_status = '') THEN '%s' ELSE gsu_status END", $this->_('OK')), 'gsu_status_show', 'gsu_status');
     $model->addColumn("CASE WHEN gsu_surveyor_active THEN '' ELSE 'deleted' END", 'row_class');
     $model->resetOrder();
     $model->set('gsu_survey_name', 'label', $this->_('Name'), 'elementClass', 'Exhibitor');
     $model->set('gsu_survey_description', 'label', $this->_('Description'), 'elementClass', 'Exhibitor', 'formatFunction', array(__CLASS__, 'formatDescription'));
     $model->set('gso_source_name', 'label', $this->_('Source'), 'elementClass', 'Exhibitor');
     $model->set('gsu_surveyor_active', 'label', $this->_('Active in source'), 'elementClass', 'Exhibitor', 'multiOptions', $yesNo);
     $model->set('gsu_status_show', 'label', $this->_('Status in source'), 'elementClass', 'Exhibitor');
     $model->set('gsu_active', 'label', sprintf($this->_('Active in %s'), $this->project->getName()), 'elementClass', 'Checkbox', 'multiOptions', $yesNo);
     $model->set('gsu_id_primary_group', 'label', $this->_('Group'), 'description', $this->_('If empty, survey will never show up!'), 'multiOptions', $dbLookup->getGroups());
     if ($detailed) {
         $model->addDependency('CanEditDependency', 'gsu_surveyor_active', array('gsu_active'));
         $model->set('gsu_active', 'validators[group]', new \MUtil_Validate_Require($model->get('gsu_active', 'label'), 'gsu_id_primary_group', $model->get('gsu_id_primary_group', 'label')));
     }
     $model->set('gsu_insertable', 'label', $this->_('Insertable'), 'description', $this->_('Can this survey be manually inserted into a track?'), 'elementClass', 'Checkbox', 'multiOptions', $yesNo, 'onclick', 'this.form.submit()');
     if ($detailed) {
         $model->set('gsu_valid_for_length', 'label', $this->_('Add to inserted end date'), 'description', $this->_('Add to the start date to calculate the end date when inserting.'), 'filter', 'Int');
         $model->set('gsu_valid_for_unit', 'label', $this->_('Inserted end date unit'), 'description', $this->_('The unit used to calculate the end date when inserting the survey.'), 'multiOptions', $translated->getPeriodUnits());
         $model->set('gsu_insert_organizations', 'label', $this->_('Insert organizations'), 'description', $this->_('The organizations where the survey may be inserted.'), 'elementClass', 'MultiCheckbox', 'multiOptions', $dbLookup->getOrganizations(), 'required', true);
         $ct = new \MUtil_Model_Type_ConcatenatedRow('|', $this->_(', '));
         $ct->apply($model, 'gsu_insert_organizations');
         //            if ('edit' == $action) {
         //                $element = new \Gems_JQuery_Form_Element_ToggleCheckboxes('toggleOrg', array('selector'=>'input[name^=gtr_organizations]'));
         //                $element->setLabel($this->_('Toggle'));
         //                $model->set('toggleOrg', 'elementClass', $element);
         //            }
         $switches = array(0 => array('gsu_valid_for_length' => array('elementClass' => 'Hidden', 'label' => null), 'gsu_valid_for_unit' => array('elementClass' => 'Hidden', 'label' => null), 'gsu_insert_organizations' => array('elementClass' => 'Hidden', 'label' => null)));
         $model->addDependency(array('ValueSwitchDependency', $switches), 'gsu_insertable');
     }
     if ($detailed) {
         $model->set('track_usage', 'label', $this->_('Usage'), 'elementClass', 'Exhibitor', 'noSort', true, 'no_text_search', true);
         $model->setOnLoad('track_usage', array($this, 'calculateTrackUsage'));
         $model->set('calc_duration', 'label', $this->_('Duration calculated'), 'elementClass', 'Html');
         $model->setOnLoad('calc_duration', array($this, 'calculateDuration'));
         $model->set('gsu_duration', 'label', $this->_('Duration description'), 'description', $this->_('Text to inform the respondent, e.g. "20 seconds" or "1 minute".'));
         if ($survey instanceof \Gems_Tracker_Survey) {
             $surveyFields = $this->util->getTranslated()->getEmptyDropdownArray() + $survey->getQuestionList($this->locale->getLanguage());
             $model->set('gsu_result_field', 'label', $this->_('Result field'), 'multiOptions', $surveyFields);
             // $model->set('gsu_agenda_result',         'label', $this->_('Agenda field'));
         }
     } else {
         $model->set('track_count', 'label', ' ', 'elementClass', 'Exhibitor', 'noSort', true, 'no_text_search', true);
         $model->setOnLoad('track_count', array($this, 'calculateTrackCount'));
     }
     $model->set('gsu_code', 'label', $this->_('Survey code'), 'description', $this->_('Optional code name to link the survey to program code.'), 'size', 10);
     $model->set('gsu_export_code', 'label', $this->_('Survey export code'), 'description', $this->_('A unique code indentifying this survey during track import'), 'size', 20);
     if ($detailed) {
         $events = $this->loader->getEvents();
         $beforeOptions = $events->listSurveyBeforeAnsweringEvents();
         if (count($beforeOptions) > 1) {
             $model->set('gsu_beforeanswering_event', 'label', $this->_('Before answering'), 'multiOptions', $beforeOptions, 'elementClass', 'Select');
         }
         $completedOptions = $events->listSurveyCompletionEvents();
         if (count($completedOptions) > 1) {
             $model->set('gsu_completed_event', 'label', $this->_('After completion'), 'multiOptions', $completedOptions, 'elementClass', 'Select');
         }
         $displayOptions = $events->listSurveyDisplayEvents();
         if (count($displayOptions) > 1) {
             $model->set('gsu_display_event', 'label', $this->_('Answer display'), 'multiOptions', $displayOptions, 'elementClass', 'Select');
         }
         if ('show' !== $action || $survey->hasPdf()) {
             // Only the action changes from the current page
             // and the right to see the pdf is the same as
             // the right to see this page.
             $pdfLink = \MUtil_Html::create('a', array($this->getRequest()->getActionKey() => 'pdf'), array('class' => 'pdf', 'target' => '_blank', 'type' => 'application/pdf', 'onclick' => 'event.cancelBubble = true;'));
             $model->set('gsu_survey_pdf', 'label', 'Pdf', 'accept', 'application/pdf', 'destination', $this->loader->getPdf()->getUploadDir('survey_pdfs'), 'elementClass', 'File', 'extension', 'pdf', 'filename', $surveyId, 'required', false, 'itemDisplay', $pdfLink, 'validators[pdf]', new \MUtil_Validate_Pdf());
         }
     }
     return $model;
 }
 /**
  * Link the model to the user_logins table.
  *
  * @param \Gems_Model_JoinModel $model
  * @param string $loginField Field that links to login name field.
  * @param string $organizationField Field that links to the organization field.
  */
 protected function addUserLogin(\Gems_Model_JoinModel $model, $loginField, $organizationField)
 {
     $model->addTable('gems__user_logins', array($loginField => 'gul_login', $organizationField => 'gul_id_organization'), 'gul', \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_INSERT | \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_UPDATE | \MUtil_Model_DatabaseModelAbstract::SAVE_MODE_DELETE);
 }
 /**
  * Create a database model for retrieving the respondent tracks
  *
  * @return \Gems_Model_JoinModel A NEW JoinModel, not a continuation pattern return
  */
 public function getRespondentTracksModel()
 {
     $model = new \Gems_Model_JoinModel('surveys', 'gems__respondent2track');
     $model->addTable('gems__tracks', array('gr2t_id_track' => 'gtr_id_track'));
     $model->addTable('gems__respondent2org', array('gr2t_id_user' => 'gr2o_id_user'));
     return $model;
 }