Commit 80188cb1 authored by Виталий Мурашко's avatar Виталий Мурашко

Merge branch 'master' of http://git.task-on.com/ktask/task-on.com

Conflicts:
	common/modules/bids/controllers/BidController.php
	common/modules/school/controllers/LessonController.php
parents a24cf796 a545697f
...@@ -182,7 +182,7 @@ class UnisenderAPI { ...@@ -182,7 +182,7 @@ class UnisenderAPI {
public function linkIsVisited($email, $link) { public function linkIsVisited($email, $link) {
if (array_key_exists('result', $this->visitedLinks) && array_key_exists('data', $this->visitedLinks['result'])) { if (array_key_exists('result', $this->visitedLinks) && array_key_exists('data', $this->visitedLinks['result'])) {
foreach($this->visitedLinks['result']['data'] as $transition) { foreach($this->visitedLinks['result']['data'] as $transition) {
if ($transition[0]==$email && $transition[1]==$link) if ($transition[0]==$email && strpos($link, $transition[1])!==false)
return true; return true;
} }
} }
......
...@@ -10,7 +10,8 @@ use yii\web\Response; ...@@ -10,7 +10,8 @@ use yii\web\Response;
use yii\web\UploadedFile; use yii\web\UploadedFile;
use common\modules\bids\models\Bid; use common\modules\bids\models\Bid;
use dosamigos\transliterator\TransliteratorHelper; use common\modules\bids\models\BidFile;
/** /**
* BidAdminController implements the CRUD actions for Bid model. * BidAdminController implements the CRUD actions for Bid model.
*/ */
...@@ -30,29 +31,35 @@ class BidController extends \common\components\BaseController ...@@ -30,29 +31,35 @@ class BidController extends \common\components\BaseController
*/ */
public function actionAdd() public function actionAdd()
{ {
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Bid; $model = new Bid;
$model->scenario = Yii::$app->request->post('scenario'); $model->scenario = Yii::$app->request->post('scenario');
if(Yii::$app->request->isAjax) if(Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))
{ {
$model->load(Yii::$app->request->post()); $transaction = Yii::$app->db->beginTransaction();
$model->file = UploadedFile::getInstance($model, 'file');
Yii::$app->response->format = Response::FORMAT_JSON; try
$model->filename = TransliteratorHelper::process($_POST['file_name'], '', 'en'); {
$model->filename = str_replace("-", "_", $model->filename); if($model->save())
$model->filename = preg_replace('/[^0-9a-z_\.]/i', '', $model->filename);
if($model->validate())
{ {
/*if($model->file) // Yii::$app->user->identity->afterSubscribe(12);
if($model->file)
{ {
$model->upload(); foreach ($model->file as $filename)
$model->file = null; {
}*/ $file = new BidFile;
$file->bid_id = $model->id;
$file->filename = $filename;
$file->save();
}
}
$model->save();
$model->send(); $model->send();
$transaction->commit();
return ['success' => true]; return ['success' => true];
} }
else else
...@@ -60,6 +67,12 @@ class BidController extends \common\components\BaseController ...@@ -60,6 +67,12 @@ class BidController extends \common\components\BaseController
return ActiveForm::validate($model); return ActiveForm::validate($model);
} }
} }
catch (Exception $e)
{
$transaction->rollBack();
throw $e;
}
}
else else
{ {
throw new NotFoundHttpException('The requested page does not exist.'); throw new NotFoundHttpException('The requested page does not exist.');
...@@ -69,19 +82,24 @@ class BidController extends \common\components\BaseController ...@@ -69,19 +82,24 @@ class BidController extends \common\components\BaseController
public function actionUploadFiles() public function actionUploadFiles()
{ {
$model = new Bid(); Yii::$app->response->format = Response::FORMAT_JSON;
if (!empty($_FILES)) {
$model = new BidFile;
$model->file = UploadedFile::getInstanceByName('file');
$tempFile = $_FILES['file']['tmp_name']; if($model->file)
$_FILES['file']['name'] = TransliteratorHelper::process($_FILES['file']['name'], '', 'en'); {
$_FILES['file']['name'] = str_replace("-", "_", $_FILES['file']['name']); if(!file_exists(BidFile::path()))
$_FILES['file']['name'] = preg_replace('/[^0-9a-z_\.]/i', '', $_FILES['file']['name']); {
mkdir(BidFile::path(), 0777, true);
}
$targetPath = $model->getPath(); $model->filename = date('dmYHis-') . uniqid() . '.' . $model->file->extension;
$targetFile = $targetPath. $_FILES['file']['name']; $model->file->saveAs(BidFile::path() . $model->filename);
move_uploaded_file($tempFile,$targetFile); return [
return $_FILES['file']['name']; 'filename' => $model->filename
];
} }
} }
} }
...@@ -30,10 +30,6 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -30,10 +30,6 @@ class Bid extends \common\components\ActiveRecordModel
const TAG_INVOLVEMENT = 'Вовлечение'; const TAG_INVOLVEMENT = 'Вовлечение';
const TAG_TREATMENT = 'Обращение'; const TAG_TREATMENT = 'Обращение';
const FILE_FOLDER = '/uploads/bids/';
public $file;
public static $form_titles = [ public static $form_titles = [
self::FORM_PROJECT => 'Расчитать проект', self::FORM_PROJECT => 'Расчитать проект',
self::FORM_CALLBACK => 'Обратный звонок', self::FORM_CALLBACK => 'Обратный звонок',
...@@ -46,6 +42,8 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -46,6 +42,8 @@ class Bid extends \common\components\ActiveRecordModel
self::FORM_SUBSCRIBE => 'Ошибки', self::FORM_SUBSCRIBE => 'Ошибки',
]; ];
public $file;
/** /**
* @inheritdoc * @inheritdoc
*/ */
...@@ -81,12 +79,13 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -81,12 +79,13 @@ class Bid extends \common\components\ActiveRecordModel
[['email'], 'required', 'on' => self::SCENARIO_SUBSCRIBE], [['email'], 'required', 'on' => self::SCENARIO_SUBSCRIBE],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, xls, xlsx, doc, docx, pdf'],
[['text'], 'string'], [['text'], 'string'],
[['name'], 'string', 'max' => 100], [['name'], 'string', 'max' => 100],
[['phone'], 'string', 'max' => 30], [['phone'], 'string', 'max' => 30],
[['email'], 'string', 'max' => 70], [['email'], 'string', 'max' => 70],
[['filename', 'form'], 'string', 'max' => 50], [['form'], 'string', 'max' => 50],
[['file'], 'safe'],
]; ];
} }
...@@ -100,8 +99,6 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -100,8 +99,6 @@ class Bid extends \common\components\ActiveRecordModel
'name' => 'Имя', 'name' => 'Имя',
'phone' => 'Телефон', 'phone' => 'Телефон',
'email' => 'Email', 'email' => 'Email',
'filename' => 'Прикрепленный файл',
'file' => 'Прикрепленный файл',
'text' => 'Сообщение', 'text' => 'Сообщение',
'form' => 'Форма отправки', 'form' => 'Форма отправки',
'created_at' => 'Дата добавления', 'created_at' => 'Дата добавления',
...@@ -109,25 +106,12 @@ class Bid extends \common\components\ActiveRecordModel ...@@ -109,25 +106,12 @@ class Bid extends \common\components\ActiveRecordModel
]; ];
} }
public function getUrl() /**
{ * @return \yii\db\ActiveQuery
return Yii::$app->params['frontUrl'] . self::FILE_FOLDER . $this->filename; */
} public function getFiles()
public function getPath()
{
return Yii::getAlias('@frontend/web') . self::FILE_FOLDER;
}
public function upload()
{
if(!file_exists($this->getPath()))
{ {
mkdir($this->getPath(), 0777, true); return $this->hasMany(BidFile::className(), ['bid_id' => 'id']);
}
$this->filename = date('dmYHis-') . uniqid() . '.' . $this->file->extension;
$this->file->saveAs($this->getPath() . $this->filename);
} }
public function send() public function send()
......
<?php
namespace common\modules\bids\models;
use Yii;
/**
* This is the model class for table "bids_files".
*
* @property integer $id
* @property integer $bid_id
* @property string $filename
*
* @property Bids $bid
*/
class BidFile extends \common\components\ActiveRecordModel
{
const FILE_FOLDER = '/uploads/bids/';
public $file;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'bids_files';
}
/**
* @inheritdoc
*/
public function name()
{
return 'Файл заявки';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['bid_id'], 'required'],
[['bid_id'], 'integer'],
[['filename'], 'string', 'max' => 100],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif, xls, xlsx, doc, docx, pdf', 'maxFiles' => 4],
[['bid_id'], 'exist', 'skipOnError' => true, 'targetClass' => Bid::className(), 'targetAttribute' => ['bid_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'file' => 'Прикрепленный файл',
'bid_id' => 'Заявка',
'filename' => 'Файл',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBid()
{
return $this->hasOne(Bid::className(), ['id' => 'bid_id']);
}
public function getUrl()
{
return Yii::$app->params['frontUrl'] . self::FILE_FOLDER . $this->filename;
}
public static function path()
{
return Yii::getAlias('@frontend/web') . self::FILE_FOLDER;
}
}
...@@ -19,7 +19,7 @@ class SearchBid extends Bid ...@@ -19,7 +19,7 @@ class SearchBid extends Bid
{ {
return [ return [
[['id'], 'integer'], [['id'], 'integer'],
[['name', 'phone', 'email', 'filename', 'text', 'created_at', 'form'], 'safe'], [['name', 'phone', 'email', 'text', 'created_at', 'form'], 'safe'],
]; ];
} }
...@@ -67,7 +67,6 @@ class SearchBid extends Bid ...@@ -67,7 +67,6 @@ class SearchBid extends Bid
$query->andFilterWhere(['like', 'name', $this->name]) $query->andFilterWhere(['like', 'name', $this->name])
->andFilterWhere(['like', 'phone', $this->phone]) ->andFilterWhere(['like', 'phone', $this->phone])
->andFilterWhere(['like', 'email', $this->email]) ->andFilterWhere(['like', 'email', $this->email])
->andFilterWhere(['like', 'filename', $this->filename])
->andFilterWhere(['like', 'text', $this->text]); ->andFilterWhere(['like', 'text', $this->text]);
return $dataProvider; return $dataProvider;
......
...@@ -26,11 +26,19 @@ $this->params['breadcrumbs'][] = $this->title; ...@@ -26,11 +26,19 @@ $this->params['breadcrumbs'][] = $this->title;
'phone', 'phone',
'email:email', 'email:email',
[ [
'attribute' => 'filename', 'header' => 'Файлы',
'format' => 'html', 'format' => 'html',
'value' => function($model) 'value' => function($model)
{ {
return ($model->filename?Html::a($model->filename, $model->getUrl()):null); $files = [];
if($model->files)
{
foreach ($model->files as $file)
{
$files[] = Html::a($file->filename, $file->getUrl());
}
}
return implode('<br>', $files);
} }
], ],
'text:ntext', 'text:ntext',
......
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use common\modules\bids\models\Bid; use common\modules\bids\models\BidFile;
?> ?>
Имя: <?=$model->name?><br> Имя: <?=$model->name?><br>
...@@ -12,7 +12,15 @@ Email: <?=$model->email?><br> ...@@ -12,7 +12,15 @@ Email: <?=$model->email?><br>
Сообщение: <?=$model->text?><br> Сообщение: <?=$model->text?><br>
Файл: <?=($model->filename?Html::a($model->filename,\Yii::$app->params['frontUrl'].Bid::FILE_FOLDER.$model->filename):'')?><br> <?php if($model->files) : ?>
<hr>
Файлы:
<?php foreach ($model->files as $file)
{
echo Html::a($file->filename,\Yii::$app->params['frontUrl'].BidFile::FILE_FOLDER.$file->filename) . '<br>';
} ?>
<hr>
<?php endif; ?>
Дата добавления заявки: <?=date('d.m.Y H:i:s', $model->created_at)?><br> Дата добавления заявки: <?=date('d.m.Y H:i:s', $model->created_at)?><br>
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
namespace common\modules\blog\models; namespace common\modules\blog\models;
use Yii; use Yii;
use yii\helpers\Url;
use common\modules\languages\models\Languages; use common\modules\languages\models\Languages;
use common\modules\blog\models\PostLang; use common\modules\blog\models\PostLang;
...@@ -191,7 +192,12 @@ class Post extends \common\components\ActiveRecordModel ...@@ -191,7 +192,12 @@ class Post extends \common\components\ActiveRecordModel
*/ */
public function getViews() public function getViews()
{ {
return SessionUrl::find()->where(['url' => '/blog/'.$this->url]); return SessionUrl::find()->where(['url' => $this->getFullUrl()]);
}
public function getFullUrl()
{
return Url::to(['/blog/' . $this->url]);
} }
public function getThumbnailUrl() public function getThumbnailUrl()
......
...@@ -82,4 +82,21 @@ class PostLang extends \common\components\ActiveRecordModel ...@@ -82,4 +82,21 @@ class PostLang extends \common\components\ActiveRecordModel
{ {
return $this->hasOne(Languages::className(), ['id' => 'lang_id']); return $this->hasOne(Languages::className(), ['id' => 'lang_id']);
} }
public function cutText($chars)
{
$text = strip_tags($this->text, '<a>');
if(strlen($text) > $chars)
{
$text = $text . " ";
$text = substr($text, 0, $chars);
$text = substr($text, 0, strrpos($text, ' '));
$text = $text . '...';
return '<p>'.$text.'</p><p><a href="'.$this->post->getFullUrl().'">Читать...</a></p>';
}
return $this->text;
}
} }
...@@ -18,15 +18,6 @@ use yii\helpers\Url; ...@@ -18,15 +18,6 @@ use yii\helpers\Url;
<?=$model->getViews()->count()?> <?=$model->getViews()->count()?>
<div class="blog_toltip_left">Количество просмотров</div> <div class="blog_toltip_left">Количество просмотров</div>
</span> </span>
<!-- <ul class="article_short_social">
<li>
<a href="#"><img src="/images/icon/sh_social_vk.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_fb.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_tw.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_gp.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_t.png" height="30" width="30" alt=""></a>
</li>
</ul> -->
</div> </div>
<div class="article_short_tags"> <div class="article_short_tags">
...@@ -43,7 +34,7 @@ use yii\helpers\Url; ...@@ -43,7 +34,7 @@ use yii\helpers\Url;
echo Html::img($model->preview); echo Html::img($model->preview);
endif; ?> endif; ?>
<?=$model->lang->text?> <?=$model->lang->cutText(650)?>
</div> </div>
</article> </article>
......
...@@ -27,6 +27,10 @@ use common\modules\bids\models\Bid; ...@@ -27,6 +27,10 @@ use common\modules\bids\models\Bid;
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Заявка на статью отправлена. Мы обязательно ее рассмотрим.</div>
<div class="content">
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
<div class="blog_form_left form_resp"> <div class="blog_form_left form_resp">
...@@ -69,6 +73,8 @@ use common\modules\bids\models\Bid; ...@@ -69,6 +73,8 @@ use common\modules\bids\models\Bid;
<?php echo Html::submitButton('Предложить статью', ['class' => 'save-button btn-default button-lg']); ?> <?php echo Html::submitButton('Предложить статью', ['class' => 'save-button btn-default button-lg']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
...@@ -95,6 +101,10 @@ use common\modules\bids\models\Bid; ...@@ -95,6 +101,10 @@ use common\modules\bids\models\Bid;
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Заявка на статью по предложенной теме отправлена. Мы обязательно ее рассмотрим.</div>
<div class="content">
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
<div class="blog_form_left50 form_resp"> <div class="blog_form_left50 form_resp">
...@@ -132,6 +142,8 @@ use common\modules\bids\models\Bid; ...@@ -132,6 +142,8 @@ use common\modules\bids\models\Bid;
<?php echo Html::submitButton('Предложить тему', ['class' => 'save-button btn-default button-lg']); ?> <?php echo Html::submitButton('Предложить тему', ['class' => 'save-button btn-default button-lg']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
......
<ul class="article_short_social">
<li>
<a href="#" onclick="window.open('http://vkontakte.ru/share.php?url=<?=$link?>&title=<?=$title?>', 'Soc', 'screenX=100,screenY=100,height=500,width=500,location=no,toolbar=no,directories=no,menubar=no,status=no'); return false;"><img src="/images/icon/sh_social_vk.png" height="30" width="30" alt=""></a>
<a href="#" onclick="window.open('http://www.facebook.com/share.php?u=<?=$title?>', 'Soc', 'screenX=100,screenY=100,height=500,width=500,location=no,toolbar=no,directories=no,menubar=no,status=no'); return false;"><img src="/images/icon/sh_social_fb.png" height="30" width="30" alt=""></a>
<a href="#" onclick="window.open('http://twitter.com/timeline/home?status=<?=$title?>%20<?=$link?>', 'Soc', 'screenX=100,screenY=100,height=500,width=500,location=no,toolbar=no,directories=no,menubar=no,status=no'); return false;"><img src="/images/icon/sh_social_tw.png" height="30" width="30" alt=""></a>
<a href="#" onclick="window.open('https://plus.google.com/share?url=<?=$link?>', 'Soc', 'screenX=100,screenY=100,height=500,width=500,location=no,toolbar=no,directories=no,menubar=no,status=no'); return false;"><img src="/images/icon/sh_social_gp.png" height="30" width="30" alt=""></a>
<!-- <a href="#"><img src="/images/icon/sh_social_t.png" height="30" width="30" alt=""></a> -->
</li>
</ul>
\ No newline at end of file
...@@ -25,6 +25,10 @@ use common\modules\bids\models\Bid; ...@@ -25,6 +25,10 @@ use common\modules\bids\models\Bid;
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Теперь вы подписаны на обновления блога.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -38,6 +42,8 @@ use common\modules\bids\models\Bid; ...@@ -38,6 +42,8 @@ use common\modules\bids\models\Bid;
<?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?> <?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
\ No newline at end of file
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\Url;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $model common\modules\blog\models\Post */ /* @var $model common\modules\blog\models\Post */
...@@ -21,15 +22,9 @@ use yii\helpers\Html; ...@@ -21,15 +22,9 @@ use yii\helpers\Html;
<?=$model->getViews()->count()?> <?=$model->getViews()->count()?>
<div class="blog_toltip_left">Количество просмотров</div> <div class="blog_toltip_left">Количество просмотров</div>
</span> </span>
<!-- <ul class="article_short_social">
<li> <?=$this->render('_social', ['link' => Url::to(['/blog/'.$model->url], true), 'title' => $model->lang->title])?>
<a href="#"><img src="/images/icon/sh_social_vk.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_fb.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_tw.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_gp.png" height="30" width="30" alt=""></a>
<a href="#"><img src="/images/icon/sh_social_t.png" height="30" width="30" alt=""></a>
</li>
</ul> -->
</div> </div>
<div class="article_short_tags"> <div class="article_short_tags">
......
...@@ -2,10 +2,13 @@ ...@@ -2,10 +2,13 @@
namespace common\modules\school\controllers; namespace common\modules\school\controllers;
use Yii;
use common\components\BaseController; use common\components\BaseController;
use common\modules\school\models\Lessons; use common\modules\school\models\Lessons;
use common\modules\school\models\LessonImage; use common\modules\school\models\LessonImage;
use common\modules\testings\models\Passing;
class LessonController extends BaseController class LessonController extends BaseController
{ {
...@@ -20,11 +23,20 @@ class LessonController extends BaseController ...@@ -20,11 +23,20 @@ class LessonController extends BaseController
public function actionView($id) public function actionView($id)
{ {
$model = Lessons::findOne($id); $model = Lessons::findOne($id);
\Yii::$app->view->registerMetaTag([ \Yii::$app->view->registerMetaTag([
'property' => 'og:title', 'property' => 'og:title',
'content' => $model->title 'content' => $model->title
]); ]);
return $this->render('view', ['model' => $model]);
// Ищим прохождение теста
$passing = null;
if($model->test)
{
$passing = Passing::find()->where(['test_id' => $model->test_id, 'user_id' => Yii::$app->user->id])->one();
}
return $this->render('view', compact('model', 'passing'));
} }
......
...@@ -4,6 +4,7 @@ use yii\helpers\Url; ...@@ -4,6 +4,7 @@ use yii\helpers\Url;
use common\modules\users\widgets\UserBoxWidget; use common\modules\users\widgets\UserBoxWidget;
use common\modules\school\assets\WidgetAssetBundle; use common\modules\school\assets\WidgetAssetBundle;
use common\modules\testings\models\Passing;
WidgetAssetBundle::register($this); WidgetAssetBundle::register($this);
?> ?>
...@@ -75,7 +76,11 @@ WidgetAssetBundle::register($this); ...@@ -75,7 +76,11 @@ WidgetAssetBundle::register($this);
</section> </section>
<section class="vc-cont"> <section class="vc-cont">
<div class="container"> <div class="container">
<?php if($model->test) : ?> <?php if($model->test) : ?>
<?php if(!$passing) : ?>
<div class="row"> <div class="row">
<div class="col-md-4 col-xs-5 col-sm-12"> <div class="col-md-4 col-xs-5 col-sm-12">
<a href="<?=Url::to(['/testing/info/' . $model->test_id])?>" class="vc_bt_quit_less">Завершить урок</a> <a href="<?=Url::to(['/testing/info/' . $model->test_id])?>" class="vc_bt_quit_less">Завершить урок</a>
...@@ -84,14 +89,55 @@ WidgetAssetBundle::register($this); ...@@ -84,14 +89,55 @@ WidgetAssetBundle::register($this);
<div class="vc_quit_txt">Чтобы завершить урок, выполните задание.</div> <div class="vc_quit_txt">Чтобы завершить урок, выполните задание.</div>
</div> </div>
</div> </div>
<?php endif; ?>
<!-- <div class="row"> <?php else : ?>
<?php if($passing->status == Passing::STARTED && strtotime($passing->start_date) + ($passing->test->minutes * 60) > time() && $passing->attempt < $passing->test->attempt) : ?>
<div class="row">
<div class="col-md-4 col-xs-5 col-sm-12">
<a href="<?=Url::to(['/testing/pass/' . $passing->id])?>" class="vc_bt_quit_less">Продолжить</a>
</div>
<div class="col-md-8 col-xs-7 col-sm-12">
<div class="vc_quit_txt">Пожалуйста, завершите начатое тестирование.</div>
</div>
</div>
<?php elseif($passing->passed == Passing::PASSED) : ?>
<div class="row">
<div class="col-md-4 col-xs-5 col-sm-12">
<a href="<?=Url::to(['/testing/statistic/' . $passing->id])?>" class="vc_bt_quit_less">Результаты</a>
</div>
<div class="col-md-8 col-xs-7 col-sm-12">
<div class="vc_quit_txt">Вы можете посмотреть результаты теста.</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<div class="vc_green_inf"> <div class="vc_green_inf">
<span>Тестирование успешно пройдено. Вы набрали 99 999 балов.<br> Оставляйте комментарии, что бы увеличить Ваш рейтинг.</span> <span>Тестирование успешно пройдено. Вы набрали <?=$passing->points?> баллов.<br> Оставляйте комментарии, что бы увеличить Ваш рейтинг.</span>
</div>
</div> </div>
</div> </div>
</div> -->
<?php else : ?>
<div class="row">
<div class="col-md-4 col-xs-5 col-sm-12">
<a href="<?=Url::to(['/testing/info/' . $model->test_id])?>" class="vc_bt_quit_less">Пересдать</a>
</div>
<div class="col-md-8 col-xs-7 col-sm-12">
<div class="vc_quit_txt">Может быть повезет на этот раз?</div>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<?php endif; ?>
<?php if($model->text):?> <?php if($model->text):?>
<div class="row"> <div class="row">
......
<?php
namespace common\modules\testings\controllers;
use Yii;
use common\components\AdminController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\modules\testings\models\Mistake;
use common\modules\testings\models\Passing;
class MistakeAdminController extends AdminController
{
public $errorSummaryCssClass = 'error-summary';
public $encodeErrorSummary = true;
public static function actionsTitles()
{
return array(
'View' => 'Просмотр ошибки',
'Create' => 'Создание ошибки',
'Update' => 'Редактирование ошибки',
);
}
public function actionView($passing)
{
return $this->render('view', [
'model' => Mistake::find()->where(['passing_id' => $passing])->one(),
]);
}
public function actionCreate($passing)
{
$model = new Mistake;
Yii::$app->controller->page_title = 'Добавить ошибку';
Yii::$app->controller->breadcrumbs = [
['Список прохождений' => '/testings/passing-admin/manage', 'session' => $model->passing->test->session_id],
'Добавить ошибку'
];
$model->load(Yii::$app->request->post());
$model->passing_id = $passing;
if (Yii::$app->request->isPost && $model->save())
{
if ($model->retest)
{
$pass = new Passing;
$oldpass = Passing::findOne($model->passing_id);
$pass->attributes = $oldpass->attributes;
$pass->is_passed = null;
$pass->pass_date = null;
$pass->attempt = 0;
$pass->pass_date_start = '';
$pass->save();
}
return $this->redirect(['/testings/passing-admin/manage', 'session' => $model->passing->test->session_id]);
}
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/MistakeForm', $model);
return $this->render('create', [
'model' => $model,
'form' => $form->out
]);
}
}
public function actionUpdate($passing)
{
Yii::$app->controller->page_title = 'Редактировать ошибку';
Yii::$app->controller->breadcrumbs = [
['Список прохождений' => '/testings/passing-admin/manage', 'session' => $model->passing->test->session_id],
'Редактировать ошибку'
];
$model = Mistake::find()->where(['passing_id' => $passing])->one();
$model->load(Yii::$app->request->post());
$model->passing_id = $passing;
if (Yii::$app->request->isPost && $model->save())
{
if ($model->retest)
{
$pass = new Passing;
$pass->attributes = $model->passing->attributes;
$pass->is_passed = null;
$pass->pass_date = null;
$pass->attempt = 0;
$pass->pass_date_start = '';
$pass->save();
}
return $this->redirect(['/testings/passing-admin/manage', 'session' => $model->passing->test->session_id]);
}
else
{
$form = new \common\components\BaseForm('/common/modules/testings/forms/MistakeForm', $model);
return $this->render('update', [
'model' => $model,
'form' => $form->out
]);
}
}
/**
* Finds the Faq model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Faq the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Answer::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
...@@ -35,26 +35,8 @@ class SessionAdminController extends AdminController ...@@ -35,26 +35,8 @@ class SessionAdminController extends AdminController
{ {
$model = $this->findModel($id); $model = $this->findModel($id);
$test_ids = array_keys(\yii\helpers\ArrayHelper::map($model->tests, 'id', 'name'));
$query = Passing::find()
->joinWith('user')
->where([
'test_id' => $test_ids,
]);
$query->andWhere(['<>', 'end_date', ""]);
$users = [];
foreach ($query->all() as $passing)
{
$users[$passing->end_date] = $passing->user;
}
return $this->render('view', [ return $this->render('view', [
'model' => $model, 'model' => $model
'users' => $users
]); ]);
} }
......
<?php
namespace common\modules\testings\models;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
class Mistake extends \common\components\ActiveRecordModel
{
const PAGE_SIZE = 10;
const NOT_AGREED = 0;
const AGREED = 1;
public $company;
public $managerField;
public $mistakeField;
public $retest = 0;
public static $state_list = [
self::NOT_AGREED => 'Не согласовано',
self::AGREED => 'Согласовано',
];
public static function tableName()
{
return 'testings_mistakes';
}
public function name()
{
return 'Сообщения об ошибках';
}
public function attributeLabels()
{
return [
'passing_id' => 'Прохождение',
'description' => 'Описание ошибки',
'is_expert_agreed' => 'Согласовано ли с экспертом',
'create_date' => 'Время создания',
];
}
/**
* @inheritdoc
*/
public function behaviors()
{
// $behaviors['FileManager'] = array(
// 'class' => 'application.components.activeRecordBehaviors.FileManagerBehavior'
// );
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'create_date',
'updatedAtAttribute' => 'create_date',
'value' => new Expression('NOW()'),
],
];
}
public function rules()
{
return [
[['passing_id', 'description', 'is_expert_agreed'], 'required'],
[['passing_id', 'is_expert_agreed'], 'integer'],
[['description'], 'string', 'max' => 3000],
[['retest'], 'safe']
];
}
public function getPassing()
{
return $this->hasOne(Passing::className(), ['id' => 'passing_id']);
}
// public function getFiles()
// {
// return $this->hasMany(FileManager::className(), ['object_id' => 'id'])
// ->andWhere([
// 'files.model_id' => get_class($this),
// 'files.tag' => 'files'
// ])
// ->orderBy(['files.order DESC']);
// }
}
\ No newline at end of file
...@@ -12,24 +12,30 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -12,24 +12,30 @@ class Passing extends \common\components\ActiveRecordModel
{ {
const PAGE_SIZE = 10; const PAGE_SIZE = 10;
const STARTED = 0; const NOT_STARTED = 0;
const STARTED = 11;
const ENDED = 1;
const FAILED = 0;
const PASSED = 1; const PASSED = 1;
const MISTAKE = 8;
const FAILED = 9;
const PASSING_PERCENT_RIGHT_CENTER = 50; const PASSING_PERCENT_RIGHT_CENTER = 50;
const PASSING_PERCENT_RIGHT_ALMOST = 75; const PASSING_PERCENT_RIGHT_ALMOST = 75;
const PASSING_PERCENT_RIGHT_ALL = 100; const PASSING_PERCENT_RIGHT_ALL = 100;
public static $state_list = [ public static $state_list = [
self::STARTED => 'Начал тестирование', self::NOT_STARTED => 'Не сдавал',
self::STARTED => 'Тестирование',
self::ENDED => 'Завершено',
];
public static $passed_list = [
self::FAILED => 'Не сдал', self::FAILED => 'Не сдал',
self::PASSED => 'Сдал', self::PASSED => 'Сдал',
self::MISTAKE => 'Ошибка',
]; ];
public static $answer_list = [ public static $answer_list = [
self::STARTED => 'Не верно', self::FAILED => 'Не верно',
self::PASSED => 'Верно', self::PASSED => 'Верно',
]; ];
...@@ -57,8 +63,8 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -57,8 +63,8 @@ class Passing extends \common\components\ActiveRecordModel
{ {
return [ return [
[['user_id', 'test_id'], 'required'], [['user_id', 'test_id'], 'required'],
[['user_id', 'test_id', 'is_passed'], 'integer'], [['user_id', 'test_id', 'status', 'passed', 'percent', 'points'], 'integer'],
[['pass_date', 'pass_date_start', 'attempt'], 'safe'], [['start_date', 'attempt'], 'safe'],
[['end_date'], 'required', 'on' => 'extend'], [['end_date'], 'required', 'on' => 'extend'],
]; ];
} }
...@@ -66,14 +72,14 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -66,14 +72,14 @@ class Passing extends \common\components\ActiveRecordModel
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'is_passed' => 'Состояние',
'test_id' => 'Tест', 'test_id' => 'Tест',
'user_id' => 'ФИО', 'user_id' => 'ФИО',
'create_date' => 'Дата создания', 'passed' => 'Сдал/Не сдал',
'pass_date' => 'Дата прохождения теста', 'status' => 'Статус',
'start_date' => 'Дата создания',
'end_date' => 'Дата прохождения теста',
'session_id' => 'Сессия', 'session_id' => 'Сессия',
'filter_user_email' => 'Email', 'filter_user_email' => 'Email',
'filter_user_company_name' => 'Наименование компании',
'filter_user_last_name' => 'ФИО', 'filter_user_last_name' => 'ФИО',
]; ];
} }
...@@ -113,7 +119,7 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -113,7 +119,7 @@ class Passing extends \common\components\ActiveRecordModel
return $count; return $count;
} }
public function getPercent() public function getPercentRight()
{ {
$all = 0; $all = 0;
$right = 0; $right = 0;
...@@ -156,17 +162,18 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -156,17 +162,18 @@ class Passing extends \common\components\ActiveRecordModel
public function getTime() public function getTime()
{ {
if($this->pass_date_start && $this->pass_date) if($this->start_date && $this->end_date)
{ {
return (strtotime($this->pass_date) - strtotime($this->pass_date_start)); return (strtotime($this->end_date) - strtotime($this->start_date));
} }
else else
{ {
$timeSummary = 0; $time = 0;
foreach ($this->questions as $q) { foreach ($this->questions as $q)
$timeSummary += $q->answer_time; {
$time += $q->answer_time;
} }
return $timeSummary; return $time;
} }
} }
...@@ -175,4 +182,32 @@ class Passing extends \common\components\ActiveRecordModel ...@@ -175,4 +182,32 @@ class Passing extends \common\components\ActiveRecordModel
$cases = array (2, 0, 1, 1, 1, 2); $cases = array (2, 0, 1, 1, 1, 2);
return $number." ".$titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ]; return $number." ".$titles[ ($number%100 > 4 && $number %100 < 20) ? 2 : $cases[min($number%10, 5)] ];
} }
public function recountPassResult()
{
if ($this->percent >= $this->test->pass_percent)
{
$this->passed = self::PASSED;
}
else
{
$this->passed = self::FAILED;
}
return true;
}
public function addPoints()
{
if($this->passed == Passing::PASSED)
{
$this->points = $this->test->passed_scores;
}
else
{
$this->points = $this->test->notpassed_scores;
}
return true;
}
} }
...@@ -169,7 +169,7 @@ class Question extends \common\components\ActiveRecordModel ...@@ -169,7 +169,7 @@ class Question extends \common\components\ActiveRecordModel
break; break;
case self::USER_ANSWER: case self::USER_ANSWER:
$models = $query->one(); $model = $query->one();
if ($model) if ($model)
{ {
$answer = trim(preg_replace('/\s+/', ' ', $model->text)); $answer = trim(preg_replace('/\s+/', ' ', $model->text));
......
...@@ -46,17 +46,15 @@ class QuestionPassing extends \common\components\ActiveRecordModel ...@@ -46,17 +46,15 @@ class QuestionPassing extends \common\components\ActiveRecordModel
{ {
return [ return [
[['passing_id', 'question_id'], 'required'], [['passing_id', 'question_id'], 'required'],
[['passing_id', 'answer_time'], 'integer'], [['passing_id', 'question_id', 'answer_time'], 'integer'],
[['question_id'], 'string', 'max' => 11],
[['user_answer'], 'string', 'max' => 3000], [['user_answer'], 'string', 'max' => 3000],
// array('id, passing_id, question_id, user_answer, answer_time', 'safe', 'on' => 'search'),
]; ];
} }
public function attributeLabels() public function attributeLabels()
{ {
return [ return [
'question_id' => 'Наименование вопроса', 'question_id' => 'Вопрос',
'user_answer' => 'Ответ пользователя', 'user_answer' => 'Ответ пользователя',
'answer_time' => 'Время прохождения, секунд', 'answer_time' => 'Время прохождения, секунд',
'create_date' => 'Дата создания', 'create_date' => 'Дата создания',
...@@ -72,7 +70,7 @@ class QuestionPassing extends \common\components\ActiveRecordModel ...@@ -72,7 +70,7 @@ class QuestionPassing extends \common\components\ActiveRecordModel
public function getPassing() public function getPassing()
{ {
return $this->hasOne(Passing::className(), ['passing_id' => 'id']); return $this->hasOne(Passing::className(), ['id' => 'passing_id']);
} }
public function search($passing = null) public function search($passing = null)
......
...@@ -15,7 +15,6 @@ use common\modules\testings\models\Mistake; ...@@ -15,7 +15,6 @@ use common\modules\testings\models\Mistake;
class SearchPassing extends Passing class SearchPassing extends Passing
{ {
public $filter_user_email; public $filter_user_email;
public $filter_user_company_name;
public $filter_user_last_name; public $filter_user_last_name;
/** /**
...@@ -24,8 +23,8 @@ class SearchPassing extends Passing ...@@ -24,8 +23,8 @@ class SearchPassing extends Passing
public function rules() public function rules()
{ {
return [ return [
[['id', 'user_id', 'test_id', 'is_passed'], 'integer'], [['id', 'user_id', 'test_id', 'status', 'passed'], 'integer'],
[['id', 'user_id', 'test_id', 'is_passed', 'pass_date', 'filter_user_email', 'filter_user_company_name', 'filter_user_last_name'], 'safe'], [['id', 'user_id', 'test_id', 'status', 'passed', 'end_date', 'filter_user_email', 'filter_user_last_name'], 'safe'],
]; ];
} }
...@@ -53,7 +52,7 @@ class SearchPassing extends Passing ...@@ -53,7 +52,7 @@ class SearchPassing extends Passing
'query' => $query, 'query' => $query,
'pagination' => ['pageSize' => self::PAGE_SIZE], 'pagination' => ['pageSize' => self::PAGE_SIZE],
'sort' => [ 'sort' => [
'defaultOrder'=>'create_date DESC', 'defaultOrder'=>'start_date DESC',
], ],
]); ]);
...@@ -79,8 +78,10 @@ class SearchPassing extends Passing ...@@ -79,8 +78,10 @@ class SearchPassing extends Passing
$query->andFilterWhere([ $query->andFilterWhere([
'id' => $this->id, 'id' => $this->id,
'user_id' => $this->user_id, 'user_id' => $this->user_id,
'status' => $this->status,
'passed' => $this->passed,
'test_id' => $this->test_id, 'test_id' => $this->test_id,
'create_date' => $this->create_date, 'start_date' => $this->start_date,
Test::tableName() . '.session_id' => Yii::$app->request->get('session'), Test::tableName() . '.session_id' => Yii::$app->request->get('session'),
]); ]);
...@@ -90,12 +91,6 @@ class SearchPassing extends Passing ...@@ -90,12 +91,6 @@ class SearchPassing extends Passing
$query->andFilterWhere(['like', User::tableName() . '.email', $this->filter_user_email]); $query->andFilterWhere(['like', User::tableName() . '.email', $this->filter_user_email]);
} }
if($this->filter_user_company_name)
{
$with['user'] = true;
$query->andFilterWhere(['like', User::tableName() . '.company_name', $this->filter_user_company_name]);
}
if($this->filter_user_last_name) if($this->filter_user_last_name)
{ {
$with['user'] = true; $with['user'] = true;
...@@ -104,35 +99,35 @@ class SearchPassing extends Passing ...@@ -104,35 +99,35 @@ class SearchPassing extends Passing
// $tpassing = Yii::app()->request->getQuery('Passing'); // $tpassing = Yii::app()->request->getQuery('Passing');
// $pass_date = 'CONCAT( RIGHT( LEFT( pass_date, 10 ) , 4 ) , "-", TRIM( // $end_date = 'CONCAT( RIGHT( LEFT( end_date, 10 ) , 4 ) , "-", TRIM(
// TRAILING CONCAT( ".", SUBSTRING_INDEX( LEFT( pass_date, 10 ) , ".", -1 ) ) // TRAILING CONCAT( ".", SUBSTRING_INDEX( LEFT( end_date, 10 ) , ".", -1 ) )
// FROM TRIM( // FROM TRIM(
// LEADING CONCAT( SUBSTRING_INDEX( LEFT( pass_date, 10 ) , ".", 1 ) , "." ) // LEADING CONCAT( SUBSTRING_INDEX( LEFT( end_date, 10 ) , ".", 1 ) , "." )
// FROM LEFT( pass_date, 10 ) ) ) , "-", LEFT( pass_date, 2 ) )'; // FROM LEFT( end_date, 10 ) ) ) , "-", LEFT( end_date, 2 ) )';
// if (($tpassing['pass_date']) && (Yii::app()->request->getQuery('date_to'))) { // if (($tpassing['end_date']) && (Yii::app()->request->getQuery('date_to'))) {
// $criteria->addCondition($pass_date.' BETWEEN "'.$tpassing['pass_date'].'" AND "'.Yii::app()->request->getQuery('date_to').'"'); // $criteria->addCondition($end_date.' BETWEEN "'.$tpassing['end_date'].'" AND "'.Yii::app()->request->getQuery('date_to').'"');
// } // }
// elseif(Yii::app()->request->getQuery('date_to')) { // elseif(Yii::app()->request->getQuery('date_to')) {
// $criteria->addCondition($pass_date.' < "'.Yii::app()->request->getQuery('date_to').'"'); // $criteria->addCondition($end_date.' < "'.Yii::app()->request->getQuery('date_to').'"');
// } // }
// elseif($tpassing['pass_date']) { // elseif($tpassing['end_date']) {
// $criteria->addCondition($pass_date.' > "'.Yii::app()->request->getQuery('pass_date').'"'); // $criteria->addCondition($end_date.' > "'.Yii::app()->request->getQuery('end_date').'"');
// } // }
// switch ($this->is_passed) // switch ($this->status)
// { // {
// case Passing::AUTH: // case Passing::AUTH:
// $with['user'] = true; // $with['user'] = true;
// $query->andFilterWhere(['>', 'ser.create_date', '2014-06-05 00:00:00']); // $query->andFilterWhere(['>', 'ser.start_date', '2014-06-05 00:00:00']);
// $query->andFilterWhere([User::tableName() . '.is_auth' => 0]); // $query->andFilterWhere([User::tableName() . '.is_auth' => 0]);
// break; // break;
// case Passing::STARTED: // case Passing::STARTED:
// $query->andFilterWhere([ // $query->andFilterWhere([
// 'is_passed' => 0, // 'status' => 0,
// 'pass_date' => null, // 'end_date' => null,
// Mistake::tableName() . '.passing_id' => null // Mistake::tableName() . '.passing_id' => null
// ]); // ]);
// break; // break;
...@@ -145,7 +140,7 @@ class SearchPassing extends Passing ...@@ -145,7 +140,7 @@ class SearchPassing extends Passing
// case Passing::PASSED: // case Passing::PASSED:
// $with['mistake'] = true; // $with['mistake'] = true;
// $query->andFilterWhere([ // $query->andFilterWhere([
// 'is_passed' => 1, // 'status' => 1,
// Mistake::tableName() . '.passing_id' => null // Mistake::tableName() . '.passing_id' => null
// ]); // ]);
// break; // break;
...@@ -153,16 +148,16 @@ class SearchPassing extends Passing ...@@ -153,16 +148,16 @@ class SearchPassing extends Passing
// case Passing::FAILED: // case Passing::FAILED:
// $with['mistake'] = true; // $with['mistake'] = true;
// $query->andFilterWhere([ // $query->andFilterWhere([
// 'is_passed' => 0, // 'status' => 0,
// Mistake::tableName() . '.passing_id' => null // Mistake::tableName() . '.passing_id' => null
// ]); // ]);
// $query->andFilterWhere(['not', 'pass_date', null]); // $query->andFilterWhere(['not', 'end_date', null]);
// break; // break;
// case Passing::NOT_STARTED: // case Passing::NOT_STARTED:
// $with['mistake'] = true; // $with['mistake'] = true;
// $query->andFilterWhere([ // $query->andFilterWhere([
// 'is_passed' => null, // 'status' => null,
// Mistake::tableName() . '.passing_id' => null // Mistake::tableName() . '.passing_id' => null
// ]); // ]);
// break; // break;
...@@ -183,7 +178,7 @@ class SearchPassing extends Passing ...@@ -183,7 +178,7 @@ class SearchPassing extends Passing
{ {
$query = $this->query(Yii::$app->request->queryParams); $query = $this->query(Yii::$app->request->queryParams);
$query->andWhere(['is_passed' => 1]); $query->andWhere(['status' => 1]);
return $query->count(); return $query->count();
} }
...@@ -192,7 +187,7 @@ class SearchPassing extends Passing ...@@ -192,7 +187,7 @@ class SearchPassing extends Passing
{ {
$query = $this->query(Yii::$app->request->queryParams); $query = $this->query(Yii::$app->request->queryParams);
$query->andWhere(['is_passed' => 0]); $query->andWhere(['status' => 0]);
return $query->count(); return $query->count();
} }
...@@ -201,7 +196,7 @@ class SearchPassing extends Passing ...@@ -201,7 +196,7 @@ class SearchPassing extends Passing
{ {
$query = $this->query(Yii::$app->request->queryParams); $query = $this->query(Yii::$app->request->queryParams);
$query->andWhere(['is_passed' => 2]); $query->andWhere(['status' => 2]);
return $query->count(); return $query->count();
} }
...@@ -210,7 +205,7 @@ class SearchPassing extends Passing ...@@ -210,7 +205,7 @@ class SearchPassing extends Passing
{ {
$query = $this->query(Yii::$app->request->queryParams); $query = $this->query(Yii::$app->request->queryParams);
$query->andWhere(['is_passed' => null]); $query->andWhere(['status' => null]);
return $query->count(); return $query->count();
} }
......
...@@ -106,7 +106,7 @@ class Session extends \common\components\ActiveRecordModel ...@@ -106,7 +106,7 @@ class Session extends \common\components\ActiveRecordModel
$query->andWhere([ $query->andWhere([
Test::tableName() . '.session_id' => $this->id, Test::tableName() . '.session_id' => $this->id,
'is_passed' => Passing::PASSED, 'passed' => Passing::PASSED,
]); ]);
$query->groupBy(['user_id', 'test_id']); $query->groupBy(['user_id', 'test_id']);
......
...@@ -10,6 +10,7 @@ use yii\helpers\ArrayHelper; ...@@ -10,6 +10,7 @@ use yii\helpers\ArrayHelper;
use common\modules\testings\models\Passing; use common\modules\testings\models\Passing;
use common\modules\testings\models\Session; use common\modules\testings\models\Session;
use common\modules\testings\models\Question; use common\modules\testings\models\Question;
use common\modules\school\models\Lessons;
class Test extends \common\components\ActiveRecordModel class Test extends \common\components\ActiveRecordModel
{ {
...@@ -105,6 +106,11 @@ class Test extends \common\components\ActiveRecordModel ...@@ -105,6 +106,11 @@ class Test extends \common\components\ActiveRecordModel
return $this->hasOne(Question::className(), ['id' => 'test_id']); return $this->hasOne(Question::className(), ['id' => 'test_id']);
} }
public function getLesson()
{
return $this->hasOne(Lessons::className(), ['test_id' => 'id']);
}
public static function getTestsList($session_id) public static function getTestsList($session_id)
{ {
return ArrayHelper::map(self::find()->where(['session_id' => $session_id]), 'id', 'name'); return ArrayHelper::map(self::find()->where(['session_id' => $session_id]), 'id', 'name');
......
<?php
/*
$this->tabs = array(
'добавить' => $this->createUrl('create')
);
*/
$this->widget('AdminGrid', array(
'id' => 'testing-mistake-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array('name' => 'passing_id'),
array('name' => 'description'),
array(
'name' => 'is_expert_agreed',
'value' => 'TestingMistake::$state_list[$data->is_expert_agreed]',
),
array('name' => 'create_date'),
array(
'class' => 'CButtonColumn',
),
),
));
<?php
echo $form;
\ No newline at end of file
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
use common\modules\testings\models\Mistake;
/* @var $this yii\web\View */
?>
<div class="faq-view">
<p>
<?= Html::a(Yii::t('content', 'Update'), ['update', 'passing' => $model->passing_id], ['class' => 'btn btn-primary']) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'description',
[
'attribute' => 'is_expert_agreed',
'value' => Mistake::$state_list[$model->is_expert_agreed],
],
'create_date',
],
]) ?>
</div>
<?php
// if ($model->files) {
// $this->widget('fileManager.portlets.FileList', array(
// 'model' => $model,
// 'tag' => 'files',
// 'tagName' => 'div',
// 'htmlOptions' => array(
// 'class' => 'file-list',
// 'style' => 'margin: 20px 10px 0 10px;'
// ),
// ));
// }
\ No newline at end of file
...@@ -62,14 +62,6 @@ use common\modules\testings\models\Passing; ...@@ -62,14 +62,6 @@ use common\modules\testings\models\Passing;
return Html::a($model->user->email, "mailto:" . $model->user->email); return Html::a($model->user->email, "mailto:" . $model->user->email);
} }
], ],
[
'attribute' => 'filter_user_company_name',
'format' => 'html',
'value' => function($model)
{
return $model->user->company_name;
}
],
[ [
'attribute' => 'test_id', 'attribute' => 'test_id',
'format' => 'html', 'format' => 'html',
...@@ -80,7 +72,7 @@ use common\modules\testings\models\Passing; ...@@ -80,7 +72,7 @@ use common\modules\testings\models\Passing;
} }
], ],
[ [
'attribute' => 'is_passed', 'attribute' => 'status',
'format' => 'html', 'format' => 'html',
'filter' => Passing::$state_list, 'filter' => Passing::$state_list,
'value' => function($model) 'value' => function($model)
...@@ -88,46 +80,16 @@ use common\modules\testings\models\Passing; ...@@ -88,46 +80,16 @@ use common\modules\testings\models\Passing;
return Html::tag("span", Passing::$state_list[$model->status], ["class" => "STATE" . $model->status]); return Html::tag("span", Passing::$state_list[$model->status], ["class" => "STATE" . $model->status]);
} }
], ],
'pass_date',
[ [
'header' => 'Ответственный менеджер', 'attribute' => 'passed',
'format' => 'html', 'format' => 'html',
'filter' => Passing::$passed_list,
'value' => function($model) 'value' => function($model)
{ {
if($model->user && $model->user->manager) return Html::tag("span", Passing::$passed_list[$model->passed], ["class" => "STATE" . $model->passed]);
{
return Html::a($model->user->manager->name, ["/users/user-admin/view", "id" => $model->user->manager->id]);
}
else
{
return "Пользователь удалён";
}
}
],
[
'header' => 'Загрузить сообщение об ошибке',
'format' => 'html',
'filter' => false,
'value' => function($model)
{
if($model->is_passed !== null)
{
if($model->mistake)
{
$text = "Сведения " . $model->mistake->create_date;
}
else
{
$text = "Загрузить";
}
return Html::a($text, ["/testings/passing-admin/mistake", "id" => $model->id]);
}
else
{
return "";
}
} }
], ],
'end_date',
[ [
'class' => 'common\components\ColorActionColumn', 'class' => 'common\components\ColorActionColumn',
'template' => '{view} {delete}', 'template' => '{view} {delete}',
......
...@@ -28,7 +28,7 @@ use common\modules\testings\models\Passing; ...@@ -28,7 +28,7 @@ use common\modules\testings\models\Passing;
'attributes' => [ 'attributes' => [
[ [
'attribute' => 'user_id', 'attribute' => 'user_id',
'value' => ($model->user) ? Html::a($model->user->fio, ["/testings/user-admin/view", "id" => $model->user->id]) : "Пользователь удалён", 'value' => ($model->user) ? $model->user->surname . ' ' . $model->user->name : "Пользователь удалён",
'format' => 'html', 'format' => 'html',
], ],
[ [
...@@ -42,11 +42,11 @@ use common\modules\testings\models\Passing; ...@@ -42,11 +42,11 @@ use common\modules\testings\models\Passing;
'format' => 'html', 'format' => 'html',
], ],
[ [
'attribute' => 'is_passed', 'attribute' => 'passed',
'format' => 'raw', 'format' => 'raw',
'value' => Passing::$state_list[$model->is_passed] . " ({$model->CountPassedQuestions} - {$model->percent_rights}%)", 'value' => Passing::$passed_list[$model->passed] . " ({$model->CountPassedQuestions} - {$model->percent}%)",
], ],
'pass_date', 'end_date',
], ],
]) ?> ]) ?>
......
...@@ -30,7 +30,7 @@ use \common\components\zii\AdminGrid; ...@@ -30,7 +30,7 @@ use \common\components\zii\AdminGrid;
'start_date', 'start_date',
'end_date', 'end_date',
[ [
'header' => 'Назначено тестов', 'header' => 'Прохождений',
'value' => function($model) 'value' => function($model)
{ {
return $model->usersOverall; return $model->usersOverall;
...@@ -66,14 +66,6 @@ use \common\components\zii\AdminGrid; ...@@ -66,14 +66,6 @@ use \common\components\zii\AdminGrid;
return Html::a("Список групп", ["/testings/user-admin/manage-group", "session" => $model->id]); return Html::a("Список групп", ["/testings/user-admin/manage-group", "session" => $model->id]);
}, },
], ],
[
'header' => 'Список пользователей',
'format' => 'html',
'value' => function($model)
{
// return Html::a("Список пользователей", ["/testings/user-admin/manage", "session" => $model->id]);
},
],
[ [
'header' => 'Список прохождений', 'header' => 'Список прохождений',
'format' => 'html', 'format' => 'html',
...@@ -82,14 +74,6 @@ use \common\components\zii\AdminGrid; ...@@ -82,14 +74,6 @@ use \common\components\zii\AdminGrid;
return Html::a("Список прохождений", ["/testings/passing-admin/manage", "session" => $model->id]); return Html::a("Список прохождений", ["/testings/passing-admin/manage", "session" => $model->id]);
}, },
], ],
// [
// 'header' => 'Статистика прохождений',
// 'format' => 'html',
// 'value' => function($model)
// {
// return Html::a("Статистика прохождений", ["/testings/passing-admin/statistics", "session" => $model->id]);
// },
// ],
[ [
'class' => 'common\components\ColorActionColumn', 'class' => 'common\components\ColorActionColumn',
'template' => '{view} {update}', 'template' => '{view} {update}',
......
...@@ -14,7 +14,7 @@ use yii\widgets\DetailView; ...@@ -14,7 +14,7 @@ use yii\widgets\DetailView;
<p> <p>
<?= Html::a(Yii::t('content', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?> <?= Html::a(Yii::t('content', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a("Экспорт результатов", ['testings/session-admin/export-session-result', 'id' => $model->id], ['class' => 'btn btn-info']) ?> <!-- <?= Html::a("Экспорт результатов", ['testings/session-admin/export-session-result', 'id' => $model->id], ['class' => 'btn btn-info']) ?> -->
</p> </p>
<?= DetailView::widget([ <?= DetailView::widget([
...@@ -27,10 +27,4 @@ use yii\widgets\DetailView; ...@@ -27,10 +27,4 @@ use yii\widgets\DetailView;
], ],
]) ?> ]) ?>
<?php echo '<br/><br/><h2>Продленные сессии</h2>'; ?>
<?php foreach ($users as $time => $user)
{
echo $user->first_name.' '.$user->last_name.' '.$user->patronymic.' до '.$time.'<br/>';
} ?>
</div> </div>
\ No newline at end of file
...@@ -44,6 +44,8 @@ if($session) ...@@ -44,6 +44,8 @@ if($session)
'minutes', 'minutes',
'questions', 'questions',
'pass_percent', 'pass_percent',
'passed_scores',
'notpassed_scores',
'attempt', 'attempt',
[ [
'header' => 'Список вопросов', 'header' => 'Список вопросов',
......
...@@ -29,6 +29,8 @@ use yii\widgets\DetailView; ...@@ -29,6 +29,8 @@ use yii\widgets\DetailView;
'minutes', 'minutes',
'questions', 'questions',
'pass_percent', 'pass_percent',
'passed_scores',
'notpassed_scores',
'attempt', 'attempt',
'create_date', 'create_date',
], ],
......
<?php <?php
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use common\models\Settings;
?> ?>
...@@ -18,47 +22,43 @@ use yii\helpers\Html; ...@@ -18,47 +22,43 @@ use yii\helpers\Html;
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<h1 class="successfully_title">Тестирование не завершено.</h1> <h1 class="successfully_title">Сожалеем, но у вас закончилось время.</h1>
<h6>Для переназначения теста позвоните в службу поддержки по телефону +7 903 961-42-29</h6> <div class="successfully_subtitle" style="color: #4A6377;font-size: 36px;margin-top:10px;">Вам начислено <?=$model->points?> баллов</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="list_back" style="padding-bottom: 0;">
<a href="<?=Url::to(['/testing/gen-pass/'.$model->test_id])?>">Попробуйте пройти тест еще раз</a>
</div>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<div class="error_fedback clearfix"> <div class="error_fedback clearfix">
<h6>Обратная связь</h6> <h6>Скажите, какие вопросы вызывали трудности?</h6>
<?php $form = ActiveForm::begin([
'id' => 'error-testing-form',
'action' => ['/testing/send-not-attempt/'.$model->id]
])?>
<?=Html::beginForm();?> <?=Html::textArea('message', '', ['placeholder' => 'Введите сообщение'])?>
<h6>Обратная связь</h6> <?=Html::submitButton('Отправить', [
<?=Html::textArea('message', '', ['placeholder' => 'Введите сообщение']);?>
<?=Html::ajaxSubmitButton(
'Отправить',
Url::to(['/testings/testingTest/sendNotAttempt', 'id' => $model->id]),
[
'dataType' => 'json',
'success' => 'js:function(data){
if(data.success)
{
console.log("+");
$(".error_fedback").html("<div class=\"row\"><div class=\"col-sm-8\" style=\"margin:0 auto;float:none;\"><div class=\"gray_box\"><p>" + data.message + "</p></div></div></div>");
}
}'
],
[
'class' => 'error_fedback_btn' 'class' => 'error_fedback_btn'
] ])?>
);?>
<div class="clear"></div> <?php ActiveForm::end()?>
<?=Html::endForm();?>
</div> </div>
</div> </div>
</div> </div>
<!-- <div class="row"> <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<div class="list_back"> <div class="list_back">
<a href="/testings/test/index">Вернуться к списку тестов <span>↑</span></a> <a href="<?=Url::to(['/school/course/'.$model->test->lesson->course->id])?>">Вернуться к списку уроков <span></span></a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<a href="<?=Url::to(['/school/lesson/'.$model->test->lesson->id])?>">Вернуться к уроку <span></span></a>
</div>
</div> </div>
</div> </div>
</div> -->
<div class="row"> <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<div class="read_box_wr"> <div class="read_box_wr">
......
<?php
$this->page_title = $model->test->session->name;
$this->crumbs = array(
'Тестирование' => array('/testings/testingTest/index'),
$model->test->name => false,
);
?>
<?php if (Yii::app()->user->hasFlash('flash')) : ?>
<div class="message"><span>
<?php echo Yii::app()->user->getFlash('flash'); ?>
</span></div>
<?php endif; ?>
<div class="row">
<div class="col-sm-12">
<div class="not_passed_text">
<?=Setting::getValue('text_pass_not_time');?>
</div>
</div>
</div>
<div class="test_parameters not_passed_test">
<div class="row">
<div class="col-sm-6">
<h6>Тест пройден на:</h6>
<h5><?php echo $model->percent; ?>%</h5>
</div>
<div class="col-sm-6">
<h6>Прохождение теста у Вас заняло:</h6>
<?php
$minutesText = TestingPassing::declOfNum(floor($model->time / 60), array(' минута ', ' минуты ', ' минут '));
$secondsText = TestingPassing::declOfNum($model->time % 60, array(' секунда', ' секунды', ' секунд'));
?>
<h5><?=$minutesText?><?=$secondsText?></h5>
</div>
</div>
<br>
</div>
<?php if($model->gammas && !$model->test->mix) : ?>
<div class="row">
<div class="col-sm-12">
<div class="statistics_test_wr">
<ul class="statistics_test">
<?php foreach ($model->gammas as $gamma) : ?>
<li><span><?php echo $model->gammaPercent($gamma->id); ?>%</span><?php echo $gamma->name; ?> (<?php echo TestingGamma::$type_list[$gamma->type]; ?>)</li>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
<?php endif; ?>
<div class="row">
<div class="col-sm-12">
<div class="list_back">
<a href="/testings/testingTest/index">Вернуться к списку тестов <span></span></a>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="green_wr not_passed_test_progress">
<div class="green_box">
<div class="progress_ins">
<span class="col_text">Вопрос <strong class="green_text"><?=$model->test->questions?></strong> из <strong class="green_text"><?=$model->test->questions?></strong></span>
<div class="progress_wr">
<div class="progress">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
<span class="sr-only">100% Complete (success)</span>
</div>
</div>
</div>
<div class="progress_done">
Выполнено 100%
</div>
</div>
<div class="time_progress">
<p>Затраченное время:</p>
<span><?=date("H:i:s", mktime(0, 0, $model->time));?></span>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<br>
\ No newline at end of file
This diff is collapsed.
<?php
use yii\helpers\Url;
use common\modules\testings\models\Passing;
?>
<section class="top_line_testing"> <section class="top_line_testing">
<div class="container"> <div class="container">
<div class="row"> <div class="row">
...@@ -12,13 +20,13 @@ ...@@ -12,13 +20,13 @@
<div class="container"> <div class="container">
<div class="row"> <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<?php if ($model->is_passed == TestingPassing::PASSED) : ?> <?php if ($model->passed == Passing::PASSED) : ?>
<h1 class="successfully_title">Поздравляем, Вы сдали тест</h1> <h1 class="successfully_title">Поздравляем, Вы сдали тест</h1>
<div class="successfully_subtitle">Тестирование завершено</div> <?php elseif ($model->passed == Passing::FAILED) : ?>
<?php elseif ($model->is_passed == TestingPassing::FAILED) : ?>
<h1 class="successfully_title">Тест не сдан!</h1> <h1 class="successfully_title">Тест не сдан!</h1>
<div class="successfully_subtitle">Тестирование завершено</div>
<?php endif; ?> <?php endif; ?>
<div class="successfully_subtitle" style="color: #404146;font-size: 20px;">Количество набранных баллов:</div>
<div class="successfully_subtitle" style="color: #4A6377;font-size: 36px;margin-top:-15px;"><?=$model->points?></div>
</div> </div>
</div> </div>
<div class="row"> <div class="row">
...@@ -35,6 +43,14 @@ ...@@ -35,6 +43,14 @@
<div class="succes_block_cont"><?=$minutesText?> <?=$secondsText?></div> <div class="succes_block_cont"><?=$minutesText?> <?=$secondsText?></div>
</div> </div>
</div> </div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<div class="list_back">
<a href="<?=Url::to(['/school/course/'.$model->test->lesson->course->id])?>">Вернуться к списку уроков <span></span></a> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
<a href="<?=Url::to(['/school/lesson/'.$model->test->lesson->id])?>">Вернуться к уроку <span></span></a>
</div>
</div>
</div>
<!-- <div class="row"> <!-- <div class="row">
<div class="col-md-12 col-xs-12 col-sm-12"> <div class="col-md-12 col-xs-12 col-sm-12">
<ul class="stat_testing"> <ul class="stat_testing">
...@@ -62,3 +78,5 @@ ...@@ -62,3 +78,5 @@
</div> </div>
</div> </div>
</section> </section>
<?php echo $this->render('@app/views/layouts/footer-testing'); ?>
\ No newline at end of file
<?php
use yii\helpers\Url;
use common\modules\testings\widgets\NotCloseTabsWidget;
use common\modules\testings\models\Question;
?>
<?php
$questions = [];
$count = 0;
foreach ($model->questions as $question)
{
$count++;
$pictures = [];
foreach ($question->question->files as $file)
{
$pictures[] = $file->url;
}
$answers = [];
// если ответ вводит сам пользователь, нельзя отправлять ответ - поскольку в нём указан верный ответ.
foreach ($question->question->answers as $answer)
{
if ($question->question->type <> Question::USER_ANSWER)
{
$answers[] = $answer->text;
}
else
{
$answers[] = 'тут должен быть ответ';
}
}
$questions[$count] = [
'id' => $question->question->id,
'text' => $question->question->text,
'type' => $question->question->type,
'pictures' => $pictures,
'answers' => $answers,
'userAnswer' => '',
'time' => 0,
'theme' => $question->question->theme->name,
];
}
?>
<script type="text/javascript">
$(function(){
countDown.init({
continue: <?=($model->start_date?'true':'false')?>,
startDate: '<?=date("d F Y H:i:s", strtotime($model->start_date))?>',
startDateTime: <?=strtotime($model->start_date)?>,
minutes: <?=$model->test->minutes;?>,
time: <?=time()?>
});
tester.init({
global_id: <?=$current_answer?>,
one_option: <?=Question::ONE_OPTION?>,
few_options: <?=Question::FEW_OPTIONS?>,
user_answer: <?=Question::USER_ANSWER?>,
delimiter: '<?=Question::DELIMITER?>',
questions_count: <?=count($questions)?>,
questions: <?=\yii\helpers\Json::encode($questions)?>,
answerUrl: '<?=Url::to(["/testing/set-answer/".$model->id])?>',
finishUrl: '<?=Url::to(["/testing/finish-test/".$model->id])?>',
passUrl: '<?=Url::to(["/testing/pass/".$model->id])?>'
});
});
</script>
<section class="top_line_testing">
<div class="container">
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<strong>Тест: </strong>
<p><?=$model->test->name?> | <span id="questionThemeBox"></span></p>
</div>
</div>
</div>
</section>
<section class="testing_block">
<div class="container">
<?= NotCloseTabsWidget::widget() ?>
<br>
<div class="row">
<div class="col-md-1 col-xs-1 col-sm-2">
<span class="testing_num questionNumber"></span>
</div>
<div class="col-md-11 col-xs-11 col-sm-10">
<h1 class="testing_block_title" id="questionTextBox"></h1>
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12" id="questionPictureBox">
</div>
</div>
<div class="row">
<div class="col-md-12 col-xs-12 col-sm-12">
<form class="testing_form">
<div class="questions" id="answerBox"></div>
<div class="answer" id="sendInfoBox"></div>
<button id="clickNext" class="testing_form_btn" onClick="tester.nextQuestion(); return false;">Подтвердить ответ</button>
</form>
</div>
</div>
<div class="row col-md-12 col-xs-12 col-sm-12">
<h4 class="testing_info_foot" id="messageStep50"></h4>
<h4 class="testing_info_foot" id="messageStep75"></h4>
<h4 class="testing_info_foot" id="messageStep100"></h4>
</div>
</div>
</section>
<section class="testing_foot">
<div class="container">
<div class="row">
<div class="test_ft clearfix">
<div class="col-md-6 col-xs-8 col-sm-12">
<div class="testing_votes">Вопрос <strong class="questionNumber">1</strong> из <strong><?=count($questions)?></strong></div>
<div class="testing_progress"><div class="testing_progress_proc" id="progressbar" style="width:0%;"></div></div>
</div>
<div class="col-md-6 col-xs-4 col-sm-12">
<div class="testing_time">До конца осталось: <span id="countdown_timer"></span></div>
</div>
</div>
</div>
</div>
</section>
<?php echo $this->render('@app/views/layouts/footer-testing'); ?>
\ No newline at end of file
...@@ -10,7 +10,7 @@ class NotCloseTabsWidget extends Widget ...@@ -10,7 +10,7 @@ class NotCloseTabsWidget extends Widget
public function run() public function run()
{ {
return $this->render('NotCloseTabsWidget', [ return $this->render('NotCloseTabsWidget', [
'message' => Settings::getValue('not_close_tabs_message'); 'message' => Settings::getValue('not_close_tabs_message')
]); ]);
} }
} }
......
...@@ -161,6 +161,9 @@ class Conditions { ...@@ -161,6 +161,9 @@ class Conditions {
// Привели массив в понятный вид // Привели массив в понятный вид
$conditionsArray=[]; $conditionsArray=[];
foreach($conditions as $i=>$condition) { foreach($conditions as $i=>$condition) {
$object=Conditions::init()->getConditionById($condition->condition_id);
if ($object->recall===false)
return false;
$conditionsArray[$i][] = $condition; $conditionsArray[$i][] = $condition;
} // На выходе получаем массив необходимого формата } // На выходе получаем массив необходимого формата
// Обрабатываем отформатированный массив // Обрабатываем отформатированный массив
......
...@@ -13,7 +13,9 @@ use common\modules\triggers\components\conditions\vendor\ConditionBase; ...@@ -13,7 +13,9 @@ use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface; use common\modules\triggers\components\conditions\vendor\ConditionInterface;
use common\modules\triggers\models\TriggerCondition; use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerParam; use common\modules\triggers\models\TriggerParam;
use common\modules\triggers\models\TriggerSchedule;
use common\modules\triggers\models\TriggerTrigger; use common\modules\triggers\models\TriggerTrigger;
use yii\web\BadRequestHttpException;
class CheckPresenceTime extends ConditionBase implements ConditionInterface { class CheckPresenceTime extends ConditionBase implements ConditionInterface {
const CONDITION_ID=5; const CONDITION_ID=5;
...@@ -30,32 +32,56 @@ class CheckPresenceTime extends ConditionBase implements ConditionInterface { ...@@ -30,32 +32,56 @@ class CheckPresenceTime extends ConditionBase implements ConditionInterface {
return parent::init($conditionName); return parent::init($conditionName);
} }
public function initScript(){ public function initScript($cron_time=180){
return true; // Получили список всех активных (актуальных) триггеров
/** @var TriggerTrigger[] $actualTriggers */ /** @var TriggerTrigger[] $actualTriggers */
$actualTriggers = TriggerTrigger::getActualTriggers(self::CONDITION_ID); $actualTriggers = TriggerTrigger::getActualTriggers(self::CONDITION_ID);
// Перебираем их в цикле
foreach($actualTriggers as $trigger) { foreach($actualTriggers as $trigger) {
// Получили условия триггера на итерации
$conditions = TriggerCondition::find()->where(['trigger_id' => $trigger->getPrimaryKey()])->all(); $conditions = TriggerCondition::find()->where(['trigger_id' => $trigger->getPrimaryKey()])->all();
// Перебираем все условия триггера на итерации
foreach($conditions as $condition) { foreach($conditions as $condition) {
// Пытаемся получить параметр URL в условии
/** @var TriggerParam $paramUrl */ /** @var TriggerParam $paramUrl */
$paramUrl = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'url'])->one(); $paramUrl = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'url'])->one();
// Пытаемся получить параметр времени на условии
/** @var TriggerParam $paramTime */
$paramTime = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'time'])->one(); $paramTime = TriggerParam::find()->where(['condition_id'=>$condition->getPrimaryKey(), 'key'=>'time'])->one();
if ($condition->condition_id==self::CONDITION_ID && $paramUrl!==null && $paramUrl->value==\Yii::$app->request->getUrl()) { // Если сработали условия что триггер есть, у него указаны время и URL и при этом он является триггером ДАННОГО типа
if ($condition->condition_id==self::CONDITION_ID && $paramUrl!==null && $paramUrl->value==\Yii::$app->request->getUrl() && $paramTime!==null) {
$now = new \DateTime();
$time = new \DateTime();
$time->modify('+ '.(((int)$trigger->timeout<(int)$cron_time) ? $cron_time : (int)$trigger->timeout+(int)$cron_time).' second');
// Заносим запись в базу
$model = new TriggerSchedule();
$model->sended = 0;
$model->checked = 0;
$model->message = 'Test the presence time';
$model->email = \common\modules\users\models\User::findOne(\Yii::$app->user->id)->email;
$model->time = $time->format('Y-m-d H:i:s');
$model->date_create = $now->format('Y-m-d H:i:s');
if ($model->save()) {
$view = \Yii::$app->controller->view; $view = \Yii::$app->controller->view;
$script ='$(window).on("beforeunload", function() { // Создаем скрипт
var timer='.(($paramTime!==null) ? $paramTime->value : 0).'; $script ='$(document).ready(function() {
if(timer>0){ var timer='.((int)$paramTime->value*1000).';
setTimeout(function() {
$.ajax({ $.ajax({
url: "/triggers/default/inittrigger", url: "/triggers/default/dropschedule",
method: "GET", method: "GET",
async: false, async: false,
data: { data: {
id: '.$trigger->getPrimaryKey().' id: '.$model->getPrimaryKey().'
}, },
}); });
} }, timer);
});'; });';
echo $view->registerJs($script, $view::POS_READY); // Регистрируем его
$view->registerJs($script, $view::POS_READY);
} else {
throw new BadRequestHttpException(current(current($model->getErrors())), 500);
}
} }
} }
} }
......
<?php
namespace common\modules\triggers\components\conditions\conditions;
use common\components\UnisenderAPI;
use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface;
class CheckUserToRegistration extends ConditionBase implements ConditionInterface{
const CONDITION_ID = 6;
public $recall=false;
public $name = 'Пользователь зарегистрировался';
/**
* @param null|string $conditionName
* @return $this mixed
*/
public static function init($conditionName=__CLASS__){
return parent::init($conditionName);
}
/**
* @param $message
* @return bool
*/
public function check($message){
return true;
}
}
\ No newline at end of file
...@@ -9,6 +9,9 @@ return [ ...@@ -9,6 +9,9 @@ return [
'check-email-to-unsubscribed' => [ 'check-email-to-unsubscribed' => [
'class' => 'common\modules\triggers\components\conditions\conditions\CheckEmailToUnsubscribed', 'class' => 'common\modules\triggers\components\conditions\conditions\CheckEmailToUnsubscribed',
], ],
'check-user-to-registration' => [
'class' => 'common\modules\triggers\components\conditions\conditions\CheckUserToRegistration',
],
'check-clicking-on-the-link' => [ 'check-clicking-on-the-link' => [
'class' => 'common\modules\triggers\components\conditions\conditions\CheckClickingOnTheLink', 'class' => 'common\modules\triggers\components\conditions\conditions\CheckClickingOnTheLink',
'params' => [ 'params' => [
......
...@@ -7,6 +7,8 @@ use yii\helpers\Html; ...@@ -7,6 +7,8 @@ use yii\helpers\Html;
class ConditionBase { class ConditionBase {
protected static $conditionClass; protected static $conditionClass;
public $recall = true;
public $name; public $name;
public $config = []; public $config = [];
......
...@@ -18,14 +18,12 @@ class DefaultController extends BaseController ...@@ -18,14 +18,12 @@ class DefaultController extends BaseController
return [ return [
'Index' => 'Главная страница модуля', 'Index' => 'Главная страница модуля',
'Rechecktriggers' => 'Запуск проверки срабатывания триггеров', 'Rechecktriggers' => 'Запуск проверки срабатывания триггеров',
'Inittrigger' => 'Init trigger By id' 'Dropschedule' => 'Drop schedule By id'
]; ];
} }
public function actionInittrigger($id){ public function actionDropschedule($id){
/** @var TriggerTrigger $trigger */ TriggerSchedule::findOne($id)->delete();
$trigger = TriggerTrigger::findOne($id);
$trigger->initAction();
} }
/** /**
...@@ -45,24 +43,31 @@ class DefaultController extends BaseController ...@@ -45,24 +43,31 @@ class DefaultController extends BaseController
// Получили текущую дату и время // Получили текущую дату и время
$timeNow = new DateTime(); $timeNow = new DateTime();
// Получили все те сообщения которые еще не обработаны и имеют дату равную или меньше текущей // Получили все те сообщения которые еще не обработаны и имеют дату равную или меньше текущей
$uncheckedArray = TriggerSchedule::find()->where('checked=:checked AND time <= :time_now', [':checked' => 0, ':time_now' => $timeNow->format('Y-m-d H:i:s')])->all(); /** @var TriggerSchedule[] $uncheckedArray */
$uncheckedArray = TriggerSchedule::find()->where('time <= :time_now', [':time_now' => $timeNow->format('Y-m-d H:i:s')])->all();
// Получили все актуальные триггеры в базе // Получили все актуальные триггеры в базе
$actualTriggers = TriggerTrigger::getActualTriggers(); $actualTriggers = TriggerTrigger::getActualTriggers();
// Перебираем эти сообщения в цикле // Перебираем эти сообщения в цикле
foreach($uncheckedArray as $message) { foreach($uncheckedArray as $message) {
$triggerIsUsed=false;
// Проверяем каждое сообщение на срабатывание триггера // Проверяем каждое сообщение на срабатывание триггера
foreach($actualTriggers as $trigger) { foreach($actualTriggers as $trigger) {
// Вызвали срабатывание условий // Вызвали метод проверки срабатывания условий
$triggerResult = Conditions::init()->handleMessageByTriggerId($message, $trigger->getPrimaryKey()); $triggerResult = Conditions::init()->handleMessageByTriggerId($message, $trigger->getPrimaryKey());
// Если триггер сработал инициируем действие // Если триггер сработал инициируем действие
if ($triggerResult===true) { if ($triggerResult===true) {
$trigger->initAction($message); $triggerIsUsed=true;
$init = $trigger->initAction(['email' => $message->email]);
if ($init!==true)
echo $init;
} }
} }
if ($triggerIsUsed===true) {
/** @var TriggerSchedule $model */ /** @var TriggerSchedule $model */
$model=TriggerSchedule::findOne($message->getPrimaryKey()); $model=TriggerSchedule::findOne($message->getPrimaryKey());
$model->checked=1; $model->checked=1;
$model->save(); $model->save();
} }
} }
}
} }
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
namespace common\modules\triggers\controllers; namespace common\modules\triggers\controllers;
use common\modules\triggers\models\TriggerCondition;
use Yii; use Yii;
use common\modules\triggers\components\conditions\Conditions; use common\modules\triggers\components\conditions\Conditions;
use common\modules\triggers\components\conditions\vendor\ConditionBase; use common\modules\triggers\components\conditions\vendor\ConditionBase;
...@@ -47,9 +48,15 @@ class TriggerAdminController extends AdminController { ...@@ -47,9 +48,15 @@ class TriggerAdminController extends AdminController {
} }
public function actionTesting(){ public function actionTesting(){
return $this->render( $trigger = \common\modules\triggers\components\conditions\conditions\CheckClickingOnTheLink::init();
'testing' $trigger->model = TriggerCondition::find()->where(['id' => 11])->one();
); $model = \common\modules\triggers\models\TriggerSchedule::find()->where(['id'=>24])->one();
$trigger->check($model);
// return $this->render(
// 'testing'
// );
} }
public function actionGetresult($id){ public function actionGetresult($id){
......
...@@ -34,7 +34,7 @@ class TriggerSchedule extends \yii\db\ActiveRecord ...@@ -34,7 +34,7 @@ class TriggerSchedule extends \yii\db\ActiveRecord
public function rules() public function rules()
{ {
return [ return [
[['sended', 'checked', 'message_id', 'list_id', 'campaign_id'], 'integer'], [['sended', 'checked', /*'message_id',*/ 'list_id', 'campaign_id'], 'integer'],
[['message', 'email'], 'required'], [['message', 'email'], 'required'],
[['message'], 'string'], [['message'], 'string'],
[['time', 'date_create'], 'safe'], [['time', 'date_create'], 'safe'],
......
...@@ -2,10 +2,14 @@ ...@@ -2,10 +2,14 @@
namespace common\modules\triggers\models; namespace common\modules\triggers\models;
use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\triggers\components\conditions\Conditions; use common\modules\triggers\components\conditions\Conditions;
use Faker\Provider\tr_TR\DateTime; use Faker\Provider\tr_TR\DateTime;
use Yii; use Yii;
use common\modules\messageTemplate\components\Templates;
use common\modules\users\models\User; use common\modules\users\models\User;
use common\components\UnisenderAPI;
use yii\helpers\Json;
/** /**
* This is the model class for table "trigger_trigger". * This is the model class for table "trigger_trigger".
...@@ -205,9 +209,85 @@ class TriggerTrigger extends \common\components\ActiveRecordModel ...@@ -205,9 +209,85 @@ class TriggerTrigger extends \common\components\ActiveRecordModel
/** /**
* Тут выполняем то, что произойдет когда триггер сработает * Тут выполняем то, что произойдет когда триггер сработает
* @param null $message *
* @param array $params
* @return string
*/ */
public function initAction($message=null){ public function initAction($params=array()){
echo "ASD"; $templateData = [];
if (array_key_exists('email', $params))
$email = $params['email'];
elseif(empty($email) && !Yii::$app->user->isGuest) {
$email = Yii::$app->user->identity->email;
} else {
return 'Email not found';
}
$user = User::find()->where(['email' => $email])->one();
if (array_key_exists('user_fio', $params))
$user_fio = $params['user_fio'];
elseif(!is_null($user)) {
$user_fio = $user->fio;
}
$templateData['user_fio'] = (isset($user_fio)) ? $user_fio : '';
/** @var \DateTime $time_now */
$time_now=new \DateTime();
/** @var MessageTemplate $templateModel */
$templateModel = MessageTemplate::findOne($this->message_template_id);
/** @var Templates $template */
$template = new Templates($this->message_template_id, $templateData);
$sender = new UnisenderAPI();
// Create the send list
$newList = $sender->createList();
$newListObject=Json::decode($newList);
if (array_key_exists('result', $newListObject) && is_array($newListObject['result']) && array_key_exists('id', $newListObject['result'])) {
$newListId=$newListObject['result']['id'];
// Subscribe user to new List
$sender->subscribe(['list_ids' => $newListId, 'fields[email]' => $email, 'double_optin' => 1]);
// Create new message
$newMessage=$sender->createEmailMessage('Школа аналитики "Арт Проект"', 'subscribe@task-on.com', $templateModel->subject, $template->getTemplate(), $newListId);
// Decode result
$newMessageObject=Json::decode($newMessage);
if (array_key_exists('result', $newMessageObject) && is_array($newMessageObject['result']) && array_key_exists('message_id', $newMessageObject['result'])) {
// Get the message ID
$newMessageId=$newMessageObject['result']['message_id'];
// Create new campaign
$newCampaign = $sender->createCampaign($newMessageId);
// Parse the result
$newCampaignObject = Json::decode($newCampaign);
if (array_key_exists('result', $newCampaignObject) && is_array($newCampaignObject['result']) && array_key_exists('campaign_id', $newCampaignObject['result'])) {
$newCampaignId = $newCampaignObject['result']['campaign_id'];
$schedule = new TriggerSchedule();
$schedule->sended=1;
// $schedule->checked=(array_key_exists('checked', $params)) ? $params['checked'] : 0;
// $schedule->message_id=$newMessageId;
$schedule->message=$template->getTemplate();
$schedule->email=$email;
$schedule->time=$time_now->format('Y-m-d H:i:s');
$schedule->date_create=$time_now->format('Y-m-d H:i:s');
$schedule->list_id=$newListId;
$schedule->campaign_id=$newCampaignId;
if ($schedule->save()) {
return true;
} else {
return (current(current($schedule->getErrors())));
}
} else {
$error = (array_key_exists('error', $newCampaignObject)) ? $newCampaignObject['error'].' (createCampaign)' : 'Неизвестная ошибка (CreateCampaign)';
return $error;
}
} else {
$error = (array_key_exists('error', $newMessageObject)) ? $newMessageObject['error'].' (createMessage)' : 'Неизвестная ошибка (CreateMessage)';
return $error;
}
} else {
$error = (array_key_exists('error', $newListObject)) ? $newListObject['error'].' (createList)' : 'Неизвестная ошибка (CreateList)';
return $error;
}
} }
} }
...@@ -2,35 +2,36 @@ ...@@ -2,35 +2,36 @@
use \common\components\UnisenderAPI; use \common\components\UnisenderAPI;
use \yii\helpers\Json; use \yii\helpers\Json;
$email = 'bystrov@kupitsite.ru'; //$email = 'bystrov@kupitsite.ru';
$sender = new UnisenderAPI(); //$sender = new UnisenderAPI();
//$sender->validateSender('subscribe@task-on.com');
// Create the send list // Create the send list
$newList = $sender->createList(); //$newList = $sender->createList();
$newListObject=Json::decode($newList); //$newListObject=Json::decode($newList);
if (array_key_exists('result', $newListObject) && array_key_exists('id', $newListObject['result'])) { //if (array_key_exists('result', $newListObject) && array_key_exists('id', $newListObject['result'])) {
$newListId=$newListObject['result']['id']; // $newListId=$newListObject['result']['id'];
// Subscribe user to new List // // Subscribe user to new List
$subscribe = $sender->subscribe(['list_ids' => $newListId, 'fields[email]' => $email, 'double_optin' => 1]); // $subscribe = $sender->subscribe(['list_ids' => $newListId, 'fields[email]' => $email, 'double_optin' => 1]);
// Create new message // // Create new message
$newMessage=$sender->createEmailMessage('bystrov', $email, 'Testing Subject', 'Testing Body <br><a href="http://www.google.com/">Testing link</a><br><a href="{{_UnsubscribeUrl}}">Отписаться</a>', $newListId); // $newMessage=$sender->createEmailMessage('bystrov', $email, 'Testing Subject', 'Testing Body <br><a href="http://www.google.com/">Testing link</a><br><a href="{{_UnsubscribeUrl}}">Отписаться</a>', $newListId);
// Decode result // // Decode result
$newMessageObject=Json::decode($newMessage); // $newMessageObject=Json::decode($newMessage);
if (array_key_exists('result', $newMessageObject) && array_key_exists('message_id', $newMessageObject['result'])) { // if (array_key_exists('result', $newMessageObject) && array_key_exists('message_id', $newMessageObject['result'])) {
// Get the message ID // // Get the message ID
$newMessageId=$newMessageObject['result']['message_id']; // $newMessageId=$newMessageObject['result']['message_id'];
// Create new campaign // // Create new campaign
$newCampaign = $sender->createCampaign($newMessageId); // $newCampaign = $sender->createCampaign($newMessageId);
// Parse the result // // Parse the result
$newCampaignObject = Json::decode($newCampaign); // $newCampaignObject = Json::decode($newCampaign);
if (array_key_exists('result', $newCampaignObject) && array_key_exists('campaign_id', $newCampaignObject['result'])) { // if (array_key_exists('result', $newCampaignObject) && array_key_exists('campaign_id', $newCampaignObject['result'])) {
$newCampaignId = $newCampaignObject['result']['campaign_id']; // $newCampaignId = $newCampaignObject['result']['campaign_id'];
} // }
} // }
} //}
//
echo 'Рассылка: '.((isset($newCampaignId)) ? $newCampaignId : 'Not found'); //echo 'Рассылка: '.((isset($newCampaignId)) ? $newCampaignId : 'Not found');
echo '<br>'; //echo '<br>';
echo 'Список: '.((isset($newListId)) ? $newListId : 'Not found'); //echo 'Список: '.((isset($newListId)) ? $newListId : 'Not found');
echo '<br>'; //echo '<br>';
echo 'Сообщение: '.((isset($newMessageId)) ? $newMessageId : 'Not found'); //echo 'Сообщение: '.((isset($newMessageId)) ? $newMessageId : 'Not found');
\ No newline at end of file \ No newline at end of file
...@@ -5,6 +5,8 @@ use Yii; ...@@ -5,6 +5,8 @@ use Yii;
use common\modules\users\models\User; use common\modules\users\models\User;
use \common\modules\rbac\models\AuthAssignment; use \common\modules\rbac\models\AuthAssignment;
use common\modules\messageTemplate\models\MessageTemplate; use common\modules\messageTemplate\models\MessageTemplate;
use yii\base\Exception;
use yii\web\BadRequestHttpException;
class UserController extends \common\components\BaseController { class UserController extends \common\components\BaseController {
const ERROR_PASSWORD_RECOVER_AUTH = 'Вы не можете восстановить пароль будучи авторизованным!'; const ERROR_PASSWORD_RECOVER_AUTH = 'Вы не можете восстановить пароль будучи авторизованным!';
...@@ -141,12 +143,9 @@ class UserController extends \common\components\BaseController { ...@@ -141,12 +143,9 @@ class UserController extends \common\components\BaseController {
$params = []; $params = [];
$params['link_activate'] = Yii::$app->params['frontUrl'].'/activate/'.$model->activate_code; $params['link_activate'] = Yii::$app->params['frontUrl'].'/activate/'.$model->activate_code;
$params['link'] = Yii::$app->params['frontUrl']; $params['link'] = Yii::$app->params['frontUrl'];
$templateModel = MessageTemplate::findOne(['name' => 'Регистрация на сайте']);
$model->afterRegistration($templateModel->id, $params);
echo json_encode(array('success'=>true)); echo json_encode(array('success'=>true));
} } else {
else {
echo json_encode(array('errors'=>$model->getErrors())); echo json_encode(array('errors'=>$model->getErrors()));
} }
} }
......
...@@ -4,7 +4,10 @@ namespace common\modules\users\models; ...@@ -4,7 +4,10 @@ namespace common\modules\users\models;
use common\components\UnisenderAPI; use common\components\UnisenderAPI;
use common\modules\messageTemplate\controllers\TemplateAdminController; use common\modules\messageTemplate\controllers\TemplateAdminController;
use common\modules\messageTemplate\models\MessageTemplate; use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\triggers\components\conditions\conditions\CheckUserToRegistration;
use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerSchedule; use common\modules\triggers\models\TriggerSchedule;
use common\modules\triggers\models\TriggerTrigger;
use Yii; use Yii;
use yii\base\NotSupportedException; use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior; use yii\behaviors\TimestampBehavior;
...@@ -511,6 +514,26 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter ...@@ -511,6 +514,26 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return parent::beforeSave($insert); return parent::beforeSave($insert);
} }
public function validate($attributeNames = null, $clearErrors = true) {
if (!parent::validate($attributeNames = null, $clearErrors = true))
return false;
if ($this->scenario===self::SCENARIO_REGISTRATION) {
if (!$this->afterRegistration(['email' => $this->email, 'user_fio' => $this->getFio()]))
return false;
}
return true;
}
public function getFio()
{
$result = $this->name;
if (isset($this->surname) && strlen($this->surname)>0) {
$result .= ' '.$this->surname;
}
return $result;
}
public function beforeDelete() public function beforeDelete()
{ {
if (parent::beforeDelete()) if (parent::beforeDelete())
...@@ -545,10 +568,32 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter ...@@ -545,10 +568,32 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return (bool)static::find()->where('email = :email', [':email'=>$email])->count(); return (bool)static::find()->where('email = :email', [':email'=>$email])->count();
} }
/**
* Проверяем есть ли среди активных триггеров тот, у которого указан параметр проверки регистрации.
* Если указан, выполняем действия триггера
*/
public function afterRegistration($params=array()){
/** @var TriggerTrigger[] $actualTriggers */
$actualTriggers = TriggerTrigger::getActualTriggers();
foreach($actualTriggers as $trigger) {
$exists = TriggerCondition::find()->where(['trigger_id'=>$trigger->id, 'condition_id'=>CheckUserToRegistration::CONDITION_ID])->exists();
if ($exists===true) {
$init = $trigger->initAction($params);
if ($init===true) {
return true;
} else {
$this->addError('email', $init);
return false;
}
}
}
return true;
}
/** /**
* @param $template_id * @param $template_id
*/ */
public function afterRegistration($template_id, $params){ public function afterSubscribe($template_id, $params=array()){
/** @var \DateTime $time_now */ /** @var \DateTime $time_now */
$time_now=new \DateTime(); $time_now=new \DateTime();
/** @var MessageTemplate $templateModel */ /** @var MessageTemplate $templateModel */
......
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160224_162315_upgrade_bids_files extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->createTable('bids_files', [
'id' => Schema::TYPE_PK,
'bid_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'filename' => Schema::TYPE_STRING . '(100) DEFAULT NULL'
]);
$this->dropColumn('bids', 'filename');
$this->addForeignKey(
'fk_bids_files_bid_id_bids_id',
'bids_files', 'bid_id',
'bids', 'id'
);
}
public function safeDown()
{
$this->dropForeignKey('fk_bids_files_bid_id_bids_id', 'bids_files');
$this->dropTable('bids_files');
$this->addColumn('bids', 'filename', Schema::TYPE_STRING . '(50) DEFAULT NULL');
}
}
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160225_043622_fix_passing_table extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->alterColumn('testings_passings', 'attempt', Schema::TYPE_INTEGER . '(3) NOT NULL DEFAULT 0');
$this->addColumn('testings_passings', 'percent', Schema::TYPE_INTEGER . '(11) NOT NULL DEFAULT 0 AFTER points');
$this->addColumn('testings_passings', 'passed', Schema::TYPE_INTEGER . '(1) NOT NULL DEFAULT 0 AFTER status');
$this->dropTable('testings_mistakes');
}
public function safeDown()
{
$this->alterColumn('testings_passings', 'attempt', Schema::TYPE_INTEGER . '(3) NOT NULL');
$this->dropColumn('testings_passings', 'percent');
$this->dropColumn('testings_passings', 'passed');
$this->createTable('testings_mistakes', [
'id' => Schema::TYPE_PK,
'passing_id' => Schema::TYPE_INTEGER . '(11) NOT NULL',
'description' => Schema::TYPE_STRING . '(3000) NOT NULL',
'is_expert_agreed' => 'tinyint(1) NOT NULL',
'create_date' => Schema::TYPE_TIMESTAMP . ' NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
]);
}
}
<?php
use yii\db\Migration;
class m160226_101540_update_schedule_tinyint_columns extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->alterColumn(
'trigger_schedule',
'sended',
$this->integer(1)->defaultValue(0)->notNull()
);
$this->alterColumn(
'trigger_schedule',
'checked',
$this->integer(1)->defaultValue(0)->notNull()
);
}
public function safeDown()
{
$this->alterColumn(
'trigger_schedule',
'sended',
$this->smallInteger(1)->defaultValue(0)->notNull()
);
$this->alterColumn(
'trigger_schedule',
'checked',
$this->smallInteger(1)->defaultValue(0)->notNull()
);
}
}
...@@ -27,6 +27,10 @@ use common\modules\bids\models\Bid; ...@@ -27,6 +27,10 @@ use common\modules\bids\models\Bid;
], ],
]); ?> ]); ?>
<div class="message-box callback send_secce">Ваша заявка отправлена, мы вам перезвоним.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -49,6 +53,8 @@ use common\modules\bids\models\Bid; ...@@ -49,6 +53,8 @@ use common\modules\bids\models\Bid;
<?php echo Html::submitButton('Заказать звонок', ['class' => 'save-button popup_bt_send']); ?> <?php echo Html::submitButton('Заказать звонок', ['class' => 'save-button popup_bt_send']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
</div> </div>
\ No newline at end of file
...@@ -40,8 +40,8 @@ $more = CoContent::find() ...@@ -40,8 +40,8 @@ $more = CoContent::find()
<div class="col-md-6 col-xs-6 col-sm-12"> <div class="col-md-6 col-xs-6 col-sm-12">
<div class="subsc_block"> <div class="subsc_block">
<h2 class="subsc_block_title">Подписаться на обновление</h2> <h2 class="subsc_block_title">Подписаться на обновления</h2>
<div class="subsc_block_txt">Нам будет приятно, если вы захотите подписаться на обновление наших проектов</div> <div class="subsc_block_txt">Нам будет приятно, если вы захотите подписаться на обновления наших проектов</div>
<?php <?php
$model = new Bid; $model = new Bid;
$model->scenario = Bid::SCENARIO_SUBSCRIBE; $model->scenario = Bid::SCENARIO_SUBSCRIBE;
...@@ -58,6 +58,10 @@ $more = CoContent::find() ...@@ -58,6 +58,10 @@ $more = CoContent::find()
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Теперь вы подписаны на обновления кейсов.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -71,6 +75,8 @@ $more = CoContent::find() ...@@ -71,6 +75,8 @@ $more = CoContent::find()
<?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?> <?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
</div> </div>
......
...@@ -25,6 +25,10 @@ use common\modules\bids\models\Bid; ...@@ -25,6 +25,10 @@ use common\modules\bids\models\Bid;
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Теперь вы подписаны на обновления кейсов.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -38,9 +42,9 @@ use common\modules\bids\models\Bid; ...@@ -38,9 +42,9 @@ use common\modules\bids\models\Bid;
<?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?> <?php echo Html::submitButton('Подписаться', ['class' => 'save-button']); ?>
<?php ActiveForm::end(); ?> </div>
<div class="send_secce" style="display:none;">Вы успешно подписались на обновление раздела «Кейсы». Нам приятно, что вы следите за нашим развитием :-)</div> <?php ActiveForm::end(); ?>
</div> </div>
</div> </div>
</div> </div>
\ No newline at end of file
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
<?php $this->registerJsFile('/js/modernizr.min.js', ['position' => yii\web\View::POS_END ]);?> <?php $this->registerJsFile('/js/modernizr.min.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/libs/bootstrap/js/bootstrap.min.js', ['position' => yii\web\View::POS_END ]);?> <?php $this->registerJsFile('/js/libs/bootstrap/js/bootstrap.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/libs/waypoints/waypoints.min.js', ['position' => yii\web\View::POS_END ]);?> <?php $this->registerJsFile('/js/libs/waypoints/waypoints.min.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/libs/magnific/jquery.magnific-popup.min.js', ['position' => yii\web\View::POS_END ]);?> <?php $this->registerJsFile('/js/libs/magnific/jquery.magnific-popup.min.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/libs/bxslider/jquery.bxslider.min.js', ['position' => yii\web\View::POS_END ]);?> <?php $this->registerJsFile('/js/libs/bxslider/jquery.bxslider.min.js', ['position' => yii\web\View::POS_END ]);?>
......
...@@ -38,6 +38,10 @@ FileUploadBundle::register($this); ...@@ -38,6 +38,10 @@ FileUploadBundle::register($this);
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Ваша заявка на проект успешно отправлена!</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -75,9 +79,6 @@ FileUploadBundle::register($this); ...@@ -75,9 +79,6 @@ FileUploadBundle::register($this);
<div class="file_upload_bt"> <div class="file_upload_bt">
<div class="file-upload"> <div class="file-upload">
<label> <label>
<?php/* echo $form->field($model, 'file', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>'
])->fileInput();*/ ?>
<span>Выбрать файл</span> <span>Выбрать файл</span>
</label> </label>
</div> </div>
...@@ -85,9 +86,13 @@ FileUploadBundle::register($this); ...@@ -85,9 +86,13 @@ FileUploadBundle::register($this);
<div class="file_drop">Перетащите файл в данную область<br/> или выберите файл с компьютера</div> <div class="file_drop">Перетащите файл в данную область<br/> или выберите файл с компьютера</div>
</div> </div>
</div> </div>
<input type="hidden" name="file_name" id='file_name' value=""/> <div id="files-zone">
</div>
<?php echo Html::submitButton('Рассчитать проект', ['class' => 'btn-default save-button']); ?> <?php echo Html::submitButton('Рассчитать проект', ['class' => 'btn-default save-button']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
</div> </div>
......
...@@ -66,7 +66,7 @@ FileUploadBundle::register($this); ...@@ -66,7 +66,7 @@ FileUploadBundle::register($this);
</div> </div>
<div class="col-md-5 col-xs-6 col-sm 12"> <div class="col-md-5 col-xs-6 col-sm 12">
<div class="support_block"> <div class="support_block">
<div class="support_block__txt">Для вашего удобства мы подготовили видео в котором рассказывается как правильно ставить задачу в отдел технической поддержки.</div> <div class="support_block__txt">Для вашего удобства мы подготовили видео, в котором рассказывается, как правильно ставить задачу в отдел технической поддержки.</div>
<div class="support_block__link_pv"><a href="#" class="">Смотреть видео</a></div> <div class="support_block__link_pv"><a href="#" class="">Смотреть видео</a></div>
</div> </div>
</div> </div>
...@@ -100,6 +100,10 @@ FileUploadBundle::register($this); ...@@ -100,6 +100,10 @@ FileUploadBundle::register($this);
], ],
]); ?> ]); ?>
<div class="message-box send_secce">Ваша заявка отправлена, мы вам перезвоним.</div>
<div class="content">
<?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?> <?php echo Html::hiddenInput('scenario', $model->scenario, ['class' => 'not_clear']); ?>
<?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?> <?php echo $form->field($model, 'form', ['template' => '{input}'])->hiddenInput(['class' => 'not_clear']); ?>
...@@ -129,20 +133,20 @@ FileUploadBundle::register($this); ...@@ -129,20 +133,20 @@ FileUploadBundle::register($this);
<div class="file_upload_bt_cs"> <div class="file_upload_bt_cs">
<div class="file-upload_cs"> <div class="file-upload_cs">
<label> <label>
<?php /*echo $form->field($model, 'file', [
'template' => '<div class="row"><div class="col-sm-4">{input}</div></div>'
])->fileInput(); */?>
<span>Выбрать файл</span> <span>Выбрать файл</span>
</label> </label>
</div> </div>
<!--<input type="text" id="filename" class="filename_cs" disabled>-->
<div class="file_drop_cs">Перетащите файл в данную область<br/> или выберите файл с компьютера</div> <div class="file_drop_cs">Перетащите файл в данную область<br/> или выберите файл с компьютера</div>
</div> </div>
</div> </div>
<input type="hidden" name="file_name" id='file_name' value=""/> <div id="files-zone">
</div>
<?php echo Html::submitButton('Отправить', ['class' => 'btn-default save-button']); ?> <?php echo Html::submitButton('Отправить', ['class' => 'btn-default save-button']); ?>
</div>
<?php ActiveForm::end(); ?> <?php ActiveForm::end(); ?>
</div> </div>
</div> </div>
......
...@@ -5,7 +5,8 @@ ...@@ -5,7 +5,8 @@
.field-bid-file { .field-bid-file {
margin: 0; margin: 0;
} }
.has-error input { .has-error input,
.has-error textarea {
background: #fff url(../images/icon-fail.png) no-repeat 96% center !important; background: #fff url(../images/icon-fail.png) no-repeat 96% center !important;
border: 1px solid #E9A2A2 !important; border: 1px solid #E9A2A2 !important;
} }
...@@ -47,6 +48,13 @@ section .container ol:not([class]) li { ...@@ -47,6 +48,13 @@ section .container ol:not([class]) li {
section.reviews-block .row { section.reviews-block .row {
margin-bottom: 50px; margin-bottom: 50px;
} }
.input_bg {
padding: 6px 10px 13px;
line-height: 18px;
}
.input_bg label {
padding: 6px 0px 0px 35px !important;
}
a.login_form_link, a.login_form_popup_link, a.reg_popup_link, a.reg_form_link{ a.login_form_link, a.login_form_popup_link, a.reg_popup_link, a.reg_form_link{
margin-top: 20px; margin-top: 20px;
display: block; display: block;
...@@ -159,6 +167,11 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow ...@@ -159,6 +167,11 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow
.video_sec a.toggle_bottom { .video_sec a.toggle_bottom {
margin-top: 153px; margin-top: 153px;
} }
.top_keys_soc a.toggle_bottom {
position: relative;
top: 128px;
margin-top: 0;
}
.bx-wrapper .bx-prev { .bx-wrapper .bx-prev {
background: #344555 url(../images/arrow_left.png) no-repeat center center; background: #344555 url(../images/arrow_left.png) no-repeat center center;
} }
...@@ -181,7 +194,37 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow ...@@ -181,7 +194,37 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow
margin: 0 auto; margin: 0 auto;
display: none; display: none;
} }
.article_short_txt img {
margin-top: 0;
}
.article_short_tags {
margin-bottom: 14px;
}
.bids-form .message-box {
position: absolute;
z-index: 110;
text-align: center;
width: 480px;
left: 50%;
top: 50%;
margin: -11px 0 0 -240px;
display: none;
line-height: 30px;
}
.bids-form .message-box.callback {
width: 300px;
margin-left: -150px;
margin-top: 20px;
}
.subsc_blog_form {
position: relative;
}
.testing_img_block img {
width: 100%;
}
.testing_img_block {
height: auto;
}
/* ------------ BLOG MODAL ------------------ */ /* ------------ BLOG MODAL ------------------ */
...@@ -404,6 +447,10 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow ...@@ -404,6 +447,10 @@ a.toggle_bottom:hover .icon-arrowDown2:after, a.toggle_bottom:active .icon-arrow
float: none; float: none;
margin: 20px auto 40px; margin: 20px auto 40px;
} }
.top_keys_soc a.toggle_bottom {
top: 0px;
margin: 30px auto;
}
} }
@media only screen and (max-width: 479px) and (min-width: 320px) { @media only screen and (max-width: 479px) and (min-width: 320px) {
......
...@@ -32,10 +32,25 @@ $('form.bids-form').on('beforeSubmit', function(e) { ...@@ -32,10 +32,25 @@ $('form.bids-form').on('beforeSubmit', function(e) {
var response = xhr.responseText; var response = xhr.responseText;
} }
form.find('.has-error').removeClass('has-error');
if(response.success) if(response.success)
{ {
if(form.find('.message-box').length > 0)
{
form.find('.message-box').fadeIn('fast');
form.find('.content').css('visibility','hidden');
setTimeout(function(){
form.find('.message-box').fadeOut('fast');
form.find('.content').css('visibility','visible');
}, 2000);
}
form.find('input:not(.not_clear), textarea').val(''); form.find('input:not(.not_clear), textarea').val('');
$('.send_secce').show();
form.find('#files-zone').html('');
$('.dz-preview.dz-processing').remove();
dataLayer.push({ dataLayer.push({
'event': 'UA_event', 'event': 'UA_event',
...@@ -43,8 +58,6 @@ $('form.bids-form').on('beforeSubmit', function(e) { ...@@ -43,8 +58,6 @@ $('form.bids-form').on('beforeSubmit', function(e) {
'Action': form.data('title'), 'Action': form.data('title'),
'Label': 'Успешно' 'Label': 'Успешно'
}); });
form.find('.has-error').removeClass('has-error');
} }
else else
{ {
......
...@@ -53,4 +53,22 @@ $(document).ready(function() { ...@@ -53,4 +53,22 @@ $(document).ready(function() {
}, 1000 * 60 * 5); }, 1000 * 60 * 5);
$('form#error-testing-form').on('beforeSubmit', function(e) {
$.ajax({
url: $('form#error-testing-form').attr('action'),
method: 'POST',
dataType: 'json',
data: {
message: $('[name="message"]').val()
},
success: function(response){
if(response.success)
{
$(".error_fedback").html('<div class="row"><div class="col-sm-8" style="margin:0 auto;float:none;"><div class="gray_box"><p>' + response.message + '</p></div></div></div>');
}
}
});
}).on('submit', function(e){
return false;
});
}); });
\ No newline at end of file
This diff is collapsed.
...@@ -6,15 +6,16 @@ $(document).ready(function() { ...@@ -6,15 +6,16 @@ $(document).ready(function() {
// var myDropzone = new Dropzone("div#block_upload", {url: "/bids/bid/upload-files", maxFiles: 1}); // var myDropzone = new Dropzone("div#block_upload", {url: "/bids/bid/upload-files", maxFiles: 1});
Dropzone.options.blockUpload = { Dropzone.options.blockUpload = {
url: "/bids/bid/upload-files", url: "/bids/bid/upload-files",
maxFiles: 1, maxFiles: 4,
addRemoveLinks: true, addRemoveLinks: true,
dictRemoveFile: 'Удалить', dictRemoveFile: 'Удалить',
/*accept: function(file, done) { /*accept: function(file, done) {
$('#file_name').val(file.name); $('#file_name').val(file.name);
done(); done();
},*/ },*/
success: function(first,response) { success: function(first, response)
$('#file_name').val(response); {
$('#files-zone').append('<input type="hidden" name="Bid[file][]" value="'+response.filename+'" />');
$('.file_drop').hide(); $('.file_drop').hide();
$('.file_drop_cs').hide(); $('.file_drop_cs').hide();
} }
......
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