Fix user import

parent 30fb4c80
......@@ -16,6 +16,11 @@ class TestingSession extends \common\components\ActiveRecordModel
const PAGE_SIZE = 10;
public $csv_file;
public $file;
const TEMP_FOLDER = '/uploads/temp/';
const SCENARIO_UPLOAD = 'upload';
const IS_PRESENT = 0;
const IS_PAST = 1;
......@@ -55,8 +60,9 @@ class TestingSession extends \common\components\ActiveRecordModel
public function rules()
{
return [
[['name', 'start_date', 'end_date'], 'required'],
[['name'], 'string', 'max' => 80],
[['name', 'start_date', 'end_date'], 'required', 'except' => self::SCENARIO_UPLOAD],
[['name'], 'string', 'max' => 80, 'except' => self::SCENARIO_UPLOAD],
[['csv_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xls, xlsx', 'on' => self::SCENARIO_UPLOAD],
];
}
......@@ -152,6 +158,38 @@ class TestingSession extends \common\components\ActiveRecordModel
return $query->all();
}
private function getPath()
{
return Yii::getAlias('@webroot') . self::TEMP_FOLDER;
}
public function upload()
{
if($this->validate())
{
if(!file_exists($this->getPath()))
{
mkdir($this->getPath(), 0777, true);
}
$this->file = $this->getPath() . date('dmYHis-') . uniqid() . '.' . $this->csv_file->extension;
$this->csv_file->saveAs($this->file);
return true;
}
else
{
return false;
}
}
public function deleteFile()
{
if(file_exists($this->file))
{
unlink($this->file);
}
}
public function sendMailByList($users)
{
for ($i = 0; $i < count($users); $i++)
......
......@@ -22,6 +22,13 @@ class TestingTest extends \common\components\ActiveRecordModel
public $csv_file;
public $file;
public static $mix_test_titles = [
'Комбинированный тест',
'комбинированный тест',
'Комбинированный',
'комбинированный'
];
/**
* @inheritdoc
*/
......
......@@ -64,8 +64,6 @@ class TestingUser extends \common\components\ActiveRecordModel
'password' => 'Пароль',
'email' => 'Email',
'manager_id' => 'Ответственный менеджер',
'tki' => 'ТКИ',
'region' => 'Регион',
'create_date' => 'Время создания',
];
}
......@@ -78,11 +76,8 @@ class TestingUser extends \common\components\ActiveRecordModel
[['first_name', 'patronymic', 'last_name'], 'string', 'max' => 50],
[['company_name'], 'string', 'max' => 250],
[['email'], 'string', 'max' => 150],
[['tki', 'city', 'region'], 'string', 'max' => 100],
[['city'], 'string', 'max' => 100],
[['manager_id'], 'string', 'max' => 11],
[['pass_date', 'pass_date_start', 'attempt'], 'safe'],
[['end_date'], 'required', 'on' => 'extend'],
];
}
......
......@@ -18,7 +18,7 @@ class TestingUserGroup extends \common\components\ActiveRecordModel
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'create_date',
'createdAtAttribute' => 'created',
'updatedAtAttribute' => null,
'value' => new Expression('NOW()'),
],
......
<?php
$this->tabs = array(
'просмотреть сессию' => $this->createUrl('/testings/testingPassingAdmin/manage',array('session'=>$model->id)),
);
$this->page_title = 'Импорт пользователей из CSV-файла';
use yii\widgets\ActiveForm;
use yii\helpers\Html;
$this->crumbs = array(
'Список сессий' => array('/testings/testingSessionAdmin/manage'),
$model->name => array('/testings/testingPassingAdmin/manage','session'=>$model->id),
'Импорт пользователей из CSV-файла',
);
?>
<?php if (Yii::app()->user->hasFlash('flash')): ?>
<?php echo $this->msg(Yii::app()->user->getFlash('flash'), 'ok'); ?>
<?php if (\Yii::$app->session->hasFlash('flash')): ?>
<div class="alert alert-success fade in m-b-15">
<?php echo \Yii::$app->session->getFlash('flash'); ?>
<span class="close" data-dismiss="alert">×</span>
</div>
<?php endif ?>
<?php if (isset($log)) : ?>
<?php $this->tabs['загрузить ещё пользователей из CSV-файла'] = $this->createUrl('/testings/testingSessionAdmin/importCSV',array('id'=>$model->id)); ?>
<div><?php echo $log; ?></div>
<div id="log_box"><?php echo $log; ?></div>
<hr>
<script type="text/javascript">
jQuery('#log_box p').each(function(){
var str = $(this).text();
var reg = /Ошибка/gi;
if (str.match(reg)) {
$(this).css('background-color','#ccc').css('color','red');
$(this).css('color','red');
}
});
</script>
......@@ -35,43 +33,23 @@ $this->crumbs = array(
<div>
Для загрузки реестра пользователей на сайт необходимо:
<ol>
<li>Заполнить <a href="/upload/users/Users_example_table.xls">шаблон</a> в формате MS Excel. Поля для назначения тестов имеют формат "да/нет".</li>
<li>Заполнить <a href="/uploads/templates/Users_example_table.xlsx">шаблон</a> в формате MS Excel. Поля для назначения тестов имеют формат "да/нет".</li>
<li>ВАЖНО! Список тестов в сессии необходимо создать заранее! Порядок создания тестов в сессии определяет порядок столбцов в файле!</li>
<li>Сохранить файл как CSV (разделители-запятые).</li>
<li>Сохранить файл как XLS.</li>
<li>Загрузить файл на сайт c помощью кнопки ниже.</li>
</ol>
<span style="color: red;">Важно!</span> Не используйте клавишу ENTER для перевода строки при заполнении шаблона. Если это необходимо, пользуйтесь вместо этого тегом <strong><span style="color: red">&lt;br&gt;</span></strong>.
<div class="message info">Внимание! Для правильной работы модуля CSV-импорта необходимо корректно заполнять шаблон. Любое отхождение от шаблона (пустая строка, добавленный столбец) может нарушить работу данной системы.</div>
<?php $form = $this->beginWidget('CActiveForm', array(
'id'=>'import-csv-form',
'htmlOptions' => array(
'enctype' => 'multipart/form-data'
)
)); ?>
<div class="message info">Внимание! Для правильной работы модуля CSV-импорта необходимо корректно заполнять шаблон. Любое отхождение от шаблона (пустая строка, добавленный столбец) может нарушить работу данной системы.</div>
<dl class="text">
<dd>
<?=$form->label($group, 'name')?>
<?=$form->textField($group, 'name', array(
'class' => 'text'
));?>
<?=$form->error($group, 'name');?>
</dd>
</dl>
<hr>
<dl class="file">
<dd>
<?=$form->label($model, 'csv_file')?>
<?=$form->fileField($model, 'csv_file');?>
<?=$form->error($model, 'csv_file');?>
</dd>
</dl>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<div class="row buttons">
<?=CHtml::submitButton('Загрузить', array(
'class' => 'submit mid'
))?>
</div>
<?= $form->field($group, 'name')->textInput() ?>
<?= $form->field($model, 'csv_file')->fileInput() ?>
<?= Html::submitButton('Загрузить', ['class' => 'btn btn-success']); ?>
<?php $this->endWidget(); ?>
\ No newline at end of file
<?php ActiveForm::end() ?>
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment