Exemplo n.º 1
0
 public function execute($context)
 {
     // проверка прав доступа к разделу
     if (!$this->registry->getModel('Auth')->checkAccess($_SESSION['accesses'], 'members', $context['project']['projectID'])) {
         $this->registry->getModel('Auth')->restrict();
     }
     $context['APPLICATION']->AddHeadScript('/js/forms.js');
     $context['APPLICATION']->AddHeadScript('/js/icheck/icheck.min.js');
     $context['APPLICATION']->SetAdditionalCSS('/js/icheck/skins/minimal/eco.css');
     if (isset($_POST['type'])) {
         if ($_POST['type'] == 'exist') {
             if (isset($_POST['member_id'])) {
                 // проверяем, может уже есть респондент с таким участником
                 $existRespondent = $this->registry->getDbHelper('MembersHelper')->findRespondentByMemberIDAndSessionID($context['project']['projectID'], $_POST['member_id'], $_POST['session_id']);
                 if (!$existRespondent) {
                     // добавляем респондента
                     $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => intval($_POST['member_id']), 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => intval($_POST['session_id']), 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 }
             }
         } else {
             // пробуем добавить участника
             $validations = array('name' => 'anything', 'surname' => 'anything', 'email' => 'email', 'position' => 'anything', 'department' => 'anything', 'language' => 'identifier');
             $required = array('name', 'email', 'language');
             $validator = new \Ecoplay\Form\Validator($validations, $required, array());
             if ($validator->validate($_POST)) {
                 // проверяем чтобы не было уже участника с таким email
                 if (!$this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($_POST['email'], $context['project']['projectID'])) {
                     $memberID = $this->registry->getDbHelper('MembersHelper')->addMember(trim($_POST["name"]), trim($_POST["surname"]), trim($_POST["position"]), trim($_POST["email"]), $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key'), intval($_POST["language"]), 1, 'new', trim($_POST['department']));
                     $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                     $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     // добавляем респондента
                     $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => $memberID, 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => intval($_POST['session_id']), 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 } else {
                     $this->component->arResult['statusError'] = 'Участник с таким email (' . $_POST['email'] . ') уже существует';
                 }
             }
         }
     }
     if ($_FILES["filepath"] && !$_FILES['filepath']['error']) {
         $sessionID = (int) $_POST["fgroup"];
         if ($sessionID) {
             $session = $this->registry->getDbHelper('ProjectsHelper')->findSessionById($sessionID);
         }
         // обрабатываем загруженный файл
         $csvImporter = new \Ecoplay\Import\Csv($_FILES["filepath"]["tmp_name"], $_SERVER["DOCUMENT_ROOT"] . "/temp/csv/");
         $data = $csvImporter->parse();
         $sessionIndex = $csvImporter->getColumnIndex('Группа');
         if (!((!$sessionIndex || !$data[0][$sessionIndex]) && (!$sessionID || !$session))) {
             // определяем группу
             if ($sessionIndex && $data[0][$sessionIndex]) {
                 // ищем группу
                 $session = $this->registry->getDbHelper('ProjectsHelper')->findSessionByProjectIDAndName($context['project']['projectID'], $data[0][$sessionIndex]);
                 if ($session) {
                     $sessionID = $session['sessionID'];
                 } else {
                     $session = array('name' => $data[0][$sessionIndex], 'active' => 1, 'status' => 'active', 'projectID' => $context['project']['projectID']);
                     $sessionID = $this->registry->getDbHelper('ProjectsHelper')->addSession($session);
                     $session['sessionID'] = $sessionID;
                 }
             }
             $inserted = $skipped = 0;
             $validations = array(0 => 'anything', 1 => 'anything', 2 => 'email', 3 => 'anything', 4 => 'anything');
             $required = array(2);
             $validator = new \Ecoplay\Form\Validator($validations, $required, array());
             $projectLangID = $this->registry->getModel('Projects')->getDefaultLangID($context['project']);
             $languageIndex = $csvImporter->getColumnIndex('Язык');
             $languagesIDs = array();
             $availableLanguages = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs(json_decode($context['project']['~languages']));
             foreach ($availableLanguages as $language) {
                 $languagesIDs[$language['abbr']] = $language['langID'];
             }
             foreach ($data as $row) {
                 if ($sessionIndex && $row[$sessionIndex] && $row[$sessionIndex] != $session['name']) {
                     // ищем группу
                     $session = $this->registry->getDbHelper('ProjectsHelper')->findSessionByProjectIDAndName($context['project']['projectID'], $row[$sessionIndex]);
                     if ($session) {
                         $sessionID = $session['sessionID'];
                     } else {
                         $session = array('name' => $row[$sessionIndex], 'active' => 1, 'status' => 'active', 'projectID' => $context['project']['projectID']);
                         $sessionID = $this->registry->getDbHelper('ProjectsHelper')->addSession($session);
                         $session['sessionID'] = $sessionID;
                     }
                 }
                 // валидируем исходные данные
                 if (!$validator->validate($row)) {
                     $skipped++;
                 } elseif (!$row[0] && !$row[1]) {
                     // должно быть хотябы или имя, или фамилия
                     $skipped++;
                 } else {
                     // ищем такого участника уже в базе
                     $member = $this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($row[2], $context['project']['projectID']);
                     if (!$member) {
                         // добавляем участника
                         // определяем язык по структуре
                         $staff = $this->registry->getDbHelper('MembersHelper')->findStaffByProjectIDAndEmail($context['project']['projectID'], $row[2]);
                         $langID = $languageIndex && $row[$languageIndex] && array_key_exists($row[$languageIndex], $languagesIDs) ? $languagesIDs[$row[$languageIndex]] : $projectLangID;
                         $memberID = $this->registry->getDbHelper('MembersHelper')->addMember($row[0], $row[1], $row[3], $row[2], $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key', false), $langID, 1, 'new', $row[4]);
                         $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                         $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID, 'staff' => $staff), true);
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     } else {
                         $memberID = $member['projects_memberID'];
                     }
                     if ($this->registry->getDbHelper('MembersHelper')->findRespondentByProjectIDAndSessionIDAndMemberID($context['project']['projectID'], $sessionID, $memberID)) {
                         // такой оцениваемый уже есть
                         $skipped++;
                     } else {
                         $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('projectID' => $context['project']['projectID'], 'sessionID' => $sessionID, 'project_memberID' => $memberID, 'active' => 1, 'status' => 'new', 'stat1_assessID' => 0, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key', false), 'stat1_roleID' => 0));
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                         $inserted++;
                     }
                 }
             }
             $this->component->arResult['statusSuccess'] = 'Импортировано: ' . $inserted . ', проигнорировано: ' . $skipped;
         }
     }
     $statuses = $this->registry->getDbHelper('MembersHelper')->getLinearRespondentsStatusesNames();
     $this->component->arResult['statuses'] = $statuses;
     $sorts = array('respondentID' => 'respondentID', 'name' => 'name', 'surname' => 'surname', 'email' => 'email', 'position' => 'position', 'status' => 'status', 'private_lk_access_key' => 'private_lk_access_key');
     if (isset($_GET['sort']) && array_key_exists($_GET['sort'], $sorts)) {
         $sort = $_GET['sort'];
     } else {
         $sort = 'respondentID';
     }
     $order = isset($_GET['order']) && in_array($_GET['order'], array('asc', 'desc')) ? $_GET['order'] : 'asc';
     $filterQueryString = DataFilter::getFilterQueryString($_GET);
     $this->component->arResult['filterQueryString'] = $filterQueryString;
     // настройки фильтров для данных
     $filters = array(0 => array('title' => 'Имя', 'name' => 'name', 'type' => 'text', 'data_type' => 'string', 'field' => 'm.`name`'), 1 => array('title' => 'Фамилия', 'name' => 'surname', 'type' => 'text', 'data_type' => 'string', 'field' => 'm.`surname`'), 2 => array('title' => 'ID', 'name' => 'id', 'type' => 'text', 'data_type' => 'number', 'field' => 'r.`respondentID`'), 3 => array('title' => 'Текст', 'name' => 'text', 'type' => 'text', 'data_type' => 'string', 'field' => array('m.`search_text`')), 4 => array('title' => 'Статус ', 'name' => 'status', 'type' => 'select', 'data_type' => 'string', 'field' => 'r.`status`', 'values' => array(0 => 'Любой') + $statuses));
     $filterData = array('FILTERS' => $filters, 'BASE_URL' => '/projects/' . $context['project']['projectID'] . '/groups/' . (isset($_GET['TYPE']) && $_GET['TYPE'] ? $_GET['TYPE'] . '/' : '') . 'respondents/', 'SORT' => $sort, 'ORDER' => $order);
     // проверяем, введен ли фильтр
     $filterValue = DataFilter::getFilterValue($filters, $_GET, $this->registry->getDbConnect());
     if ($filterValue['valid']) {
         $filterData = array_merge($filterData, $filterValue);
     }
     // компонент отображения фильтра
     $context['APPLICATION']->IncludeComponent('ecoplay:data.filter', '', $filterData);
     // выполняем с респондентами действия
     if (isset($_POST['respondents_ids'])) {
         if (isset($_POST['all']) && $_POST['all']) {
             $selectedIDs = $this->registry->getDbHelper('LinearProjectsHelper')->getProjectRespondentsIDs($context['project']['projectID'], $filterValue['filter_strings']);
         } else {
             $selectedIDs = $_POST['respondents_ids'];
         }
         if (isset($_POST['mode'])) {
             if ($_POST['mode'] == 'send_notifications') {
                 $editedRespondents = $this->registry->getDbHelper('LinearProjectsHelper')->getRespondentsByIDs($selectedIDs);
                 $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array('need_remind' => 1));
                 foreach ($editedRespondents as $respondent) {
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                 }
             } elseif ($_POST['mode'] == 'reset') {
                 /*$editedRespondents =  $this->registry->getDbHelper('LinearProjectsHelper')->getRespondentsByIDs($selectedIDs);
                   
                   $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array(
                     'status'  => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE,
                   ));
                   
                   foreach ($editedRespondents as $respondent) {
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                   }*/
                 $seances = $this->registry->getDbHelper('SeancesHelper')->findSeanceByProjectAndRespondentsIDs($context['project']['projectID'], $selectedIDs);
                 foreach ($seances as $seance) {
                     // деактивируем текущий сеанс
                     $this->registry->getDbHelper('SeancesHelper')->editSeance($seance['seanceID'], array('active' => 0, 'private_access_key' => ''));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'seance', $seance['seanceID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_DELETE, $seance);
                     $this->registry->getDbHelper('MembersHelper')->editRespondent($seance['respondentID'], array('status' => 'active'));
                     // создаем новый сеанс
                     $BlankDataSource = new \Ecoplay\Model\BlankDataSource($this->registry->getDbConnect(), 0, 0);
                     $seanceKey = $BlankDataSource->addSeanceAndCookies($seance['private_access_key']);
                     $newSeance = $this->registry->getDbHelper('SeancesHelper')->findSeanceByKey($seanceKey);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'seance', $newSeance['seanceID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 }
             } elseif ($_POST['mode'] == 'return') {
                 if ($context['project']['allow_edit_seance_answers']) {
                     $seances = $this->registry->getDbHelper('SeancesHelper')->findSeanceByProjectAndRespondentsIDs($context['project']['projectID'], $selectedIDs);
                     foreach ($seances as $seance) {
                         if ($seance['state'] == \Ecoplay\Helper\Db\BlanksHelper::SEANCE_STATE_COMPLETE) {
                             $respondent = $this->registry->getDbHelper('MembersHelper')->findRespondentById($seance['respondentID']);
                             $this->registry->getDbHelper('MembersHelper')->editRespondent($seance['respondentID'], array('status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE));
                             // обновляем сеанс
                             $lastScreen = $this->registry->getDbHelper('BlanksHelper')->getBlankPrevScreen($seance['blankID'], $seance['last_screenID']);
                             $this->registry->getDbHelper('SeancesHelper')->editSeance($seance['seanceID'], array('state' => \Ecoplay\Helper\Db\BlanksHelper::SEANCE_STATE_PROGRESS, 'last_screenID' => $lastScreen ? $lastScreen['screenID'] : 0));
                         }
                     }
                 }
             } else {
                 $newStatus = false;
                 switch ($_POST['mode']) {
                     case 'to_new':
                         $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW;
                         break;
                     case 'to_active':
                         $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE;
                         break;
                     case 'to_complete':
                         $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_COMPLETE;
                         break;
                     case 'to_archive':
                         $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ARCHIVE;
                         break;
                 }
                 if ($newStatus) {
                     $editedRespondents = $this->registry->getDbHelper('LinearProjectsHelper')->getRespondentsByIDs($selectedIDs);
                     $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array('status' => $newStatus));
                     foreach ($editedRespondents as $respondent) {
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                     }
                 }
             }
         }
     }
     $arResult['selectedIDs'] = $selectedIDs;
     // получаем респондентов проекта
     $cnt = $this->registry->getDbHelper('LinearProjectsHelper')->getProjectRespondentsCount($context['project']['projectID'], $filterValue['filter_strings']);
     $onPage = 100;
     $pagesCnt = ceil($cnt / $onPage);
     $page = $_GET['PAGE'] && $_GET['PAGE'] <= $pagesCnt ? intval($_GET['PAGE']) : 1;
     $respondents = $this->registry->getDbHelper('LinearProjectsHelper')->getProjectRespondents($context['project']['projectID'], $page, $onPage, $sorts[$sort], $order, $filterValue['filter_strings']);
     $this->component->arResult['respondents'] = $respondents;
     $this->component->arResult['sort'] = $sort;
     $this->component->arResult['order'] = $order;
     $this->component->arResult['cntInfo'] = $pagesCnt == 1 ? $cnt : 0;
     $navResult = new \CDBResult();
     $navResult->NavPageCount = ceil($cnt / $onPage);
     $navResult->NavPageNomer = $page;
     $navResult->NavNum = 1;
     $navResult->NavPageSize = $onPage;
     $navResult->NavRecordCount = $cnt;
     $navResult->nPageWindow = 11;
     $context['APPLICATION']->IncludeComponent('ecoplay:system.pagenavigation', '', array('NAV_RESULT' => $navResult, 'NAV_URL' => '/projects/' . $context['project']['projectID'] . '/groups/' . (isset($_GET['TYPE']) && $_GET['TYPE'] ? $_GET['TYPE'] . '/' : '') . 'respondents/', 'NAV_QUERY_STRING' => 'sort=' . $sort . '&order=' . $order . ($filterQueryString ? '&' . $filterQueryString : '') . (isset($_GET['checkAll']) ? '&checkAll=1' : '')));
     $this->component->arResult['sessions'] = $this->registry->getDbHelper('ProjectsHelper')->getSessionsByProjectID($context['project']['projectID']);
     $languagesIDs = json_decode($context['project']['~languages']);
     $languagesSrc = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs($languagesIDs);
     $languages = array();
     foreach ($languagesSrc as $language) {
         $languages[$language['langID']] = $language['name'];
     }
     $this->component->arResult['languages'] = $languages;
     $this->component->arResult['project'] = $context['project'];
     $context['APPLICATION']->SetPageProperty('pageMainTitle', 'Респонденты');
     $viewHelper = new \Ecoplay\View\Helper();
     $context['APPLICATION']->SetPageProperty('navigation', $viewHelper->generateNavigation(array(0 => array('link' => '/', 'title' => 'Главная'), 1 => array('link' => '/projects/', 'title' => 'Проекты'), 2 => array('link' => '/projects/' . $context['project']['projectID'] . '/continuing/stat/', 'title' => $context['project']['project_name']), 3 => array('title' => 'Респонденты'))));
     $this->component->IncludeComponentTemplate("template_linear");
 }
Exemplo n.º 2
0
 public function execute($context)
 {
     $context['APPLICATION']->AddHeadScript('/js/forms.js');
     // проверка прав доступа к разделу
     if (!$this->registry->getModel('Auth')->checkAccess($_SESSION['accesses'], 'project_edit', $context['project']['projectID'])) {
         $this->registry->getModel('Auth')->restrict();
     }
     // выбираем языки проекта
     $projectLanguagesIds = json_decode($context['project']['~languages']);
     $languages = $this->registry->getDbHelper('TranslationHelper')->getSortedLanguages();
     $projectLanguages = array();
     foreach ($languages as $language) {
         if (in_array($language['langID'], $projectLanguagesIds)) {
             $projectLanguages[] = $language;
         }
     }
     $this->component->arResult['projectLanguages'] = $projectLanguages;
     switch ($this->getType()) {
         case '360':
             $events = array('fi' => array('name' => 'MailEvent_360_FirstInvite', 'title' => 'Первое уведомление респондента', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого (или список при групповой отправке)', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента', '#RESPONDENT_FILL_LINK#' => 'Ссылка на опросник респондента (недоступно при групповой отправке)')), 'nrn' => array('name' => 'MailEvent_360_NextRespondentNotification', 'title' => 'Последующее уведомление респондента', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого (или список при групповой отправке)', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента', '#RESPONDENT_FILL_LINK#' => 'Ссылка на опросник респондента (недоступно при групповой отправке)')), 'asr' => array('name' => 'MailEvent_360_AssessSelectRespondents', 'title' => 'Информирование оцениваемого о выборе респондентов', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого', '#ASSESS_LK_LINK#' => 'Ссылка на ЛК оцениваемого')), 'rsa' => array('name' => 'MailEvent_360_RespondentSelectAssess', 'title' => 'Информирование респондента о выборе оцениваемых', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого', '#ASSESS_LK_LINK#' => 'Ссылка на ЛК оцениваемого')), 'rasr' => array('name' => 'MailEvent_360_AssessSelectRespondentsRemind', 'title' => 'Напоминание оцениваемому о выборе респондентов', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого', '#ASSESS_LK_LINK#' => 'Ссылка на ЛК оцениваемого')), 'rrsa' => array('name' => 'MailEvent_360_RespondentSelectAssessRemind', 'title' => 'Напоминание респонденту о выборе оцениваемых', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого', '#ASSESS_LK_LINK#' => 'Ссылка на ЛК оцениваемого')), 'mr' => array('name' => 'MailEvent_360_MemeberReportNotification', 'title' => 'Информирование участника о доступности отчета', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия оцениваемого', '#REPORT_LINK#' => 'Ссылка на отчет')), 'dhr' => array('name' => 'MailEvent_360_DirectHeadReportNotification', 'title' => 'Информирование руководителя о доступности отчета', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#ASSESS#' => 'Имя Фамилия руководителя', '#REPORT_LINK#' => 'Ссылка на отчет', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента')), 'dn' => array('name' => 'MailEvent_360_DirectHeadNotification', 'title' => 'Информирование руководителя о необходимости подтвердить списки респондентов по подчиненным', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#DIRECT_HEAD#' => 'Имя Фамилия руководителя', '#ASSESS#' => 'Имя Фамилия подчиненного', '#LINK#' => 'Ссылка на страницу подтверждения')));
             break;
         case 'testing':
             $events = array('fi' => array('name' => 'MailEvent_Testing_FirstInvite', 'title' => 'Первое уведомление респондента', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента')), 'gkfi' => array('name' => 'MailEvent_Testing_GroupKey_FirstInvite', 'title' => 'Уведомление о групповой ссылке', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#GROUP_KEY_LINK#' => 'Групповая ссылка')), 'gknrn' => array('name' => 'MailEvent_Testing_GroupKey_Notification', 'title' => 'Напоминание о групповой ссылке', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#GROUP_KEY_LINK#' => 'Групповая ссылка')), 'mr' => array('name' => 'MailEvent_Testing_MailResend', 'title' => 'Напоминание о заполнении', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента')), 'rr' => array('name' => 'MailEvent_Testing_RespondentReport', 'title' => 'Письмо с последним отчетом тестируемого', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо')));
             break;
         case 'linear':
             $events = array('fi' => array('name' => 'MailEvent_Linear_FirstInvite', 'title' => 'Первое уведомление респондента', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента', '#SEANCE_LINK#' => 'Ссылка на анкету')), 'nrn' => array('name' => 'MailEvent_Linear_NextRespondentNotification', 'title' => 'Последующее уведомление респондента', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#RESPONDENT_LK_LINK#' => 'Ссылка на ЛК респондента', '#SEANCE_LINK#' => 'Ссылка на анкету')), 'gkfi' => array('name' => 'MailEvent_Linear_GroupKey_FirstInvite', 'title' => 'Уведомление о групповой ссылке', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#GROUP_KEY_LINK#' => 'Групповая ссылка')), 'gknrn' => array('name' => 'MailEvent_Linear_GroupKey_Notification', 'title' => 'Напоминание о групповой ссылке', 'replaces' => array('#EMAIL_FROM#' => 'email адрес отправителя письма', '#EMAIL_TO#' => 'email адрес на который отправляется письмо', '#RESPONDENT#' => 'Имя Фамилия того, кому отправляем письмо', '#GROUP_KEY_LINK#' => 'Групповая ссылка')));
             break;
     }
     $this->component->arResult['events'] = $events;
     // ищем шаблоны проекта
     $projectTemplatesSrc = $this->registry->getDbHelper('EmailHelper')->getProjectTemplates($context['project']['projectID']);
     $projectTemplates = array();
     foreach ($projectTemplatesSrc as $template) {
         // определяем ключ ивента
         $ek = null;
         foreach ($events as $key => $event) {
             if ($event['name'] == $template['event']) {
                 $ek = $key;
                 break;
             }
         }
         if ($ek) {
             $templateData = array('from' => $template['from'], 'to' => $template['to'], 'is_html' => $template['is_html'], 'id' => $template['ID'], 'lang' => array());
             foreach ($projectLanguages as $language) {
                 if ($language['is_default']) {
                     $templateData['lang'][$language['abbr']] = array('theme' => $template['theme'], 'body' => $template['body']);
                 } else {
                     $translation = $this->registry->getDbHelper('TranslationHelper')->findTranslation('email_theme', $template['ID'], $language['langID']);
                     if ($translation) {
                         $templateData['lang'][$language['abbr']]['theme'] = $translation['value'];
                         $templateData['lang'][$language['abbr']]['theme_id'] = $translation['translationID'];
                     }
                     $translation = $this->registry->getDbHelper('TranslationHelper')->findTranslation('email_body', $template['ID'], $language['langID']);
                     if ($translation) {
                         $templateData['lang'][$language['abbr']]['body'] = $translation['value'];
                         $templateData['lang'][$language['abbr']]['body_id'] = $translation['translationID'];
                     }
                 }
             }
             $projectTemplates[$ek] = $templateData;
         }
     }
     $this->component->arResult['projectTemplates'] = $projectTemplates;
     $errors = array();
     if (isset($_POST['send'])) {
         $validations = array();
         $required = array();
         foreach ($events as $ek => $event) {
             $validations[$ek . '_from'] = 'anything';
             $validations[$ek . '_to'] = 'anything';
             $required[] = $ek . '_from';
             $required[] = $ek . '_to';
         }
         $validator = new \Ecoplay\Form\Validator($validations, $required, array());
         if (!$validator->validate($_POST)) {
             $errors = $validator->getErrors();
         } else {
             foreach ($events as $ek => $event) {
                 // заполняем шаблоны для каждого события
                 $translations = array();
                 $templateID = 0;
                 if (array_key_exists($ek, $projectTemplates)) {
                     // шаблон уже есть в базе, обновляем его
                     $templateData = array('from' => trim($_POST[$ek . '_from']), 'to' => trim($_POST[$ek . '_to']), 'is_html' => isset($_POST[$ek . '_is_html']) ? 1 : 0);
                     // обрабатываем языки
                     foreach ($projectLanguages as $language) {
                         if ($language['is_default']) {
                             $templateData['theme'] = trim($_POST[$ek . '_' . $language['abbr'] . '_theme']);
                             $templateData['body'] = trim($_POST[$ek . '_' . $language['abbr'] . '_body']);
                         } else {
                             $translations[$language['langID']] = array('theme' => trim($_POST[$ek . '_' . $language['abbr'] . '_theme']), 'body' => trim($_POST[$ek . '_' . $language['abbr'] . '_body']), 'lang' => $language['abbr']);
                         }
                     }
                     $this->registry->getDbHelper('EmailHelper')->editProjectTemplate($projectTemplates[$ek]['id'], $templateData);
                     $templateID = $projectTemplates[$ek]['id'];
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'email_template', $templateID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $projectTemplatesSrc[$templateID]);
                 } else {
                     // шаблона в базе нет, добавляем его
                     $templateData = array('projectID' => $context['project']['projectID'], 'event' => $event['name'], 'from' => trim($_POST[$ek . '_from']), 'to' => trim($_POST[$ek . '_to']), 'is_html' => isset($_POST[$ek . '_is_html']) ? 1 : 0);
                     // обрабатываем языки
                     foreach ($projectLanguages as $language) {
                         if ($language['is_default']) {
                             $templateData['theme'] = trim($_POST[$ek . '_' . $language['abbr'] . '_theme']);
                             $templateData['body'] = trim($_POST[$ek . '_' . $language['abbr'] . '_body']);
                         } else {
                             $translations[$language['langID']] = array('theme' => trim($_POST[$ek . '_' . $language['abbr'] . '_theme']), 'body' => trim($_POST[$ek . '_' . $language['abbr'] . '_body']), 'lang' => $language['abbr']);
                         }
                     }
                     $templateID = $this->registry->getDbHelper('EmailHelper')->addProjectTemplate($templateData);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'email_template', $templateID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 }
                 foreach ($translations as $langID => $translation) {
                     if ($translation['theme']) {
                         $translationData = array('objectType' => 'email_theme', 'objectID' => $templateID, 'langID' => $langID, 'value' => $translation['theme'], 'projectID' => $context['project']['projectID']);
                         if ($projectTemplates[$ek]['lang'][$translation['lang']]['theme_id']) {
                             $this->registry->getDbHelper('TranslationHelper')->editTranslation($projectTemplates[$ek]['lang'][$translation['lang']]['theme_id'], $translationData);
                         } else {
                             $this->registry->getDbHelper('TranslationHelper')->addTranslation($translationData);
                         }
                     } elseif ($projectTemplates[$ek]['lang'][$translation['lang']]['theme_id']) {
                         // удаляем перевод
                         $this->registry->getDbHelper('TranslationHelper')->deleteTranslationByID($projectTemplates[$ek]['lang'][$translation['lang']]['theme_id']);
                     }
                     if ($translation['body']) {
                         $translationData = array('objectType' => 'email_body', 'objectID' => $templateID, 'langID' => $langID, 'value' => $translation['body'], 'projectID' => $context['project']['projectID']);
                         if ($projectTemplates[$ek]['lang'][$translation['lang']]['body_id']) {
                             $this->registry->getDbHelper('TranslationHelper')->editTranslation($projectTemplates[$ek]['lang'][$translation['lang']]['body_id'], $translationData);
                         } else {
                             $this->registry->getDbHelper('TranslationHelper')->addTranslation($translationData);
                         }
                     } elseif ($projectTemplates[$ek]['lang'][$translation['lang']]['body_id']) {
                         // удаляем перевод
                         $this->registry->getDbHelper('TranslationHelper')->deleteTranslationByID($projectTemplates[$ek]['lang'][$translation['lang']]['body_id']);
                     }
                 }
             }
             if (!isset($_GET['TYPE']) || !$_GET['TYPE']) {
                 LocalRedirect('/projects/' . $context['project']['projectID'] . '/settings/email/');
             } else {
                 LocalRedirect('/projects/' . $context['project']['projectID'] . '/settings/' . $_GET['TYPE'] . '/email/');
             }
         }
     }
     $viewHelper = new \Ecoplay\View\Helper();
     $context['APPLICATION']->SetPageProperty('pageMainTitle', 'Почтовые шаблоны');
     $navigationLinks = array(0 => array('link' => '/', 'title' => 'Главная'), 1 => array('link' => '/projects/', 'title' => 'Проекты'), 2 => array('link' => '/projects/' . $context['project']['projectID'] . '/continuing/stat/', 'title' => $context['project']['project_name']), 3 => array('title' => 'Почтовые шаблоны'));
     $context['APPLICATION']->SetPageProperty('navigation', $viewHelper->generateNavigation($navigationLinks));
     $this->component->arResult['errors'] = $viewHelper->prepareJsonErrors($errors);
     $this->component->IncludeComponentTemplate();
 }
Exemplo n.º 3
0
 public function execute($context)
 {
     $context['APPLICATION']->AddHeadScript('/js/forms.js');
     $context['APPLICATION']->AddHeadScript('/js/icheck/icheck.min.js');
     $context['APPLICATION']->SetAdditionalCSS('/js/icheck/skins/minimal/eco.css');
     if (isset($_POST['type'])) {
         if ($_POST['type'] == 'edit') {
             // находим участника
             $member = $this->registry->getDbHelper('MembersHelper')->findById($_POST['memberID']);
             if ($member['email'] != $_POST['email'] && $_POST['email']) {
                 $sameEmailMember = $this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($_POST['email'], $context['project']['projectID']);
                 $email = $sameEmailMember ? $member['email'] : $_POST['email'];
             } else {
                 $email = $member['email'];
             }
             $this->registry->getDbHelper('MembersHelper')->updateMember($member['projects_memberID'], $_POST['name'], $_POST['surname'], $_POST['position'], $email, $_POST['language'], $_POST['department']);
             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $member['projects_memberID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $member);
         } elseif ($_POST['type'] == 'exist') {
             if (isset($_POST['member_id'])) {
                 // проверяем, может этот участник уже привязан к ключу
                 $linkExist = $this->registry->getDbHelper('LinearProjectsHelper')->isMemberLinkedToGroupKey($context['project']['projectID'], $context['groupKey']['group_keyID'], intval($_POST['member_id']));
                 if (!$linkExist) {
                     // добавляем привязку
                     $itemID = $this->registry->getDbHelper('LinearProjectsHelper')->addGroupKeyMember(array('projectID' => $context['project']['projectID'], 'group_keyID' => $context['groupKey']['group_keyID'], 'memberID' => intval($_POST['member_id'])));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key_member', $itemID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 }
             }
         } else {
             // пробуем добавить участника
             $validations = array('name' => 'anything', 'surname' => 'anything', 'email' => 'email', 'position' => 'anything', 'department' => 'anything', 'language' => 'identifier');
             $required = array('name', 'email', 'language');
             $validator = new \Ecoplay\Form\Validator($validations, $required, array());
             if ($validator->validate($_POST)) {
                 // проверяем чтобы не было уже участника с таким email
                 if (!$this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($_POST['email'], $context['project']['projectID'])) {
                     $memberID = $this->registry->getDbHelper('MembersHelper')->addMember(trim($_POST["name"]), trim($_POST["surname"]), trim($_POST["position"]), trim($_POST["email"]), $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key'), intval($_POST["language"]), 1, 'new', trim($_POST['department']));
                     $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                     $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     // добавляем привязку
                     $itemID = $this->registry->getDbHelper('LinearProjectsHelper')->addGroupKeyMember(array('projectID' => $context['project']['projectID'], 'group_keyID' => $context['groupKey']['group_keyID'], 'memberID' => $memberID));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key_member', $itemID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 } else {
                     $this->component->arResult['statusError'] = 'Участник с таким email (' . $_POST['email'] . ') уже существует';
                 }
             }
         }
     }
     $selectedIDs = array();
     if (isset($_POST['items_ids'])) {
         if (isset($_POST['all']) && $_POST['all']) {
             $selectedIDs = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupKeyMembersIDsByProjectIDAndKeyID($context['project']['projectID'], $context['groupKey']['group_keyID']);
         } else {
             $selectedIDs = $_POST['items_ids'];
         }
         if (isset($_POST['mode'])) {
             if ($_POST['mode'] == 'delete') {
                 $deletedItems = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupKeyMembersByIDs($selectedIDs);
                 $this->registry->getDbHelper('LinearProjectsHelper')->deleteGroupKeyMembersByIDs($selectedIDs);
                 foreach ($deletedItems as $item) {
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key_member', $item['itemID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_DELETE, $item);
                 }
             } elseif ($_POST['mode'] == 'email') {
                 $emailedItems = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupKeyMembersByIDs($selectedIDs);
                 $this->registry->getDbHelper('LinearProjectsHelper')->editGroupKeyMembers($selectedIDs, array('send_email' => 1));
                 foreach ($emailedItems as $item) {
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key_member', $item['itemID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $item);
                 }
             }
         }
     }
     $arResult['selectedIDs'] = $selectedIDs;
     if ($_FILES["filepath"] && !$_FILES['filepath']['error']) {
         // обрабатываем загруженный файл
         $csvImporter = new \Ecoplay\Import\Csv($_FILES["filepath"]["tmp_name"], $_SERVER["DOCUMENT_ROOT"] . "/temp/csv/");
         $data = $csvImporter->parse();
         $inserted = $skipped = 0;
         $validations = array(0 => 'anything', 1 => 'anything', 2 => 'email', 3 => 'anything', 4 => 'anything');
         $required = array(2);
         $validator = new \Ecoplay\Form\Validator($validations, $required, array());
         $projectLangID = $this->registry->getModel('Projects')->getDefaultLangID($context['project']);
         $languageIndex = $csvImporter->getColumnIndex('Язык');
         $languagesIDs = array();
         $availableLanguages = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs(json_decode($context['project']['~languages']));
         foreach ($availableLanguages as $language) {
             $languagesIDs[$language['abbr']] = $language['langID'];
         }
         foreach ($data as $row) {
             // валидируем исходные данные
             if (!$validator->validate($row)) {
                 $skipped++;
             } elseif (!$row[0] && !$row[1]) {
                 // должно быть хотябы или имя, или фамилия
                 $skipped++;
             } else {
                 // ищем такого участника уже в базе
                 $member = $this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($row[2], $context['project']['projectID']);
                 if (!$member) {
                     // добавляем участника
                     // определяем язык по структуре
                     $staff = $this->registry->getDbHelper('MembersHelper')->findStaffByProjectIDAndEmail($context['project']['projectID'], $row[2]);
                     $langID = $languageIndex && $row[$languageIndex] && array_key_exists($row[$languageIndex], $languagesIDs) ? $languagesIDs[$row[$languageIndex]] : $projectLangID;
                     $memberID = $this->registry->getDbHelper('MembersHelper')->addMember($row[0], $row[1], $row[3], $row[2], $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key', false), $langID, 1, 'new', $row[4]);
                     $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                     $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 } else {
                     $memberID = $member['projects_memberID'];
                 }
                 if ($this->registry->getDbHelper('LinearProjectsHelper')->isMemberLinkedToGroupKey($context['project']['projectID'], $context['groupKey']['group_keyID'], $memberID)) {
                     // такой оцениваемый уже есть
                     $skipped++;
                 } else {
                     // добавляем привязку
                     $itemID = $this->registry->getDbHelper('LinearProjectsHelper')->addGroupKeyMember(array('projectID' => $context['project']['projectID'], 'group_keyID' => $context['groupKey']['group_keyID'], 'memberID' => intval($memberID)));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key_member', $itemID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     $inserted++;
                 }
             }
         }
         $this->component->arResult['statusSuccess'] = 'Импортировано: ' . $inserted . ', проигнорировано: ' . $skipped;
     }
     $cnt = $this->registry->getDbHelper('TestsHelper')->getGroupKeyLinkedMembersCount($context['project']['projectID'], $context['groupKey']['group_keyID']);
     $onPage = 100;
     $pagesCnt = ceil($cnt / $onPage);
     $page = $_GET['PAGE'] && $_GET['PAGE'] <= $pagesCnt ? intval($_GET['PAGE']) : 1;
     $this->component->arResult['cntInfo'] = $pagesCnt == 1 ? $cnt : 0;
     $members = $this->registry->getDbHelper('TestsHelper')->getGroupKeyLinkedMembers($context['project']['projectID'], $context['groupKey']['group_keyID'], $page, $onPage);
     $this->component->arResult['members'] = $members;
     $this->component->arResult['groupKey'] = $context['groupKey'];
     $languagesIDs = json_decode($context['project']['~languages']);
     $languagesSrc = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs($languagesIDs);
     $languages = array();
     foreach ($languagesSrc as $language) {
         $languages[$language['langID']] = $language['name'];
     }
     $this->component->arResult['languages'] = $languages;
     $this->component->IncludeComponentTemplate('linear/table');
     $navResult = new \CDBResult();
     $navResult->NavPageCount = ceil($cnt / $onPage);
     $navResult->NavPageNomer = $page;
     $navResult->NavNum = 1;
     $navResult->NavPageSize = $onPage;
     $navResult->NavRecordCount = $cnt;
     $navResult->nPageWindow = 11;
     $context['APPLICATION']->IncludeComponent('ecoplay:system.pagenavigation', '', array('NAV_RESULT' => $navResult, 'NAV_URL' => '/projects/' . $context['project']['projectID'] . '/settings/groupkeys/' . $context['groupKey']['group_keyID'] . '/members/', 'NAV_QUERY_STRING' => isset($_GET['checkAll']) ? 'checkAll=1' : ''));
     $viewHelper = new \Ecoplay\View\Helper();
     $context['APPLICATION']->SetPageProperty('pageMainTitle', 'Респонденты группового ключа');
     $context['APPLICATION']->SetPageProperty('navigation', $viewHelper->generateNavigation(array(0 => array('link' => '/', 'title' => 'Главная'), 1 => array('link' => '/projects/', 'title' => 'Проекты'), 2 => array('link' => '/projects/' . $context['project']['projectID'] . '/continuing/stat/', 'title' => $context['project']['project_name']), 3 => array('link' => '/projects/' . $context['project']['projectID'] . '/settings/groupkeys/', 'title' => ' Групповые ключи'), 4 => array('title' => $context['groupKey']['name']), 5 => array('title' => 'Список Респондентов'))));
     $this->component->IncludeComponentTemplate('linear/template');
 }
Exemplo n.º 4
0
 public function execute($context)
 {
     $context['APPLICATION']->AddHeadScript('/js/forms.js');
     $context['APPLICATION']->AddHeadScript('/js/icheck/icheck.min.js');
     $context['APPLICATION']->SetAdditionalCSS('/js/icheck/skins/minimal/eco.css');
     // проверка прав доступа к разделу
     if (!$this->registry->getModel('Auth')->checkAccess($_SESSION['accesses'], 'project_edit', $context['project']['projectID'])) {
         $this->registry->getModel('Auth')->restrict();
     }
     $sessionsSrc = $this->registry->getDbHelper('ProjectsHelper')->getSessionsByProjectId($context['project']['projectID']);
     $sessions = array();
     $sessionsNames = array();
     foreach ($sessionsSrc as $session) {
         $sessions[$session['sessionID']] = $session['name'];
         $sessionsNames[$session['name']] = $session['sessionID'];
     }
     if (isset($_POST['session_id']) && $_POST['mode'] == 'add') {
         // добавляем ключ
         $keyData = array('projectID' => $context['project']['projectID'], 'sessionID' => intval($_POST['session_id']), 'active' => 1, 'status' => 'active', 'access_key' => \Ecoplay\Helper\Db\BlanksHelper::uuid(), 'name' => $_POST['name'], 'is_need_complete_previous' => intval($_POST['is_need_complete_previous']), 'is_need_export' => intval($_POST['is_need_export']), 'fact_count' => intval($_POST['fact_count']), 'member_type' => $_POST['member_type']);
         if ($_POST['member_type'] == \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FLEXIBLE) {
             $keyData['plan_count'] = intval($_POST['plan_count']);
             $keyData['is_registration_available'] = intval($_POST['is_registration_available']);
         } else {
             $keyData['plan_count'] = 0;
             $keyData['is_registration_available'] = 0;
         }
         $keyID = $this->registry->getDbHelper('TestsHelper')->addGroupKey($keyData);
         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $keyID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
     } elseif (isset($_POST['session_id']) && $_POST['mode'] == 'update') {
         $key = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID(intval($_POST['key_id']));
         if ($key) {
             $keyData = array('sessionID' => intval($_POST['session_id']), 'name' => $_POST['name'], 'is_need_complete_previous' => intval($_POST['is_need_complete_previous']), 'fact_count' => intval($_POST['fact_count']), 'member_type' => $_POST['member_type'], 'is_need_export' => intval($_POST['is_need_export']));
             if ($_POST['member_type'] == \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FLEXIBLE) {
                 $keyData['plan_count'] = intval($_POST['plan_count']);
                 $keyData['is_registration_available'] = intval($_POST['is_registration_available']);
             } else {
                 $keyData['plan_count'] = 0;
                 $keyData['is_registration_available'] = 0;
             }
             $this->registry->getDbHelper('TestsHelper')->editGroupKey($key['group_keyID'], $keyData);
             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $key['group_keyID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $key);
         }
     } elseif ($_POST['mode'] == 'delete') {
         if (isset($_POST['all']) && $_POST['all']) {
             $selectedIDs = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupKeysIDsByProjectID($context['project']['projectID']);
         } else {
             $selectedIDs = $_POST['keys_ids'];
         }
         foreach ($selectedIDs as $keyID) {
             $key = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID(intval($keyID));
             if ($key) {
                 $this->registry->getDbHelper('TestsHelper')->editGroupKey($key['group_keyID'], array('status' => 'deleted', 'active' => '0'));
                 $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $key['group_keyID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_DELETE, $key);
             }
         }
     } elseif ($_POST['mode'] == 'activate') {
         foreach ($_POST['keys_ids'] as $keyID) {
             $key = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID(intval($keyID));
             if ($key) {
                 $this->registry->getDbHelper('TestsHelper')->editGroupKey($key['group_keyID'], array('status' => \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_STATUS_ACTIVE));
                 $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $key['group_keyID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $key);
             }
         }
     } elseif ($_POST['mode'] == 'deactivate') {
         foreach ($_POST['keys_ids'] as $keyID) {
             $key = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID(intval($keyID));
             if ($key) {
                 $this->registry->getDbHelper('TestsHelper')->editGroupKey($key['group_keyID'], array('status' => \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_STATUS_DISABLED));
                 $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $key['group_keyID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $key);
             }
         }
     } elseif ($_POST['mode'] == 'delay') {
         foreach ($_POST['keys_ids'] as $keyID) {
             $key = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID(intval($keyID));
             if ($key) {
                 $this->registry->getDbHelper('TestsHelper')->editGroupKey($key['group_keyID'], array('status' => \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_STATUS_ENDING));
                 $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $key['group_keyID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $key);
             }
         }
     } elseif ($_POST['mode'] == 'export') {
         if (isset($_POST['all']) && $_POST['all']) {
             $selectedIDs = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupKeysIDsByProjectID($context['project']['projectID']);
         } else {
             $selectedIDs = $_POST['keys_ids'];
         }
         $context['APPLICATION']->RestartBuffer();
         $csvContent = '"Название";"Группа";"ID ключа";"С регистрацией или без";"Плановое кол-во";"Ограничение на количество";"Продолжать прерванную сессию";"Ссылка";"Количество завершенных анкет";"Количество начатых анкет";"Процент"';
         $exportedKeys = $this->registry->getDbHelper('LinearProjectsHelper')->getGroupsKeysExportData($context['project']['projectID'], $selectedIDs);
         foreach ($exportedKeys as $key) {
             //$percent = $key['plan_count'] ? round($key['respondents_count']/$key['plan_count']*100, 2) : 0;
             $percent = $key['plan_count'] ? round($key['finished_seances_count'] / $key['plan_count'] * 100, 2) : 0;
             $csvContent .= "\n" . '"' . addslashes($key['~name']) . '";"' . addslashes($sessions[$key['sessionID']]) . '";"' . $key['group_keyID'] . '";' . '"' . $key['is_registration_available'] . '";"' . $key['plan_count'] . '";"' . $key['fact_count'] . '";"' . $key['is_need_complete_previous'] . '";"http://' . SITE_HOST . '/g/' . $key['access_key'] . '";' . $key['finished_seances_count'] . ';' . $key['seances_count'] . ';' . $percent . ' %';
         }
         header("Cache-Control: public");
         header("Content-Description: File Transfer");
         header("Content-Disposition: attachment; filename=export.csv");
         header("Content-type: text/csv");
         $csvContent = iconv('UTF-8', 'Windows-1251', $csvContent);
         header("Content-Length: " . mb_strlen($csvContent, 'Windows-1251'));
         echo $csvContent;
         die;
     }
     if ($_FILES["filepath"] && !$_FILES['filepath']['error']) {
         // обрабатываем загруженный файл
         $csvImporter = new \Ecoplay\Import\Csv($_FILES["filepath"]["tmp_name"], $_SERVER["DOCUMENT_ROOT"] . "/temp/csv/");
         $data = $csvImporter->parse();
         $inserted = $skipped = 0;
         $validations = array(0 => 'anything', 1 => 'anything');
         $required = array(0, 1);
         $validator = new \Ecoplay\Form\Validator($validations, $required, array());
         $registrationAvailableIndex = $csvImporter->getColumnIndex('С регистрацией или без');
         $needCompletePreviousIndex = $csvImporter->getColumnIndex('Продолжать прерванную сессию');
         $planCountIndex = $csvImporter->getColumnIndex('Плановое кол-во');
         $factCountIndex = $csvImporter->getColumnIndex('Ограничение на количество');
         $memberTypeIndex = $csvImporter->getColumnIndex('Список участников');
         $keyIDIndex = $csvImporter->getColumnIndex('ID ключа');
         $notExistSessions = array();
         foreach ($data as $row) {
             // валидируем исходные данные
             if (!$validator->validate($row)) {
                 $skipped++;
             } else {
                 if (!array_key_exists($row[1], $sessionsNames)) {
                     if (!in_array($row[1], $notExistSessions)) {
                         $notExistSessions[] = $row[1];
                     }
                     $skipped++;
                 } else {
                     $memberType = $memberTypeIndex && $row[$memberTypeIndex] == 'Известен' ? \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FIXED_LIST : \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FLEXIBLE;
                     $keyData = array('sessionID' => $sessionsNames[$row[1]], 'name' => $row[0], 'is_need_complete_previous' => $needCompletePreviousIndex && $row[$needCompletePreviousIndex] == 1 ? 1 : 0, 'fact_count' => $factCountIndex ? intval($row[$factCountIndex]) : 0, 'member_type' => $memberType);
                     if ($memberType == \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FLEXIBLE) {
                         $keyData['plan_count'] = $planCountIndex ? intval($row[$planCountIndex]) : 0;
                         $keyData['is_registration_available'] = $registrationAvailableIndex && $row[$registrationAvailableIndex] == 0 ? 0 : 1;
                     } else {
                         $keyData['plan_count'] = 0;
                         $keyData['is_registration_available'] = 0;
                     }
                     $updatedKeyID = 0;
                     if ($keyIDIndex && $row[$keyIDIndex]) {
                         $updatedKey = $this->registry->getDbHelper('TestsHelper')->findGroupKeyByID($row[$keyIDIndex]);
                         if ($updatedKey && $updatedKey['projectID'] == $context['project']['projectID']) {
                             $updatedKeyID = $updatedKey['group_keyID'];
                         }
                     }
                     if ($updatedKeyID) {
                         $keyID = $updatedKeyID;
                         $this->registry->getDbHelper('TestsHelper')->editGroupKey($keyID, $keyData);
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $keyID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $updatedKey);
                     } else {
                         $keyData['access_key'] = \Ecoplay\Helper\Db\BlanksHelper::uuid();
                         $keyData['active'] = 1;
                         $keyData['status'] = 'active';
                         $keyData['projectID'] = $context['project']['projectID'];
                         $keyID = $this->registry->getDbHelper('TestsHelper')->addGroupKey($keyData);
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'group_key', $keyID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     }
                     $inserted++;
                 }
             }
             $this->component->arResult['statusSuccess'] = 'Импортировано: ' . $inserted . ', проигнорировано: ' . $skipped;
             if (count($notExistSessions)) {
                 $this->component->arResult['action_warning'] = 'Групповые ключи для групп ' . implode(', ', $notExistSessions) . ' проигнорированы, так как указанные группы не существуют.';
             }
         }
     }
     $cnt = $this->registry->getDbHelper('TestsHelper')->getProjectGroupKeysCount($context['project']['projectID']);
     $onPage = 100;
     $pagesCnt = ceil($cnt / $onPage);
     $page = $_GET['PAGE'] && $_GET['PAGE'] <= $pagesCnt ? intval($_GET['PAGE']) : 1;
     $this->component->arResult['cntInfo'] = $pagesCnt == 1 ? $cnt : 0;
     // получаем список существующих групповых ключей
     $groupKeys = $this->registry->getDbHelper('TestsHelper')->getGroupKeysByProjectIDPaged($context['project']['projectID'], $page, $onPage);
     // количество респондентов для известных
     $fixedKeysIDs = array();
     foreach ($groupKeys as $key) {
         if ($key['member_type'] == \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_MEMBER_TYPE_FIXED_LIST) {
             $fixedKeysIDs[] = $key['group_keyID'];
         }
     }
     if (count($fixedKeysIDs)) {
         $this->component->arResult['fixedCnt'] = $this->registry->getDbHelper('TestsHelper')->getFixedKeysMembersCount($fixedKeysIDs);
     }
     $viewHelper = new \Ecoplay\View\Helper();
     /*foreach ($groupKeys as $ind => $key) {
         $groupKeys[$ind]['real_sessionID'] = $key['sessionID'];
         $groupKeys[$ind]['statusd'] = $key['status'];
       }
           
       $this->component->arResult['table_data'] = str_replace("'", "\'", $viewHelper->prepareJsonDataForTable($groupKeys,
         array('group_keyID', 'access_key', 'sessionID', 'status', 'statusd', 'name', 'cnt', 'is_registration_available', 'is_need_complete_previous', 'plan_count', 'fact_count', 'real_sessionID'),
         array(), array('sessionID' => $sessions)));
       $this->component->arResult['cnt'] = count($groupKeys);*/
     $this->component->arResult['sessions'] = $sessions;
     $this->component->arResult['memberTypes'] = \Ecoplay\Helper\Db\TestsHelper::getGroupKeyMemberTypes();
     $this->component->arResult['memberTypesDetailed'] = \Ecoplay\Helper\Db\TestsHelper::getGroupKeyMemberTypesDetailed();
     $this->component->arResult['statuses'] = \Ecoplay\Helper\Db\TestsHelper::getGroupKeyStatuses();
     $this->component->arResult['groupKeys'] = $groupKeys;
     // выводим таблицу с данными
     $this->component->IncludeComponentTemplate('linear/table');
     $navResult = new \CDBResult();
     $navResult->NavPageCount = ceil($cnt / $onPage);
     $navResult->NavPageNomer = $page;
     $navResult->NavNum = 1;
     $navResult->NavPageSize = $onPage;
     $navResult->NavRecordCount = $cnt;
     $navResult->nPageWindow = 11;
     $context['APPLICATION']->IncludeComponent('ecoplay:system.pagenavigation', '', array('NAV_RESULT' => $navResult, 'NAV_URL' => '/projects/' . $context['project']['projectID'] . '/settings/groupkeys/', 'NAV_QUERY_STRING' => isset($_GET['checkAll']) ? 'checkAll=1' : ''));
     $this->component->arResult['projectID'] = $context['project']['projectID'];
     $context['APPLICATION']->SetPageProperty('pageMainTitle', 'Групповые ключи');
     $context['APPLICATION']->SetPageProperty('navigation', $viewHelper->generateNavigation(array(0 => array('link' => '/', 'title' => 'Главная'), 1 => array('link' => '/projects/', 'title' => 'Проекты'), 2 => array('link' => '/projects/' . $context['project']['projectID'] . '/continuing/stat/', 'title' => $context['project']['project_name']), 3 => array('title' => 'Групповые ключи'))));
     $this->component->IncludeComponentTemplate('linear/template');
 }
Exemplo n.º 5
0
 public function execute($context)
 {
     // проверка прав доступа к разделу
     if (!$this->registry->getModel('Auth')->checkAccess($_SESSION['accesses'], 'members', $context['project']['projectID'])) {
         $this->registry->getModel('Auth')->restrict();
     }
     $context['APPLICATION']->AddHeadScript('/js/forms.js');
     $context['APPLICATION']->AddHeadScript('/js/icheck/icheck.min.js');
     $context['APPLICATION']->SetAdditionalCSS('/js/icheck/skins/minimal/eco.css');
     $availableSessionsIDs = $this->registry->getModel('Auth')->getAvailableSessions($_SESSION['accesses'], $context['project']['projectID'], $context['project']['project_type']);
     $viewHelper = new \Ecoplay\View\Helper();
     if (count($availableSessionsIDs)) {
         // нормогруппы для генераторов отчетов
         $projectSettings = json_decode($context['project']['~param_roles'], true);
         $haveValuation = false;
         if (array_key_exists('rgenerators', $projectSettings) && $projectSettings['rgenerators']) {
             $generatorsSrc = $this->registry->getDbHelper('ReportsHelper')->getGeneratorsCollectionByIds($projectSettings['rgenerators']);
             foreach ($generatorsSrc as $generator) {
                 if ($generator['use_valuation_group']) {
                     $haveValuation = true;
                     break;
                 }
             }
         }
         if ($haveValuation) {
             //  определяем тип админа (экопси или нет)
             $isEcopsy = false;
             $groups = $this->registry->getDbHelper('UsersHelper')->getUserGroups($context['USER']->GetID());
             if (count($groups) > 1) {
                 $isEcopsy = true;
             } else {
                 $clientID = $this->registry->getDbHelper('UsersHelper')->getUserClient($context['USER']->GetID());
                 if ($clientID == \Ecoplay\Helper\Db\ClientsHelper::ECOPSY_CLIENT_ID) {
                     $isEcopsy = true;
                 }
             }
             $this->component->arResult['valuationGroups'] = $this->registry->getDbHelper('TestsHelper')->getProjectValuationGroups($context['project']['projectID'], $isEcopsy);
         }
         $this->component->arResult['haveValuation'] = $haveValuation;
         if (isset($_POST['type'])) {
             if ($_POST['type'] == 'edit') {
                 // находим респондента
                 $respondent = $this->registry->getDbHelper('MembersHelper')->findRespondentById($_POST['respondentID']);
                 if ($respondent) {
                     // обновляем участника
                     $member = $this->registry->getDbHelper('MembersHelper')->findById($respondent['project_memberID']);
                     if ($member['email'] != $_POST['email'] && $_POST['email']) {
                         $sameEmailMember = $this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($_POST['email'], $context['project']['projectID']);
                         $email = $sameEmailMember ? $member['email'] : $_POST['email'];
                     } else {
                         $email = $member['email'];
                     }
                     $this->registry->getDbHelper('MembersHelper')->updateMember($respondent['project_memberID'], $_POST['name'], $_POST['surname'], $_POST['position'], $email, $_POST['language'], $_POST['department']);
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $respondent['project_memberID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $member);
                     if ($respondent['sessionID'] != $_POST['session_id']) {
                         $seance = $this->registry->getDbHelper('TestsSeancesHelper')->findSeanceByProjectIDAndRespondentID($context['project']['projectID'], $respondent['respondentID']);
                         if (!$seance) {
                             $this->registry->getDbHelper('MembersHelper')->editRespondent($respondent['respondentID'], array('sessionID' => $_POST['session_id']));
                             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                         }
                     }
                 }
                 echo 'Редактирование<br/>';
             } elseif ($_POST['type'] == 'exist') {
                 if (isset($_POST['member_id'])) {
                     // проверяем, может уже есть респондент с таким участником
                     //$existRespondent = $this->registry->getDbHelper('MembersHelper')->findRespondentByMemberID($context['project']['projectID'], $_POST['member_id']);
                     //if (!$existRespondent) {
                     // добавляем респондента
                     $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => intval($_POST['member_id']), 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => intval($_POST['session_id']), 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
                     $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                 }
                 //}
             } else {
                 // пробуем добавить участника
                 $validations = array('name' => 'anything', 'surname' => 'anything', 'email' => 'email', 'position' => 'anything', 'department' => 'anything', 'language' => 'identifier');
                 $required = array('name', 'email', 'language');
                 $validator = new \Ecoplay\Form\Validator($validations, $required, array());
                 if ($validator->validate($_POST)) {
                     // проверяем чтобы не было уже участника с таким email
                     if (!$this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($_POST['email'], $context['project']['projectID'])) {
                         $memberID = $this->registry->getDbHelper('MembersHelper')->addMember(trim($_POST["name"]), trim($_POST["surname"]), trim($_POST["position"]), trim($_POST["email"]), $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key'), intval($_POST["language"]), 1, 'new', trim($_POST['department']));
                         $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                         $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                         // добавляем респондента
                         $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => $memberID, 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => intval($_POST['session_id']), 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     } else {
                         $this->component->arResult['statusError'] = 'Участник с таким email (' . $_POST['email'] . ') уже существует';
                     }
                 }
             }
         }
         if ($_FILES["filepath"] && !$_FILES['filepath']['error']) {
             $sessionID = (int) $_POST["fgroup"];
             if ($sessionID) {
                 $session = $this->registry->getDbHelper('TestsHelper')->findSessionByID($sessionID);
             }
             // обрабатываем загруженный файл
             $csvImporter = new \Ecoplay\Import\Csv($_FILES["filepath"]["tmp_name"], $_SERVER["DOCUMENT_ROOT"] . "/temp/csv/");
             $data = $csvImporter->parse();
             $sessionIndex = $csvImporter->getColumnIndex('Группа');
             if (!((!$sessionIndex || !$data[0][$sessionIndex]) && (!$sessionID || !$session))) {
                 // определяем группу
                 if ($sessionIndex && $data[0][$sessionIndex]) {
                     // ищем группу
                     $session = $this->registry->getDbHelper('TestsHelper')->findSessionByProjectIDAndName($context['project']['projectID'], $data[0][$sessionIndex]);
                     if ($session) {
                         $sessionID = $session['sessionID'];
                     } else {
                         /*$session = array(
                             'name'  => $data[0][$sessionIndex],
                             'active'  => 1,
                             'status'  => 'active',
                             'projectID'  => $context['project']['projectID'],
                           );
                           $sessionID = $this->registry->getDbHelper('TestsHelper')->addSession($session);
                           $session['sessionID'] = $sessionID;*/
                         $sessionID = 0;
                     }
                 }
                 $inserted = $skipped = 0;
                 $validations = array(0 => 'anything', 1 => 'anything', 2 => 'email', 3 => 'anything', 4 => 'anything');
                 $required = array(2);
                 $validator = new \Ecoplay\Form\Validator($validations, $required, array());
                 $projectLangID = $this->registry->getModel('Projects')->getDefaultLangID($context['project']);
                 $languageIndex = $csvImporter->getColumnIndex('Язык');
                 $languagesIDs = array();
                 $availableLanguages = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs(json_decode($context['project']['~languages']));
                 foreach ($availableLanguages as $language) {
                     $languagesIDs[$language['abbr']] = $language['langID'];
                 }
                 $rowIndex = 0;
                 $skippedRows = array();
                 foreach ($data as $row) {
                     $rowIndex++;
                     if ($sessionIndex && $row[$sessionIndex] && (!$sessionID || $row[$sessionIndex] != $session['name'])) {
                         // ищем группу
                         $session = $this->registry->getDbHelper('TestsHelper')->findSessionByProjectIDAndName($context['project']['projectID'], $row[$sessionIndex]);
                         if ($session) {
                             $sessionID = $session['sessionID'];
                         } else {
                             /*$session = array(
                                 'name'  => $row[$sessionIndex],
                                 'active'  => 1,
                                 'status'  => 'active',
                                 'projectID'  => $context['project']['projectID'],
                               );
                               $sessionID = $this->registry->getDbHelper('TestsHelper')->addSession($session);
                               $session['sessionID'] = $sessionID;*/
                             $sessionID = 0;
                         }
                     }
                     if (!$sessionID) {
                         $skipped++;
                         $skippedRows[] = $rowIndex;
                         continue;
                     }
                     // валидируем исходные данные
                     if (!$validator->validate($row)) {
                         $skipped++;
                         $skippedRows[] = $rowIndex;
                     } elseif (!$row[0] && !$row[1]) {
                         // должно быть хотябы или имя, или фамилия
                         $skipped++;
                         $skippedRows[] = $rowIndex;
                     } else {
                         // ищем такого участника уже в базе
                         $member = $this->registry->getDbHelper('MembersHelper')->findByEmailAndProjectId($row[2], $context['project']['projectID']);
                         if (!$member) {
                             // добавляем участника
                             // определяем язык по структуре
                             $staff = $this->registry->getDbHelper('MembersHelper')->findStaffByProjectIDAndEmail($context['project']['projectID'], $row[2]);
                             $langID = $languageIndex && $row[$languageIndex] && array_key_exists($row[$languageIndex], $languagesIDs) ? $languagesIDs[$row[$languageIndex]] : $projectLangID;
                             $memberID = $this->registry->getDbHelper('MembersHelper')->addMember($row[1], $row[0], $row[3], $row[2], $context['project']['projectID'], $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key', false), $langID, 1, 'new', $row[4]);
                             $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                             $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'member', $memberID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                         } else {
                             $memberID = $member['projects_memberID'];
                         }
                         if ($this->registry->getDbHelper('MembersHelper')->findRespondentByProjectIDAndSessionIDAndMemberID($context['project']['projectID'], $sessionID, $memberID)) {
                             // такой оцениваемый уже есть
                             $skipped++;
                             $skippedRows[] = $rowIndex;
                         } else {
                             $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('projectID' => $context['project']['projectID'], 'sessionID' => $sessionID, 'project_memberID' => $memberID, 'active' => 1, 'status' => 'new', 'stat1_assessID' => 0, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key', false), 'stat1_roleID' => 0));
                             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondentID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                             $inserted++;
                         }
                     }
                 }
                 $this->component->arResult['statusSuccess'] = 'Импортировано: ' . $inserted . ', проигнорировано: ' . $skipped . ($skipped ? ' (строки ' . implode(', ', $skippedRows) . ')' : '');
             }
         }
         $statuses = $this->registry->getDbHelper('MembersHelper')->getTestingRespondentsStatusesNames();
         $this->component->arResult['statuses'] = $statuses;
         $sorts = array('respondentID' => 'respondentID', 'name' => 'name', 'surname' => 'surname', 'email' => 'email', 'position' => 'position', 'session' => 'sessionID', 'status' => 'status', 'private_lk_access_key' => 'private_lk_access_key', 'last_email' => 'last_email', 'last_action' => 'last_entrance');
         if (isset($_GET['sort']) && array_key_exists($_GET['sort'], $sorts)) {
             $sort = $_GET['sort'];
         } else {
             $sort = 'respondentID';
         }
         $order = isset($_GET['order']) && in_array($_GET['order'], array('asc', 'desc')) ? $_GET['order'] : 'asc';
         $filterQueryString = DataFilter::getFilterQueryString($_GET);
         $this->component->arResult['filterQueryString'] = $filterQueryString;
         $sessions = $this->registry->getDbHelper('TestsHelper')->getSessionsByProjectID($context['project']['projectID']);
         $userSessions = array();
         foreach ($sessions as $session) {
             if (in_array($session['sessionID'], $availableSessionsIDs)) {
                 $userSessions[$session['sessionID']] = $session['name'];
             }
         }
         $this->component->arResult['userSessions'] = $userSessions;
         // настройки фильтров для данных
         $filters = array(0 => array('title' => 'Имя', 'name' => 'name', 'type' => 'text', 'data_type' => 'string', 'field' => 'm.`name`'), 1 => array('title' => 'Фамилия', 'name' => 'surname', 'type' => 'text', 'data_type' => 'string', 'field' => 'm.`surname`'), 2 => array('title' => 'ID', 'name' => 'id', 'type' => 'text', 'data_type' => 'number', 'field' => 'r.`respondentID`'), 3 => array('title' => 'Текст', 'name' => 'text', 'type' => 'text', 'data_type' => 'string', 'field' => array('m.`search_text`')), 4 => array('title' => 'Статус ', 'name' => 'status', 'type' => 'select', 'data_type' => 'string', 'field' => 'r.`status`', 'values' => array(0 => 'Любой') + $statuses), 5 => array('title' => 'Группа ', 'name' => 'session_id', 'type' => 'select', 'data_type' => 'number', 'field' => 'r.`sessionID`', 'values' => array(0 => 'Любая') + $userSessions), 6 => array('title' => 'В архиве ', 'name' => 'is_archive', 'type' => 'select', 'data_type' => 'number', 'field' => 'r.`is_archive`', 'values' => array(-1 => '-', 0 => 'Нет', 1 => 'Да'), 'explicit' => 1));
         $filterData = array('FILTERS' => $filters, 'BASE_URL' => '/projects/' . $context['project']['projectID'] . '/groups/respondents/', 'SORT' => $sort, 'ORDER' => $order);
         // проверяем, введен ли фильтр
         $filterValue = DataFilter::getFilterValue($filters, $_GET, $this->registry->getDbConnect());
         if ($filterValue['valid']) {
             $filterData = array_merge($filterData, $filterValue);
         }
         // компонент отображения фильтра
         $context['APPLICATION']->IncludeComponent('ecoplay:data.filter', '', $filterData);
         // выполняем с респондентами действия
         if (isset($_POST['respondents_ids'])) {
             if (isset($_POST['all']) && $_POST['all']) {
                 $selectedIDs = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsIDsByProjectIDAndSessionsIDs($context['project']['projectID'], $availableSessionsIDs, $filterValue['filter_strings']);
             } else {
                 $selectedIDs = $_POST['respondents_ids'];
             }
             if (isset($_POST['mode'])) {
                 if ($_POST['mode'] == 'delete') {
                     $deletedRespondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByIDs($selectedIDs);
                     $this->registry->getDbHelper('MembersHelper')->deleteRespondentsByIDs($selectedIDs);
                     foreach ($deletedRespondents as $respondent) {
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_DELETE, $respondent);
                     }
                 } elseif ($_POST['mode'] == 'zip') {
                     $editedRespondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByIDs($selectedIDs);
                     $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array('is_archive' => 1));
                     foreach ($editedRespondents as $respondent) {
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                     }
                 } elseif ($_POST['mode'] == 'unzip') {
                     $editedRespondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByIDs($selectedIDs);
                     $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array('is_archive' => 0));
                     foreach ($editedRespondents as $respondent) {
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                     }
                 } elseif ($_POST['mode'] == 'mail_resend') {
                     $editedRespondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByIDs($selectedIDs);
                     $membersIds = array(0);
                     foreach ($editedRespondents as $respondent) {
                         $membersIds[intval($respondent["project_memberID"])] = intval($respondent["project_memberID"]);
                     }
                     $selectedMemebers = $this->registry->getDbHelper('MembersHelper')->getMembersByIDs($membersIds);
                     $languagesIDs = json_decode($context['project']['~languages']);
                     foreach ($selectedMemebers as $selectedMemeber) {
                         if ($selectedMemeber["email"] != "") {
                             $smtpMail = \Ecoplay\Model\SmtpMail::getInstance($this->registry->getDbConnect(), SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD);
                             $smtpMail->sendFromTemplate($context['project']['projectID'], 'MailEvent_Testing_MailResend', $languagesIDs[0], array("RESPONDENT" => $selectedMemeber["name"] . " " . $selectedMemeber["surname"], "RESPONDENT_LK_LINK" => 'http://' . SITE_HOST . '/enter/' . $selectedMemeber['private_lk_access_key'] . "/", 'EMAIL_TO' => $selectedMemeber["email"], 'EMAIL_FROM' => EMAIL_FROM), 'member', $selectedMemeber['projects_memberID']);
                         }
                     }
                 } elseif ($_POST['mode'] == 'reports') {
                     $valid = false;
                     $params = array();
                     if ($haveValuation) {
                         if ($_POST['valuation_group']) {
                             // валидируем выбранную нормогруппу
                             $valuationGroup = $this->registry->getDbHelper('TestsHelper')->findValuationGroupByID(intval($_POST['valuation_group']));
                             if ($valuationGroup) {
                                 $params['valuationGroupID'] = $valuationGroup['vgroupID'];
                                 $valid = true;
                             }
                         }
                     } else {
                         $valid = true;
                     }
                     if ($valid) {
                         // Создаем задачу на генерацию отчетов
                         $taskID = $this->registry->getDbHelper('TasksHelper')->addTask(array('name' => '', 'type' => \Ecoplay\Helper\Db\TasksHelper::TASK_TYPE_REPORT, 'params' => json_encode(array_merge($params, array('projectID' => $context['project']['projectID'], 'respondentsIDs' => $selectedIDs))), 'userID' => $context['USER']->GetID(), 'status' => \Ecoplay\Helper\Db\TasksHelper::TASK_STATUS_NEW, 'dt_created' => date('d-m-Y H:i:s')));
                         $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'task', $taskID, \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_ADD, null);
                     }
                 } else {
                     $newStatus = false;
                     switch ($_POST['mode']) {
                         case 'to_new':
                             $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_NEW;
                             break;
                         case 'to_waiting':
                             $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_WAITING;
                             break;
                         case 'to_active':
                             $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE;
                             break;
                         case 'to_complete':
                             $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_COMPLETE;
                             break;
                             /*case 'to_report':
                                 $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_REPORT;
                                 break;
                               case 'to_archive':
                                 $newStatus = \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ARCHIVE;
                                 break;*/
                     }
                     if ($newStatus) {
                         $editedRespondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByIDs($selectedIDs);
                         $this->registry->getDbHelper('MembersHelper')->editRespondents($selectedIDs, array('status' => $newStatus));
                         foreach ($editedRespondents as $respondent) {
                             $this->registry->getModel('ActionsLogger')->log($context['USER']->GetID(), 'respondent', $respondent['respondentID'], \Ecoplay\Helper\Db\LogsHelper::ACTION_TYPE_CHANGE, $respondent);
                         }
                     }
                 }
             }
         }
         $arResult['selectedIDs'] = $selectedIDs;
         // получаем респондентов проекта
         $cnt = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsCountByProjectIDAndSessionsIDs($context['project']['projectID'], $availableSessionsIDs, $filterValue['filter_strings']);
         $onPage = 100;
         $pagesCnt = ceil($cnt / $onPage);
         $page = $_GET['PAGE'] && $_GET['PAGE'] <= $pagesCnt ? intval($_GET['PAGE']) : 1;
         $respondents = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsByProjectIDAndSessionsIDsPaged($context['project']['projectID'], $availableSessionsIDs, $page, $onPage, $sorts[$sort], $order, $filterValue['filter_strings']);
         $this->component->arResult['respondents'] = $respondents;
         $this->component->arResult['sort'] = $sort;
         $this->component->arResult['order'] = $order;
         $this->component->arResult['cntInfo'] = $pagesCnt == 1 ? $cnt : 0;
         // инфа для редактирования
         $respondentsJson = array();
         $respondentsIDs = array();
         foreach ($respondents as $respondent) {
             $respondentsJson[$respondent['respondentID']] = array('name' => $respondent['name'], 'surname' => $respondent['surname'], 'email' => $respondent['email'], 'position' => $respondent['position'], 'department' => $respondent['department'], 'langID' => $respondent['langID'], 'sessionID' => $respondent['sessionID']);
             $respondentsIDs[] = $respondent['respondentID'];
         }
         $jsonRespondents = json_encode($respondentsJson);
         $jsonRespondents = str_replace("'", "\\'", $jsonRespondents);
         $jsonRespondents = str_replace("\\", "\\\\", $jsonRespondents);
         $this->component->arResult['json_respondents'] = $jsonRespondents;
         // отчеты респондентов
         $reports = array();
         if (count($respondentsIDs)) {
             $reportsSrc = $this->registry->getDbHelper('ReportsHelper')->getReportsByProjectIDAndRespondentsIDs($context['project']['projectID'], $respondentsIDs);
             foreach ($reportsSrc as $report) {
                 if (!array_key_exists($report['stat1_respondentID'], $reports)) {
                     $reports[$report['stat1_respondentID']] = array('reportID' => $report['generated_reportID'], 'cnt' => 1);
                 } else {
                     $reports[$report['stat1_respondentID']]['cnt']++;
                     if ($report['generated_reportID'] > $reports[$report['stat1_respondentID']]['reportID']) {
                         $reports[$report['stat1_respondentID']]['reportID'] = $report['generated_reportID'];
                     }
                 }
             }
         }
         $this->component->arResult['reports'] = $reports;
         // инфа для построения прогресса
         $this->component->arResult['progress_settings'] = $this->registry->getModel('Tests')->getProjectProgressSettings($context['project']['projectID']);
         // статистика по статусам
         $get = $_GET;
         if (array_key_exists('status_fvalue', $get)) {
             unset($get['status_fvalue']);
         }
         $filterValue = DataFilter::getFilterValue($filters, $get, $this->registry->getDbConnect());
         $statusesStatSrc = $this->registry->getDbHelper('TestsSeancesHelper')->getRespondentsStatusesStat($context['project']['projectID'], $availableSessionsIDs, $filterValue['filter_strings']);
         $statusesStat = array();
         $allStatusesCnt = 0;
         foreach ($statuses as $status => $name) {
             $statusesStat[$status] = 0;
         }
         foreach ($statusesStatSrc as $stat) {
             //foreach ($respondents as $respondent) {
             $statusesStat[$stat['status']] += $stat['cnt'];
             $allStatusesCnt += $stat['cnt'];
         }
         $this->component->arResult['statuses_stat'] = $statusesStat;
         $this->component->arResult['all_statuses_cnt'] = $allStatusesCnt;
         $this->component->IncludeComponentTemplate("testing_statuses_filter");
         $navResult = new \CDBResult();
         $navResult->NavPageCount = ceil($cnt / $onPage);
         $navResult->NavPageNomer = $page;
         $navResult->NavNum = 1;
         $navResult->NavPageSize = $onPage;
         $navResult->NavRecordCount = $cnt;
         $navResult->nPageWindow = 11;
         $context['APPLICATION']->IncludeComponent('ecoplay:system.pagenavigation', '', array('NAV_RESULT' => $navResult, 'NAV_URL' => '/projects/' . $context['project']['projectID'] . '/groups/respondents/', 'NAV_QUERY_STRING' => 'sort=' . $sort . '&order=' . $order . ($filterQueryString ? '&' . $filterQueryString : '') . (isset($_GET['checkAll']) ? '&checkAll=1' : '')));
         $this->component->arResult['sessions'] = $sessions;
         $packagesIDs = array();
         foreach ($sessions as $session) {
             if (!in_array($session['packageID'], $packagesIDs)) {
                 $packagesIDs[] = $session['packageID'];
             }
         }
         $this->component->arResult['packages'] = $this->registry->getDbHelper('TestsHelper')->getPackagesByIDs($packagesIDs);
         $languagesIDs = json_decode($context['project']['~languages']);
         $languagesSrc = $this->registry->getDbHelper('TranslationHelper')->getLanguagesByIDs($languagesIDs);
         $languages = array();
         foreach ($languagesSrc as $language) {
             $languages[$language['langID']] = $language['name'];
         }
         $this->component->arResult['languages'] = $languages;
     } else {
         $this->component->arResult['respondents'] = null;
     }
     $context['APPLICATION']->SetPageProperty('pageMainTitle', 'Тестируемые');
     $context['APPLICATION']->SetPageProperty('navigation', $viewHelper->generateNavigation(array(0 => array('link' => '/', 'title' => 'Главная'), 1 => array('link' => '/projects/', 'title' => 'Проекты'), 2 => array('link' => '/projects/' . $context['project']['projectID'] . '/continuing/stat/', 'title' => $context['project']['project_name']), 3 => array('title' => 'Тестируемые'))));
     $this->component->arResult['canReports'] = $this->registry->getModel('Auth')->checkAccess($_SESSION['accesses'], 'reports', $context['project']['projectID']);
     $this->component->IncludeComponentTemplate("template_testing");
 }
Exemplo n.º 6
0
 public function execute($context)
 {
     $langID = $this->registry->getModel('Projects')->getDefaultLangID($context['project']);
     $lang = $this->registry->getDbHelper('TranslationHelper')->findLanguageByID($langID);
     $translator = new \Ecoplay\Model\Translation($this->registry->getDbConnect(), $lang['abbr'], $_SERVER["DOCUMENT_ROOT"] . '/lang/', $this->registry);
     $this->component->arResult['translator'] = $translator;
     $projectViewSettings = $context['project']['param_lk'] ? (array) json_decode($context['project']['~param_lk']) : array();
     $this->component->arResult['projectViewSettings'] = $projectViewSettings;
     // кол-во респондентов, зрарегистрированных по этому ключу
     $existCnt = $this->registry->getDbHelper('TestsHelper')->getGroupKeyRespondentsCount($context['project']['projectID'], $context['groupKey']['group_keyID']);
     if ($context['groupKey']['fact_count'] && $existCnt >= $context['groupKey']['fact_count']) {
         $this->component->IncludeComponentTemplate('testing/limit');
     } elseif ($context['groupKey']['status'] != \Ecoplay\Helper\Db\TestsHelper::GROUP_KEY_STATUS_ACTIVE) {
         $this->component->IncludeComponentTemplate('testing/disabled');
     } else {
         /*$context['APPLICATION']->IncludeComponent("ecoplay:front.header", '', array(
            'TRANSLATOR'  => $translator,
            'MODE'  => 'blank',
            'MEMEBER_KEY'  => false,
            'SETTINGS'  => $projectViewSettings,
            'ADDON_CSS' => false,
            'TEXT'  => '',
           ));*/
         $added = false;
         // флаг добавления респондента
         // проверяем, возможно есть авторегистраци
         if (!$context['groupKey']['is_registration_available']) {
             $memberKey = $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key');
             $name = 'Авторегистрация ' . date('H:i d.m.Y') . ' по ключу #' . $context['groupKey']['group_keyID'];
             $memberID = $this->registry->getDbHelper('MembersHelper')->addMember($name, '', '', '', $context['project']['projectID'], $memberKey, $langID, 1, 'new', '', $context['groupKey']['group_keyID']);
             $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
             $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
             $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => $memberID, 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => $context['groupKey']['sessionID'], 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
             $added = true;
             LocalRedirect('/enter/' . $memberKey . '/');
         } else {
             if (isset($_POST['send'])) {
                 $validations = array('name' => 'anything', 'surname' => 'anything', 'email' => 'email', 'position' => 'anything');
                 $required = array('name');
                 $validator = new \Ecoplay\Form\Validator($validations, $required, array());
                 if ($validator->validate($_POST)) {
                     // добавляем участника и респондента
                     $memberKey = $this->registry->getModel('Auth')->generateUid('prep_projects_members', 'private_lk_access_key');
                     $memberID = $this->registry->getDbHelper('MembersHelper')->addMember(trim($_POST["name"]), trim($_POST["surname"]), trim($_POST["position"]), trim($_POST["email"]), $context['project']['projectID'], $memberKey, $langID, 1, 'new', '', $context['groupKey']['group_keyID']);
                     $eventListener = new EventListener($this->registry, $context['project'], $_SERVER["DOCUMENT_ROOT"] . '/');
                     $eventListener->executeEvent('MemberAdded', array('memberID' => $memberID), true);
                     $respondentID = $this->registry->getDbHelper('MembersHelper')->addRespondent(array('project_memberID' => $memberID, 'active' => 1, 'projectID' => $context['project']['projectID'], 'sessionID' => $context['groupKey']['sessionID'], 'stat1_assessID' => 0, 'status' => \Ecoplay\Helper\Db\MembersHelper::RESPONDENT_STATUS_ACTIVE, 'private_access_key' => $this->registry->getModel('Auth')->generateUid('prep_respondents', 'private_access_key'), 'stat1_roleID' => 0, 'last_email' => '0000-00-00 00:00:00', 'langID' => 0, 'last_entrance' => '0000-00-00 00:00:00', 'deny_deletion' => 0, 'addedd_by_assess' => 0, 'need_remind' => 0));
                     $added = true;
                     //$this->component->arResult['access_key'] = $memberKey;
                     //$this->component->IncludeComponentTemplate('testing/success');
                     LocalRedirect('/enter/' . $memberKey . '/');
                 }
             }
         }
         if (!$added) {
             $this->component->IncludeComponentTemplate('testing/template');
         }
     }
     /*$context['APPLICATION']->IncludeComponent("ecoplay:front.footer", '', array(
         'TRANSLATOR'  => $translator,
         'SETTINGS'  => $projectViewSettings,
       ));*/
 }