Commit e7d96745 authored by Друппов Андрей's avatar Друппов Андрей

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

parents fee10ae1 057adeea
......@@ -37,16 +37,10 @@ class SiteController extends Controller
];
}
/**
* @inheritdoc
*/
public function actions()
public function actionError()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
];
$this->layout = "clear";
return $this->render('error');
}
public function actionLogin()
......
<?php
use yii\helpers\Html;
use backend\assets\AppAsset;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<!--[if IE 8]> <html lang="en" class="ie8"> <![endif]-->
<!--[if !IE]><!-->
<html lang="ru">
<!--<![endif]-->
<head>
<meta charset="utf-8" />
<title>Произошла какая-то ошибка</title>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport" />
<?= Html::csrfMetaTags() ?>
<?php $this->head() ?>
<?php echo $this->render('head')?>
</head>
<body>
<?php $this->beginBody() ?>
<?=$content?>
<?php $this->endBody() ?>
<?php echo $this->render('foot')?>
</body>
</html>
<?php $this->endPage() ?>
\ No newline at end of file
<?php
use yii\helpers\Html;
use common\models\Settings;
/* @var $this yii\web\View */
/* @var $name string */
/* @var $message string */
/* @var $exception Exception */
$this->title = $name;
?>
<div class="site-error">
<!-- begin #page-loader -->
<div id="page-loader" class="fade in"><span class="spinner"></span></div>
<!-- end #page-loader -->
<h1><?= Html::encode($this->title) ?></h1>
<div class="alert alert-danger">
<?= nl2br(Html::encode($message)) ?>
<!-- begin #page-container -->
<div id="page-container" class="fade">
<!-- begin error -->
<div class="error">
<div class="error-code m-b-10">404 <i class="fa fa-warning"></i></div>
<div class="error-content">
<div class="error-message">Произошла какая-то ошибка</div>
<div class="error-desc m-b-20">
Страница не существует или у вас нет прав для ее просмотра.<br />
Проверьте введенный URL-адрес страницы или обратитесь в Службу технической поддержки для решения данного вопроса
<?=Html::a(Settings::getValue('content-support-email'), 'mailto:'.Settings::getValue('content-support-email'))?>
</div>
<div>
<a href="/" class="btn btn-success">Вернуться на главную страницу</a>
</div>
</div>
</div>
<p>
The above error occurred while the Web server was processing your request.
</p>
<p>
Please contact us if you think this is a server error. Thank you.
</p>
<!-- end error -->
</div>
<!-- end page container -->
<?php
namespace common\components;
use common\modules\triggers\models\TriggerLogs;
use common\modules\triggers\components\conditions\conditions\CheckPresenceTime;
use common\modules\triggers\components\conditions\conditions\CheckScrolling;
use Yii;
......@@ -63,8 +64,9 @@ abstract class BaseController extends Controller
public function beforeAction($action)
{
CheckPresenceTime::init()->initScript();
CheckScrolling::init()->initScript();
TriggerLogs::logAction();
// CheckPresenceTime::init()->initScript();
// CheckScrolling::init()->initScript();
/*if(substr($currentUrl, -1) == '/' && $currentUrl!="/") {
$urlWithoutSlash = substr($currentUrl, 0, -1);
return $this->redirect($urlWithoutSlash,true,301);
......
<?php
namespace common\components;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
abstract class FrontendController extends Controller
{
public $layout = '//main';
public $page_title;
public $page_description;
public $meta_title;
public $meta_description;
public $meta_keywords;
public $crumbs = array();
public $breadcrumbs = array();
public function init()
{
parent::init();
$this->_initSession();
}
private function _initSession()
{
$request = Yii::$app->request;
if($request->isGet && !$request->isAjax)
{
Yii::$app->session->set('SessionData', [$request->url, $request->referrer]);
}
}
}
......@@ -189,8 +189,20 @@ class UnisenderAPI {
public function linkIsVisited($email, $link) {
if (array_key_exists('result', $this->visitedLinks) && array_key_exists('data', $this->visitedLinks['result'])) {
foreach($this->visitedLinks['result']['data'] as $transition) {
if (strtolower($transition[0])==strtolower($email) && strpos($link, $transition[1])!==false)
return true;
// if (strtolower($transition[0])==strtolower($email) && strpos($link, $transition[1])!==false)
// return true;
if (strtolower($transition[0])==strtolower($email)) {
if (strlen($link)>strlen($transition[1])) {
if (strpos($link, $transition[1])!==false)
return true;
} elseif (strlen($link)>strlen($transition[1])) {
if (strpos($transition[1], $link)!==false)
return true;
} else {
if (strpos($link, $transition[1])!==false)
return true;
}
}
}
}
return false;
......
......@@ -138,7 +138,7 @@ class PostController extends BaseController
{
try
{
$email = 'Levshin@kupitsite.ru';
$email = Settings::getValue('article-email');
$message = $this->renderPartial('_mail', [
'model' => $model
......
......@@ -2,6 +2,7 @@
namespace common\modules\content\controllers;
use common\modules\users\models\User;
use Yii;
use yii\web\BadRequestHttpException;
use common\modules\content\models\CoContent;
......@@ -20,7 +21,7 @@ class PageController extends \common\components\BaseController
return $this->render('index');
}
public function actionView($id = null, $page = null)
public function actionView($id = null, $page = null, $hash=null, $email=null)
{
if(empty($id) && empty($page)) {
// if(!\Yii::$app->user->isGuest)
......@@ -35,13 +36,25 @@ class PageController extends \common\components\BaseController
{
$model = CoContent::findOne(['url' => $page]);
}
if (!empty($email) && !empty($hash)) {
/** @var User $user */
$user = User::find()->where(['email' => $email])->one();
if (!is_null($user)) {
if ($user->checkToAutoAuthByHash($hash)===true)
$user->authUser();
}
}
$content = $model->lang->getFinishedContent();
$this->meta_title = $model->metaTag->title;
$this->meta_description = $model->metaTag->description;
$this->meta_keywords = $model->metaTag->keywords;
return $this->render('view', ['content'=>$content]);
return $this->render('view', [
'content' => $content,
'model' => $model
]);
}
}
......@@ -32,6 +32,9 @@ class CoContent extends \common\components\ActiveRecordModel
const CUSTOM_DARK = 'dark';
const CUSTOM_WHITE = 'white';
const TYPE_SIMPLE = 0;
const TYPE_LANDING = 1;
public $copyLangs;
public static $cutom_list = [
......@@ -39,6 +42,11 @@ class CoContent extends \common\components\ActiveRecordModel
self::CUSTOM_WHITE => 'Светлый',
];
public static $type_titles = [
self::TYPE_SIMPLE => 'Простой',
self::TYPE_LANDING => 'Лендинг',
];
/**
* @inheritdoc
*/
......@@ -107,9 +115,9 @@ class CoContent extends \common\components\ActiveRecordModel
public function rules()
{
return [
[['active'], 'integer'],
[['active', 'type'], 'integer'],
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg, jpeg, gif'],
[['url'], 'required'],
[['url', 'type'], 'required'],
[['url'], 'string', 'max' => 250],
[['category_id', 'priority', 'custom'], 'safe'],
[['priority'], 'double']
......@@ -123,6 +131,7 @@ class CoContent extends \common\components\ActiveRecordModel
{
return [
'id' => Yii::t('content', 'ID'),
'type' => 'Тип страницы',
'category_id' => Yii::t('content', 'Category ID'),
'url' => Yii::t('content', 'Url'),
'name' => Yii::t('content', 'Name'),
......@@ -184,4 +193,17 @@ class CoContent extends \common\components\ActiveRecordModel
{
return $this->hasMany(CoContentLang::className(), ['content_id' => 'id']);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if ($this->category_id==4) { // <<< С этим надо что то делать, очень много привязок динамичных данных
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, Yii::$app->urlManager->createAbsoluteUrl('/triggers/default/recheckcases'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if (!curl_exec($curl)) {
echo curl_error($curl);
}
}
}
}
......@@ -45,6 +45,10 @@ $blocks = \common\modules\content\models\CoBlocks::find()->all();
'class' => 'form-control',
]) ?>
<?= $form->field($model, 'type')->dropDownList(CoContent::$type_titles, [
'class' => 'form-control',
]) ?>
<?php if($model->preview)
{
echo Html::img(\Yii::$app->params['frontUrl'] . $model->preview);
......
<?php
/* @var $this yii\web\View */
echo $content;
<?php
use common\modules\content\models\CoContent;
?>
<?php if($model->type == CoContent::TYPE_SIMPLE) : ?>
<section class="simple-section <?=($model->custom==CoContent::CUSTOM_DARK?'dark':'')?>">
<div class="container">
<?php endif; ?>
<?=$content;?>
<?php if($model->type == CoContent::TYPE_SIMPLE) : ?>
</div>
</section>
<?=$this->render('@app/views/layouts/footer')?>
<?php endif; ?>
\ No newline at end of file
......@@ -35,21 +35,22 @@ return [
'items' => ['active' => 'Активен', 'hidden' => 'Скрыт'],
'class' => 'form-control'
],
'rate_usability' => [
'type' => 'dropdownlist',
'items' => Reviews::getSource('rate_usability'),
'class' => 'form-control'
],
'rate_loyality' => [
'type' => 'dropdownlist',
'items' => Reviews::getSource('rate_loyality'),
'class' => 'form-control'
],
'rate_profit' => [
'type' => 'dropdownlist',
'items' => Reviews::getSource('rate_profit'),
'class' => 'form-control'
],
'priority' => ['type' => 'text', 'class' => 'form-control'],
// 'rate_usability' => [
// 'type' => 'dropdownlist',
// 'items' => Reviews::getSource('rate_usability'),
// 'class' => 'form-control'
// ],
// 'rate_loyality' => [
// 'type' => 'dropdownlist',
// 'items' => Reviews::getSource('rate_loyality'),
// 'class' => 'form-control'
// ],
// 'rate_profit' => [
// 'type' => 'dropdownlist',
// 'items' => Reviews::getSource('rate_profit'),
// 'class' => 'form-control'
// ],
],
'buttons' => [
'submit' => ['type' => 'submit', 'value' => 'Cохранить']
......
......@@ -3,6 +3,7 @@
namespace common\modules\reviews\models;
use Yii;
use yii\behaviors\TimestampBehavior;
/**
* This is the model class for table "reviews".
......@@ -90,6 +91,12 @@ class Reviews extends \common\components\ActiveRecordModel
'folder' => '/uploads/reviews/',
'field' => 'photo'
],
'timestamp' => [
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => time(),
],
];
}
......@@ -132,7 +139,7 @@ class Reviews extends \common\components\ActiveRecordModel
'state' => Yii::t('reviews', 'Состояние'),
'date' => Yii::t('reviews', 'Дата'),
'date_create' => Yii::t('reviews', 'Создана'),
'priority' => Yii::t('reviews', 'Priority'),
'priority' => Yii::t('reviews', 'Приоритет'),
'email' => Yii::t('reviews', 'Email'),
'notification_date' => Yii::t('reviews', 'Notification Date'),
'notification_send' => Yii::t('reviews', 'Notification Send'),
......
......@@ -2,14 +2,16 @@
namespace common\modules\school\controllers;
use common\components\BaseController;
use yii\filters\AccessControl;
use common\components\FrontendController;
use common\modules\school\models\Courses;
use common\modules\school\models\SearchCourses;
use common\modules\school\models\SearchLessons;
use common\modules\users\models\User;
use common\models\LoginForm;
class CourseController extends BaseController
class CourseController extends FrontendController
{
public static function actionsTitles()
{
......@@ -18,6 +20,24 @@ class CourseController extends BaseController
'View' => 'Курс',
];
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user' => 'support',
'only' => ['view', 'index'],
'rules' => [
[
'allow' => true,
'actions' => ['view', 'index'],
'roles' => ['?'],
],
],
],
];
}
public function actionIndex()
{
......
......@@ -3,14 +3,14 @@
namespace common\modules\school\controllers;
use Yii;
use yii\filters\AccessControl;
use common\components\BaseController;
use common\components\FrontendController;
use common\modules\school\models\Lessons;
use common\modules\school\models\LessonImage;
use common\modules\testings\models\Passing;
class LessonController extends BaseController
class LessonController extends FrontendController
{
public static function actionsTitles()
{
......@@ -19,6 +19,29 @@ class LessonController extends BaseController
'Download-documents' => 'Скачивание документа',
];
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user' => 'support',
'only' => ['view', 'download-documents'],
'rules' => [
[
'allow' => true,
'actions' => ['view'],
'roles' => ['?'],
],
[
'allow' => true,
'actions' => ['download-documents'],
'roles' => ['@'],
],
],
],
];
}
public function actionView($id)
{
......@@ -61,12 +84,12 @@ class LessonController extends BaseController
}
}
function cookie($name,$value=null,$expire=null){
$options['name'] = $name;
$options['value'] = $value;
$options['expire'] = time()+86400*365;
$cookie = new \yii\web\Cookie($options);
\Yii::$app->response->cookies->add($cookie);
}
function cookie($name,$value=null,$expire=null)
{
$options['name'] = $name;
$options['value'] = $value;
$options['expire'] = time()+86400*365;
$cookie = new \yii\web\Cookie($options);
\Yii::$app->response->cookies->add($cookie);
}
}
......@@ -113,59 +113,7 @@ WidgetAssetBundle::register($this);
</section>
<?php endif;*/?>
<div class="tr_foot"></div>
<footer>
<div class="container">
<div class="row">
<div class="col-md-4 col-xs-4 col-sm-12">
<a href="mailto:info@task-on.com" class="foot_mail">info@task-on.com</a>
</div>
<div class="col-md-4 col-xs-4 col-sm-12"><a href="#zvonok_form" class="zvonok_bt popup-form"><span>Заказать звонок</span></a></div>
<div class="col-md-4 col-xs-4 col-sm-12">
<!--<div class="phone_hover_foot">Стоимость звонка 0 руб,<br> в том числе с мобильного</div>-->
<span class="foot_phone">8-495-749-29-69</span>
</div>
</div>
<div class="footbottom_line">
<div class="row">
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="foot_logo">
<img src="/images/foot_logo.png" height="51" width="192" alt="">
</div>
</div>
<div class="col-md-6 col-xs-6 col-sm-12">
<ul class="social_link">
<li><a href="#" class="soc_item"><i class="fa fa-vk"></i></a></li>
<li><a href="#" class="soc_item"><i class="fbicon"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-youtube"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-instagram"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-twitter"></i></a></li>
<li><a href="#" class="soc_item"><i class="gplusicon"></i></a></li>
</ul>
</div>
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="taskon"><img src="/images/taskon.png" height="31" width="100" alt=""></div>
<div class="copyring">Powered by Taskon <br> Собственная разработка Арт Проект</div>
</div>
</div>
</div>
</div>
</footer>
<div class="hidden">
<div id="zvonok_form" class="popup">
<!-- <div class="txtbtnclose">Закрыть</div> -->
<span class="popup__title">Заказать звонок</span>
<span class="popup__subtittle">Чтобы мы могли вам перезвонить укажите свой номер телефона:</span>
<form class="valid_form">
<input type="text" class="input_st field-input required alphanumeric" placeholder="Ваше имя">
<input type="tel" class="input_st field-input required email" placeholder="Ваш телефон">
<button class="save-button popup_bt_send">Заказать звонок</button>
</form>
</div>
<?php echo \common\modules\users\widgets\LoginWidget::widget(); ?>
<?php echo \common\modules\users\widgets\RegistrationWidget::widget(); ?>
</div>
<?php echo $this->render('@app/views/layouts/footer'); ?>
......@@ -5,22 +5,9 @@
WidgetAssetBundle::register($this);
?>
<section class="ks_header">
<div class="container">
<div class="row">
<div class="col-md-5 col-xs-7 col-sm-12">
<div class="ball-block">Накоплено баллов:
<span class="col-ball">0</span>
<a href="#" class="ball-link">Как увеличить?</a>
<div class="ball_hover">Текст как увеличить,<br> текст как увеличить,</div>
</div>
</div>
<div class="col-md-5 col-md-offset-2 col-xs-5 col-sm-12">
<?php echo \common\modules\users\widgets\UserBoxWidget::widget() ?>
</div>
</div>
</div>
</section>
<?=$this->render('@frontend/views/layouts/header-school-auth')?>
<section class="les_list_top" style="background: url(<?php echo $model->getUrl($model->image);?>) no-repeat center center; background-size: 100% auto;">
<div class="ls_top_over">
<div class="container">
......@@ -76,46 +63,5 @@
<?php endif;?>
</div>
</section>
<footer>
<div class="container">
<div class="footbottom_line">
<div class="row">
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="foot_logo">
<img src="/images/foot_logo.png" height="51" width="192" alt="">
</div>
</div>
<div class="col-md-6 col-xs-6 col-sm-12">
<ul class="social_link">
<li><a href="#" class="soc_item"><i class="fa fa-vk"></i></a></li>
<li><a href="#" class="soc_item"><i class="fbicon"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-youtube"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-instagram"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-twitter"></i></a></li>
<li><a href="#" class="soc_item"><i class="gplusicon"></i></a></li>
</ul>
</div>
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="taskon"><img src="/images/taskon.png" height="31" width="100" alt=""></div>
<div class="copyring">Powered by Taskon <br> Собственная разработка Арт Проект</div>
</div>
</div>
</div>
</div>
</footer>
<div class="hidden">
<div id="zvonok_form" class="popup">
<!-- <div class="txtbtnclose">Закрыть</div> -->
<span class="popup__title">Заказать звонок</span>
<span class="popup__subtittle">Чтобы мы могли вам перезвонить укажите свой номер телефона:</span>
<form class="valid_form">
<input type="text" class="input_st field-input required alphanumeric" placeholder="Ваше имя">
<input type="tel" class="input_st field-input required email" placeholder="Ваш телефон">
<button class="save-button popup_bt_send">Заказать звонок</button>
</form>
</div>
<?php echo \common\modules\users\widgets\LoginWidget::widget(); ?>
<?php echo \common\modules\users\widgets\RegistrationWidget::widget(); ?>
</div>
<?php echo $this->render('@app/views/layouts/footer-short'); ?>
\ No newline at end of file
......@@ -8,22 +8,9 @@ use common\modules\testings\models\Passing;
WidgetAssetBundle::register($this);
?>
<section class="ks_header">
<div class="container">
<div class="row">
<div class="col-md-5 col-xs-7 col-sm-12">
<div class="ball-block">Накоплено баллов:
<span class="col-ball">0</span>
<a href="#" class="ball-link">Как увеличить?</a>
<div class="ball_hover">Текст как увеличить,<br> текст как увеличить,</div>
</div>
</div>
<div class="col-md-5 col-md-offset-2 col-xs-5 col-sm-12">
<?php echo UserBoxWidget::widget() ?>
</div>
</div>
</div>
</section>
<?=$this->render('@frontend/views/layouts/header-school-auth')?>
<section class="video-container">
<div class="container">
<div class="row">
......@@ -84,7 +71,7 @@ WidgetAssetBundle::register($this);
<section class="vc-cont">
<div class="container">
<?php if($model->test) : ?>
<?php if($model->test && !Yii::$app->user->isGuest) : ?>
<?php if(!$passing) : ?>
......@@ -206,46 +193,5 @@ WidgetAssetBundle::register($this);
</div>
</div>
</section>
<footer>
<div class="container">
<div class="footbottom_line">
<div class="row">
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="foot_logo">
<img src="/images/foot_logo.png" height="51" width="192" alt="">
</div>
</div>
<div class="col-md-6 col-xs-6 col-sm-12">
<ul class="social_link">
<li><a href="#" class="soc_item"><i class="fa fa-vk"></i></a></li>
<li><a href="#" class="soc_item"><i class="fbicon"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-youtube"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-instagram"></i></a></li>
<li><a href="#" class="soc_item"><i class="fa fa-twitter"></i></a></li>
<li><a href="#" class="soc_item"><i class="gplusicon"></i></a></li>
</ul>
</div>
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="taskon"><img src="/images/taskon.png" height="31" width="100" alt=""></div>
<div class="copyring">Powered by Taskon <br> Собственная разработка Арт Проект</div>
</div>
</div>
</div>
</div>
</footer>
<div class="hidden">
<div id="zvonok_form" class="popup">
<!-- <div class="txtbtnclose">Закрыть</div> -->
<span class="popup__title">Заказать звонок</span>
<span class="popup__subtittle">Чтобы мы могли вам перезвонить укажите свой номер телефона:</span>
<form class="valid_form">
<input type="text" class="input_st field-input required alphanumeric" placeholder="Ваше имя">
<input type="tel" class="input_st field-input required email" placeholder="Ваш телефон">
<button class="save-button popup_bt_send">Заказать звонок</button>
</form>
</div>
<?php echo \common\modules\users\widgets\LoginWidget::widget(); ?>
<?php echo \common\modules\users\widgets\RegistrationWidget::widget(); ?>
</div>
<?php echo $this->render('@app/views/layouts/footer-short'); ?>
\ No newline at end of file
......@@ -4,21 +4,16 @@ namespace common\modules\support\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use common\components\FrontendController;
use common\modules\support\models\LoginForm;
use common\modules\users\models\User;
/**
* Default controller for the `support` module
*/
class DefaultController extends Controller
class DefaultController extends FrontendController
{
public $meta_title;
public $meta_description;
public $meta_keywords;
public $page_title;
public function behaviors()
{
return [
......
......@@ -6,10 +6,10 @@ use Yii;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use common\components\FrontendController;
use common\models\Settings;
use common\modules\support\models\redmine\Issue;
use common\modules\support\models\redmine\RedmineHelper;
......@@ -17,23 +17,19 @@ use common\modules\support\models\redmine\RedmineHelper;
/**
* Default controller for the `support` module
*/
class SupportController extends Controller
{
public $meta_title;
public $meta_description;
public $meta_keywords;
class SupportController extends FrontendController
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user' => 'support',
'only' => ['index', 'create', 'view', 'file'],
'only' => ['index', 'create', 'view', 'file', 'close'],
'rules' => [
[
'allow' => true,
'actions' => ['index', 'create', 'view', 'file'],
'actions' => ['index', 'create', 'view', 'file', 'close'],
'roles' => ['@'],
],
],
......@@ -72,6 +68,7 @@ class SupportController extends Controller
$this->view->registerJsFile('/js/support.js', ['position' => yii\web\View::POS_END ]);
$model = new Issue();
$model->setScenario(Issue::SCENARIO_CREATE);
$client = $this->getClient();
......@@ -86,9 +83,34 @@ class SupportController extends Controller
'priority_id' => $model->priority_id,
'status_id' => $model->status_id,
'tracker_id' => $model->tracker_id,
'author_id' => $user['user']['id']
'author_id' => $user['user']['id'],
'assigned_to_manager_id' => null
];
$membership = $client->membership->all($model->project_id);
if(isset($membership))
{
foreach ($membership as $member)
{
if(isset($member['roles']))
{
foreach ($member['roles'] as $role)
{
if($role['id'] == RedmineHelper::MANAGER)
{
$params['assigned_to_manager_id'] = $member['user']['id'];
}
}
}
if($params['assigned_to_manager_id'])
{
break;
}
}
}
if($model->files)
{
$uploads = [];
......@@ -118,6 +140,88 @@ class SupportController extends Controller
]);
}
public function actionView($id)
{
$this->view->registerJsFile('/js/support.js', ['position' => yii\web\View::POS_END ]);
$client = $this->getClient();
$user = $client->user->getCurrentUser();
$model = $client->issue->show($id, [
'include' => [
'attachments',
'journals'
]
]);
if(empty($model['issue']) || $model['issue']['author']['id'] != $user['user']['id'])
{
throw new NotFoundHttpException('Доступ запрещен!');
}
$issue = new Issue();
$issue->setScenario(Issue::SCENARIO_UPDATE);
if ($issue->load(Yii::$app->request->post()) && $issue->validate())
{
$params = [
'notes' => $issue->notes,
];
if($issue->files)
{
$uploads = [];
foreach ($issue->files as $file)
{
$uploads[] = [
'token' => $file['token'],
'filename' => $file['filename'],
'content_type' => $file['type'],
];
}
$params = ArrayHelper::merge($params, [
'uploads' => $uploads
]);
}
$client->issue->update($id, $params);
return $this->refresh();
}
return $this->render('view', [
'model' => $model['issue'],
'issue' => $issue
]);
}
public function actionClose($id)
{
$client = $this->getClient();
$user = $client->user->getCurrentUser();
$model = $client->issue->show($id);
if(empty($model['issue']) || $model['issue']['author']['id'] != $user['user']['id'])
{
throw new NotFoundHttpException('Доступ запрещен!');
}
if($model['issue']['status']['id'] == Issue::STATUS_APPROVE)
{
$client->issue->update($id, [
'status_id' => Issue::STATUS_ACCEPTED
]);
}
return $this->redirect(['/support/view/'.$id]);
}
public function actionFile()
{
if(Yii::$app->request->isAjax)
......@@ -169,29 +273,6 @@ class SupportController extends Controller
}
}
public function actionView($id)
{
$client = $this->getClient();
$user = $client->user->getCurrentUser();
$model = $client->issue->show($id, [
'include' => [
'attachments',
'journals'
]
]);
if(empty($model['issue']) || $model['issue']['author']['id'] != $user['user']['id'])
{
throw new NotFoundHttpException('Доступ запрещен!');
}
return $this->render('view', [
'model' => $model['issue'],
]);
}
protected function getClient()
{
return $client = new \Redmine\Client(Settings::getValue('redmine-url'), Yii::$app->support->identity->redmine_key);
......
......@@ -13,6 +13,7 @@ class Issue extends yii\base\Model
public $author_id;
public $tracker_id = self::TRACKER_NONE;
public $status_id = self::STATUS_NEW;
public $notes;
public $files = null;
......@@ -22,6 +23,11 @@ class Issue extends yii\base\Model
const TRACKER_NONE = 14; // Не определено
const STATUS_NEW = 7;
const STATUS_APPROVE = 16;
const STATUS_ACCEPTED = 14;
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
/**
* @inheritdoc
......@@ -29,16 +35,17 @@ class Issue extends yii\base\Model
public function rules()
{
return [
[['tracker_id', 'status_id', 'priority_id'], 'required'],
[['notes'], 'required', 'on' => self::SCENARIO_UPDATE],
[['project_id'], 'required', 'message' => 'Выберите проект, к которому относится новая задача'],
[['subject'], 'required', 'message' => 'Введите наименование задачи'],
[['description'], 'required', 'message' => 'Укажите описание задачи'],
[['tracker_id', 'status_id', 'priority_id'], 'required', 'on' => self::SCENARIO_CREATE],
[['project_id'], 'required', 'message' => 'Выберите проект, к которому относится новая задача', 'on' => self::SCENARIO_CREATE],
[['subject'], 'required', 'message' => 'Введите наименование задачи', 'on' => self::SCENARIO_CREATE],
[['description'], 'required', 'message' => 'Укажите описание задачи', 'on' => self::SCENARIO_CREATE],
[['tracker_id', 'project_id', 'status_id', 'priority_id'], 'integer', 'on' => self::SCENARIO_CREATE],
[['description'], 'string', 'on' => self::SCENARIO_CREATE],
[['subject'], 'string', 'max' => 255, 'on' => self::SCENARIO_CREATE],
[['tracker_id', 'project_id', 'status_id', 'priority_id'], 'integer'],
[['description'], 'string'],
[['files'], 'safe'],
[['subject'], 'string', 'max' => 255],
[['files', 'notes'], 'safe'],
];
}
......@@ -55,6 +62,7 @@ class Issue extends yii\base\Model
'description' => 'Текст задачи',
'priority_id' => 'Важность',
'status_id' => 'Статус',
'notes' => 'Комментарий',
];
}
......
......@@ -8,6 +8,87 @@ class RedmineHelper
{
const MAX_FILE_SIZE = 5242880; //5mb
const OTHER_PROJECT = 75;
const MANAGER = 3;
public static $markupSet = [
[
'name' => 'Жирный',
'className' => 'fa fa-bold',
'openWith' => '*',
'closeWith' => '*'
],
[
'name' => 'Курсив',
'className' => 'fa fa-italic',
'openWith' => '_',
'closeWith' => '_'
],
[
'name' => 'Подчеркнутый',
'className' => 'fa fa-underline',
'openWith' => '+',
'closeWith' => '+'
],
[
'name' => 'Зачеркнутый',
'className' => 'fa fa-strikethrough',
'openWith' => '-',
'closeWith' => '-'
],
['separator' => '---------------'],
[
'name' => 'Заголовок 1',
'className' => 'fa fa-header header-1',
'openWith' => 'h1. ',
'closeWith' => ''
],
[
'name' => 'Заголовок 2',
'className' => 'fa fa-header header-2',
'openWith' => 'h2. ',
'closeWith' => ''
],
[
'name' => 'Заголовок 3',
'className' => 'fa fa-header header-3',
'openWith' => 'h3. ',
'closeWith' => ''
],
['separator' => '---------------'],
[
'name' => 'Маркированный список',
'className' => 'fa fa-list-ul',
'openWith' => '* ',
'multiline' => true,
'openBlockWith' => "",
'closeBlockWith' => ""
],
[
'name' => 'Нумерованный список',
'className' => 'fa fa-list-ol',
'openWith' => '# ',
'multiline' => true,
'openBlockWith' => "",
'closeBlockWith' => ""
],
['separator' => '---------------'],
[
'name' => 'Заранее форматированный тест',
'className' => 'fa fa-newspaper-o',
'openWith' => '<pre>',
'closeWith' => '</pre>'
],
['separator' => '---------------'],
[
'name' => 'Вставка изображения',
'className' => 'fa fa-picture-o',
'openWith' => '!',
'closeWith' => '!'
],
];
public static function sortIsuues($issues = null)
{
if($issues)
......@@ -75,6 +156,15 @@ class RedmineHelper
}
}
$other[self::OTHER_PROJECT] = $output[self::OTHER_PROJECT];
unset($output[self::OTHER_PROJECT]);
$output = [
'Доступные проекты' => $output,
$other[self::OTHER_PROJECT] => $other
];
return $output;
}
......
......@@ -5,78 +5,74 @@ use yii\helpers\Html;
?>
<?php if($output['models']) : ?>
<div class="panel-group panel-group-2" id="accordion_2">
<div class="panel panel-default">
<div class="panel-heading table-responsive">
<div class="panel panel-default">
<div class="panel-heading table-responsive">
<table class="w100pr table_header">
<tbody>
<tr>
<td>
<p class="panel-title2 pull-left">
<!-- <a href=""><span class="glyphicon glyphicon-align-justify"></span></a>&nbsp;&nbsp; -->
<strong><?=$title?></strong>&nbsp;&nbsp;
</p>
</td>
<td class="box_td">
<p><strong>Дата <br> поступления</strong></p>
</td>
<td class="box_td">
<p><strong>Срок <br> исполнения</strong></p>
</td>
<td class="box_td">
<p><strong>Стоимость <br> руб.</strong></p>
</td>
</tr>
</tbody>
</table>
<table class="w100pr table_header">
<tbody>
<tr>
<td>
<p class="panel-title2 pull-left">
<!-- <a href=""><span class="glyphicon glyphicon-align-justify"></span></a>&nbsp;&nbsp; -->
<strong><?=$title?></strong>&nbsp;&nbsp;
</p>
</td>
<td class="box_td">
<p><strong>Дата <br> поступления</strong></p>
</td>
<td class="box_td">
<p><strong>Срок <br> исполнения</strong></p>
</td>
<td class="box_td">
<p><strong>Стоимость <br> руб.</strong></p>
</td>
</tr>
</tbody>
</table>
</div>
<div id="collapse_1" class="panel-collapse collapse in">
<?php foreach ($output['models'] as $model) : ?>
<div class="panel-body panel-body-ex-1 color_on_cursor gray_box_2">
<table class="w100pr">
<tbody>
<tr>
<td class="box_td_fir">
<!-- <div class="arrov_poz pull-left">
<a href=""><span class="caret caret_top"></span></a>
<a href=""><span class="caret"></span></a>
</div> -->
<span><?=$model['id']?></span>
</td>
<td class="box_td_cont">
<p><strong><?=Html::a($model['subject'], ['/support/view/'.$model['id']])?></strong></p>
</td>
<td class="box_td">
<span><?=date('d.m.Y', strtotime($model['created_on']))?></span>
</td>
<td class="box_td">
<span><?=($model->due_date?date('d.m.Y', strtotime($model['due_date'])):'Не установлено')?></span>
</td>
<td class="box_td">
</div>
<div id="collapse_1" class="panel-collapse collapse in">
<?php foreach ($output['models'] as $model) : ?>
<div class="panel-body panel-body-ex-1 color_on_cursor gray_box_2">
<table class="w100pr">
<tbody>
<tr>
<td class="box_td_fir">
<!-- <div class="arrov_poz pull-left">
<a href=""><span class="caret caret_top"></span></a>
<a href=""><span class="caret"></span></a>
</div> -->
<span><?=$model['id']?></span>
</td>
<td class="box_td_cont">
<p><strong><?=Html::a($model['subject'], ['/support/view/'.$model['id']])?></strong></p>
</td>
<td class="box_td">
<span><?=date('d.m.Y', strtotime($model['created_on']))?></span>
</td>
<td class="box_td">
<span><?=($model->due_date?date('d.m.Y', strtotime($model['due_date'])):'Не установлено')?></span>
</td>
<td class="box_td">
<?php if(!$output['rating'] && $model['price_for_customer'] == 0) : ?>
<p class="green_text align_right"><strong>Гарантия</strong></p>
<?php else : ?>
<p class="pull-left"><strong><?=($model['price_for_customer']!=0 ? Yii::$app->formatter->asCurrency($model['price_for_customer'], 'RUR', [], [\NumberFormatter::CURRENCY_SYMBOL => '₽']) : 'Не установлено')?></strong></p>
<?php endif; ?>
<!-- <div class="tooltip_wr pull-right">
<div class="tooltip_box">Счет был выставлен</div>
<span class="tooltip_cont"><img src="/images/score_icon.jpg" height="24" width="19" alt=""></span>
</div> -->
</td>
</tr>
</tbody>
</table>
</div>
<?php endforeach; ?>
<?php if(!$output['rating'] && $model['price_for_customer'] == 0) : ?>
<p class="green_text align_right"><strong>Гарантия</strong></p>
<?php else : ?>
<p class="pull-left"><strong><?=($model['price_for_customer']!=0 ? Yii::$app->formatter->asCurrency($model['price_for_customer'], 'RUR', [], [\NumberFormatter::CURRENCY_SYMBOL => '₽']) : 'Не установлено')?></strong></p>
<?php endif; ?>
<!-- <div class="tooltip_wr pull-right">
<div class="tooltip_box">Счет был выставлен</div>
<span class="tooltip_cont"><img src="/images/score_icon.jpg" height="24" width="19" alt=""></span>
</div> -->
</td>
</tr>
</tbody>
</table>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<?php endif; ?>
\ No newline at end of file
......@@ -8,7 +8,7 @@ use common\modules\support\models\redmine\RedmineHelper;
?>
<div class="container_white">
<div class="container_white support-block">
<div class="container">
<div class="right_box_top row">
......@@ -53,82 +53,7 @@ use common\modules\support\models\redmine\RedmineHelper;
<?=$form->field($model, 'description', ['template' => "<p class='label_p'><strong>{label}</strong></p>\n{input}<br>{hint}{error}"])->widget(\coderlex\markitup\MarkItUp::className(), [
'options' => ['class' => 'form-control', 'style' => 'overflow:auto;resize:none;width:100%;min-height:200px;'],
'clientOptions' => [
'markupSet' => [
[
'name' => 'Жирный',
'className' => 'fa fa-bold',
'openWith' => '*',
'closeWith' => '*'
],
[
'name' => 'Курсив',
'className' => 'fa fa-italic',
'openWith' => '_',
'closeWith' => '_'
],
[
'name' => 'Подчеркнутый',
'className' => 'fa fa-underline',
'openWith' => '+',
'closeWith' => '+'
],
[
'name' => 'Зачеркнутый',
'className' => 'fa fa-strikethrough',
'openWith' => '-',
'closeWith' => '-'
],
['separator' => '---------------'],
[
'name' => 'Заголовок 1',
'className' => 'fa fa-header header-1',
'openWith' => 'h1. ',
'closeWith' => ''
],
[
'name' => 'Заголовок 2',
'className' => 'fa fa-header header-2',
'openWith' => 'h2. ',
'closeWith' => ''
],
[
'name' => 'Заголовок 3',
'className' => 'fa fa-header header-3',
'openWith' => 'h3. ',
'closeWith' => ''
],
['separator' => '---------------'],
[
'name' => 'Маркированный список',
'className' => 'fa fa-list-ul',
'openWith' => '* ',
'multiline' => true,
'openBlockWith' => "",
'closeBlockWith' => ""
],
[
'name' => 'Нумерованный список',
'className' => 'fa fa-list-ol',
'openWith' => '# ',
'multiline' => true,
'openBlockWith' => "",
'closeBlockWith' => ""
],
['separator' => '---------------'],
[
'name' => 'Заранее форматированный тест',
'className' => 'fa fa-newspaper-o',
'openWith' => '<pre>',
'closeWith' => '</pre>'
],
['separator' => '---------------'],
[
'name' => 'Вставка изображения',
'className' => 'fa fa-picture-o',
'openWith' => '!',
'closeWith' => '!'
],
]
'markupSet' => RedmineHelper::$markupSet
],
])?>
......@@ -163,41 +88,4 @@ use common\modules\support\models\redmine\RedmineHelper;
</div>
</div>
<style type="text/css">
.markItUpButton {
position: relative;
width: 23px;
height: 23px;
padding: 3px;
font-size: 13px;
text-align: center;
}
.markItUpButton a {
position: absolute;
top: 0;
left: 0;
z-index: 5;
}
.markItUp {
width: 100%;
margin: 5px 0 5px 0;
}
.header-2 {
font-size: 11px;
line-height: 16px;
}
.header-3 {
font-size: 9px;
line-height: 16px;
}
.help-block {
font-size: 12px;
line-height: 10px;
margin: -10px 0 25px;
}
.container_white .form-control {
float: none;
}
</style>
<?=$this->render('@app/views/layouts/footer');?>
\ No newline at end of file
......@@ -63,23 +63,27 @@ use common\modules\support\models\redmine\RedmineHelper;
<tr>
<td class="no_pad">
<?php
if($issues = RedmineHelper::sortIsuues($models['issues']))
{
foreach ($issues as $issue)
<div class="panel-group panel-group-2" id="accordion_2">
<?php
if($issues = RedmineHelper::sortIsuues($models['issues']))
{
if(!isset($issue['close']))
{
echo $this->render('_loop', ['output' => $issue, 'title' => $issue['title']]);
}
else
foreach ($issues as $issue)
{
$accepteds = $issue['models'];
if(!isset($issue['close']))
{
echo $this->render('_loop', ['output' => $issue, 'title' => $issue['title']]);
}
else
{
$accepteds = $issue['models'];
}
}
}
}
?>
?>
</div>
</td>
</tr>
</table>
......
<?php
use yii\widgets\ActiveForm;
use yii\helpers\Html;
use common\modules\support\models\redmine\Issue;
use common\modules\support\models\redmine\RedmineHelper;
$parser = new \Netcarver\Textile\Parser();
?>
<div class="container_white">
<div class="container_white support-block">
<div class="container">
<div class="right_box_top row">
......@@ -20,7 +26,11 @@ use common\modules\support\models\redmine\Issue;
</div>
<div class="row">
<?php if($model['status']['id'] == Issue::STATUS_APPROVE) : ?>
<div class="col-md-2 col-md-offset-10"><?=Html::a('Закрыть', ['/support/close/'.$model['id']], ['class' => 'btn btn-primary pull-right']);?></div>
<?php endif; ?>
<div class="col-md-12">
<div class="panel-body panel-body-ex-1 panel-body-ex-3 notifications_box color_on_cursor" <?=($model['priority']['id']==Issue::PRIORITY_SIMPLE?'style="border:0;"':'')?>>
......@@ -60,8 +70,7 @@ use common\modules\support\models\redmine\Issue;
<p><strong>Описание задачи</strong></p>
<p>
<?php $parser = new \Netcarver\Textile\Parser();
echo $parser->textileThis($model['description']); ?>
<?=$parser->textileThis($model['description']); ?>
</p>
</div>
......@@ -70,89 +79,84 @@ use common\modules\support\models\redmine\Issue;
<br>
<!-- <div class="row">
<div class="row">
<div class="col-sm-12">
<p class="label_p"><strong>Добавить комментарий к задаче</strong></p>
<div class="text_box_form text_box_form_bg">
<div class="text_box_form_top"><img src="/images/text_box_img.jpg" width="100%" alt=""></div>
<textarea>Высылаю нужный файл</textarea>
<?php $form = ActiveForm::begin(); ?>
<div class="file_box_wr">
<span class="glyphicon glyphicon-file"></span>
<a href="">Error_window.jpg &nbsp;</a>
<span class="color_gray">&nbsp;50,6 кБ&nbsp;&nbsp;</span>
<a href=""><span class="glyphicon glyphicon-remove color_gray"></span></a>
</div>
<div class="file_box_wr">
<span class="glyphicon glyphicon-file"></span>
<a href="">Error_window.jpg &nbsp;</a>
<span class="color_gray">&nbsp;50,6 кБ&nbsp;&nbsp;</span>
<a href=""><span class="glyphicon glyphicon-remove color_gray"></span></a>
</div>
<div class="file_box_wr">
<span class="glyphicon glyphicon-file"></span>
<a href="">Error_window.jpg &nbsp;</a>
<span class="color_gray">&nbsp;50,6 кБ&nbsp;&nbsp;</span>
<a href=""><span class="glyphicon glyphicon-remove color_gray"></span></a>
</div>
<div class="row">
<div class="col-sm-12">
<?=$form->field($issue, 'notes', ['template' => "{input}<br>{hint}{error}"])->widget(\coderlex\markitup\MarkItUp::className(), [
'options' => ['class' => 'form-control', 'style' => 'overflow:auto;resize:none;width:100%;min-height:100px;'],
'clientOptions' => [
'markupSet' => RedmineHelper::$markupSet
],
])->label(false)?>
</div>
</div>
<div id="file-container">
</div>
<input type="file" id="file-attachment-input" style="display:none;" multiple="multiple">
<?= Html::submitButton('Отправить', ['class' => 'btn btn-success-2 gray_button_poz']) ?>
<div class="gray_button attachment-button">Прикрепить файл<i class="glyphicon glyphicon-paperclip"></i></div>
<button class="btn btn-success-2 gray_button_poz">Отправить</button>
<?php ActiveForm::end(); ?>
<button class="gray_button">Прикрепить файл<i class="glyphicon glyphicon-paperclip"></i></button>
</div>
</div>
</div> -->
</div>
<?php if(isset($model['journals'])) : ?>
<div class="row">
<div class="col-md-12">
<div class="commentary_col">
<strong>Комментарии (<?=count($model['journals'])?>) </strong><!-- &nbsp;<span class="label label-success" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="4 задачи требуют проверки">4</span> -->
</div>
<?php foreach ($model['journals'] as $i => $journal) : ?>
<div class="commentary_box">
<!-- <div class="row">
<div class="col-md-12">
<div class="commentary_col">
<strong>Комментарии (14) </strong>&nbsp;<span class="label label-success" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="4 задачи требуют проверки">4</span>
</div>
<div class="commentary_box">
<p><strong>Иван Иванов</strong> <span class="color_gray">16 января 2014, 12:13</span></p>
<p>Прошу направить файлы заказчику и составить для него письмо.</p>
<a href=""><span class="glyphicon glyphicon-file"></span>скан_паспорта.jpg</a>&nbsp;&nbsp;
<a href=""><span class="glyphicon glyphicon-file"></span>данные.xml</a>
<br>
<img src="/images/commentary_box_img_1.jpg" width="96" height="56" alt="commentary_box_img_1">
<img src="/images/commentary_box_img_2.jpg" width="96" height="56" alt="commentary_box_img_2">
<br>
<a href="" class="commentary_box_ok">Ответить</a> &nbsp;&nbsp;&nbsp; <a href="" class="commentary_box_dell">Удалить</a>
<div class="line_3"></div>
<p><strong><?=$journal['user']['name']?></strong> <span class="color_gray"><?=Yii::$app->formatter->asDate($journal['created_on'], 'php:d F Y, H:i');?></span></p>
<p>
<?=$parser->textileThis($journal['notes']);?>
</p>
</div>
<div class="commentary_box marg_l_20">
<p><strong>Сидоров Петр</strong> <span class="color_gray">16 января 2014, 13:06</span></p>
<p>Почтовый сервер при отправке письма выдает вот такую ошибку. Что делать?</p>
<a href=""><span class="glyphicon glyphicon-file"></span>Error_window.jpg </a>&nbsp;&nbsp; <span class="color_gray">50,6 кБ</span>
<br>
<a href="" class="commentary_box_ok">Ответить</a> &nbsp;&nbsp;&nbsp; <a href="" class="commentary_box_dell">Удалить</a>
<div class="line_3"></div>
<?php if(isset($journal['details'])) : ?>
<?php foreach ($journal['details'] as $detail) : ?>
<?php if($detail['property'] == 'attachment') : ?>
<span class="glyphicon glyphicon-file"></span><?=$detail['new_value']?>&nbsp;&nbsp;
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
<div class="commentary_box marg_l_40">
<p><strong>Сидоров Петр</strong> <span class="color_gray">16 января 2014, 13:06</span></p>
<p>Почтовый сервер при отправке письма выдает вот такую ошибку. Что делать?</p>
<a href=""><span class="glyphicon glyphicon-file"></span>Error_window.jpg </a>&nbsp;&nbsp; <span class="color_gray">50,6 кБ</span>
<br>
<a href="" class="commentary_box_ok">Ответить</a> &nbsp;&nbsp;&nbsp; <a href="" class="commentary_box_dell">Удалить</a>
<br>
<?php if($i != count($model['journals']) - 1) : ?>
<div class="line_3"></div>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
</div> -->
<br>
<br>
<br>
<br>
<?php endif; ?>
</div>
</div>
......
......@@ -5,14 +5,16 @@ namespace common\modules\testings\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\filters\AccessControl;
use common\components\FrontendController;
use common\models\Settings;
use common\modules\testings\models\Test;
use common\modules\testings\models\Passing;
use common\modules\testings\models\Question;
use common\modules\testings\models\QuestionPassing;
class TestController extends \common\components\BaseController
class TestController extends FrontendController
{
public static function actionsTitles()
{
......@@ -27,6 +29,23 @@ class TestController extends \common\components\BaseController
);
}
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'user' => 'user',
'only' => ['info', 'pass', 'finish-test', 'set-answer', 'gen-pass', 'statistic', 'send-not-attempt'],
'rules' => [
[
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
public function actionInfo($id)
{
$model = $this->findModel($id);
......
......@@ -11,6 +11,7 @@ namespace common\modules\triggers\components\conditions;
use common\modules\triggers\controllers\TriggerAdminController;
use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerTrigger;
use common\modules\users\models\User;
use yii\web\ServerErrorHttpException;
class Conditions {
......@@ -161,9 +162,9 @@ class Conditions {
// Привели массив в понятный вид
$conditionsArray=[];
foreach($conditions as $i=>$condition) {
$object=Conditions::init()->getConditionById($condition->condition_id);
if ($object->recall===false)
return false;
// $object=Conditions::init()->getConditionById($condition->condition_id);
// if ($object->recall===false)
// return false;
$conditionsArray[$i][] = $condition;
} // На выходе получаем массив необходимого формата
// Обрабатываем отформатированный массив
......@@ -180,17 +181,46 @@ class Conditions {
return false;
}
public function handleUserByTriggerId($user_id, $trigger_id)
{
/** @var User $user */
$user = User::findOne($user_id);
if (!is_null($user)) {
// Результирующий массив
$resultArray=[];
// Получили все условия в рамках триггера
$conditions = TriggerCondition::find()->where(['trigger_id' => $trigger_id])->all();
// Привели массив в понятный вид
$conditionsArray=[];
foreach($conditions as $i=>$condition) {
$conditionsArray[$i][] = $condition;
} // На выходе получаем массив необходимого формата
// Обрабатываем отформатированный массив
foreach($conditionsArray as $key=>$array) {
$resultArray[] = self::checkConditionsArray($array, null, ['email' => $user->email]);
}
// Проверяем результат
if (count($resultArray)>0) {
foreach($resultArray as $result)
if ($result===false)
return false;
return true;
}
}
return false;
}
/**
* Проверяем массив параметров на срабатывание хотябы одного условия
* @param $array
* @param $message
* @return bool
*/
public static function checkConditionsArray($array, $message){
public static function checkConditionsArray($array, $message=null, $params=array()){
foreach($array as $item) {
$object=Conditions::init()->getConditionById($item->condition_id);
$object->model=$item;
if ($object->check($message)==true)
if ($object->check($message, $params)==true)
return true;
}
return false;
......
......@@ -28,7 +28,7 @@ class CheckClickingOnTheLink extends ConditionBase implements ConditionInterface
* @param $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
// Если модель условия указана и полученное сообщение не нуль
if (!is_null($this->model) && !is_null($message)) {
// Получаем параметр link
......
......@@ -23,7 +23,7 @@ class CheckEmailToDelivered extends ConditionBase implements ConditionInterface{
* @param $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
if (!is_null($message)) {
// Создаем объект унисендера
$sender=new UnisenderAPI();
......
......@@ -24,7 +24,7 @@ class CheckEmailToReading extends ConditionBase implements ConditionInterface {
* @param \common\modules\triggers\models\TriggerSchedule $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
if (!is_null($message)) {
// Создаем объект унисендера
$sender=new UnisenderAPI();
......
......@@ -23,7 +23,7 @@ class CheckEmailToUnsubscribed extends ConditionBase implements ConditionInterfa
* @param $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
if (!is_null($message)) {
// Создаем объект унисендера
$sender=new UnisenderAPI();
......
......@@ -14,9 +14,11 @@ use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface;
use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerLogs;
use common\modules\triggers\models\TriggerParam;
use common\modules\triggers\models\TriggerSchedule;
use common\modules\triggers\models\TriggerTrigger;
use common\modules\users\models\User;
use yii\web\BadRequestHttpException;
class CheckPresenceTime extends ConditionBase implements ConditionInterface {
......@@ -75,10 +77,33 @@ class CheckPresenceTime extends ConditionBase implements ConditionInterface {
}
/**
* @param $time
* @param TriggerSchedule $message
* @return bool
*/
public function check($time){
public function check($message=null, $params = array()){
$email = null;
if (!is_null($message))
$email = $message->email;
elseif(array_key_exists('email', $params)) {
$email = $params['email'];
}
if (!is_null($email)) {
$user = User::find()->where(['email' => $email])->one();
if (!is_null($message->trigger_id) && !is_null($user)) {
/** @var TriggerCondition[] $conditions */
$conditions = TriggerCondition::find()->where(['trigger_id'=>$message->trigger_id, 'condition_id' => self::CONDITION_ID])->all();
foreach($conditions as $condition) {
$urlParam = TriggerParam::find()->where(['condition_id' => $condition->getPrimaryKey(), 'key' => 'url', 'value' => \Yii::$app->request->getUrl()])->one();
$timeParam = TriggerParam::find()->where(['condition_id' => $condition->getPrimaryKey(), 'key' => 'time'])->one();
if (!is_null($urlParam) && !is_null($timeParam)) {
$sumTime = TriggerLogs::getSummaryTimeByUrl($urlParam, $user->getPrimaryKey());
if ($sumTime >= $timeParam) {
return true;
}
}
}
}
}
return false;
}
}
\ No newline at end of file
......@@ -86,10 +86,11 @@ class CheckScrolling extends ConditionBase implements ConditionInterface {
}
/**
* @param $time
* @param null $message
* @param array $params
* @return bool
*/
public function check($time){
public function check($message=null, $params = array()){
return false;
}
}
\ No newline at end of file
......@@ -5,6 +5,7 @@ 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;
use common\modules\triggers\models\TriggerLogs;
use common\modules\users\models\User;
class CheckUserToRegistration extends ConditionBase implements ConditionInterface{
......@@ -24,8 +25,20 @@ class CheckUserToRegistration extends ConditionBase implements ConditionInterfac
* @param $message
* @return bool
*/
public function check($message){
$exists = User::find()->where(['email' => $message->email])->exists();
return $exists;
public function check($message=null, $params = array()){
$email = null;
if (!is_null($message))
$email = $message->email;
elseif(array_key_exists('email', $params)) {
$email = $params['email'];
}
if (!is_null($email)) {
$user = User::find()->where(['email' => $email])->one();
if (!is_null($user)) {
$exists = TriggerLogs::find()->where(['user_id' => $user->getPrimaryKey(), 'action' =>TriggerLogs::USER_REGISTRATION])->exists();
return $exists;
}
}
return false;
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: shakarim
* Date: 3/18/16
* Time: 5:45 PM
*/
namespace common\modules\triggers\components\conditions\conditions;
use common\modules\triggers\components\conditions\vendor\ConditionBase;
use common\modules\triggers\components\conditions\vendor\ConditionInterface;
use common\modules\triggers\models\TriggerLogs;
use common\modules\users\models\User;
class CheckUserToSubscribe extends ConditionBase implements ConditionInterface{
const CONDITION_ID = 10;
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=null, $params = array()){
$email = null;
if (!is_null($message))
$email = $message->email;
elseif(array_key_exists('email', $params)) {
$email = $params['email'];
}
if (!is_null($email)) {
$user = User::find()->where(['email' => $email])->one();
if (!is_null($user)) {
$exists = TriggerLogs::find()->where(['user_id' => $user->getPrimaryKey(), 'action' =>TriggerLogs::USER_SUBSCRIBE])->exists();
return $exists;
}
}
return false;
}
}
\ No newline at end of file
......@@ -28,7 +28,7 @@ class UserSuccessfullyCompletedTheTest extends ConditionBase implements Conditio
* @param $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
return false;
}
}
\ No newline at end of file
......@@ -28,7 +28,7 @@ class UserUnsuccessfullyCompletedTheTest extends ConditionBase implements Condit
* @param $message
* @return bool
*/
public function check($message){
public function check($message=null, $params = array()){
return false;
}
}
\ No newline at end of file
......@@ -12,6 +12,9 @@ return [
'check-user-to-registration' => [
'class' => 'common\modules\triggers\components\conditions\conditions\CheckUserToRegistration',
],
'check-user-to-subscribe' => [
'class' => 'common\modules\triggers\components\conditions\conditions\CheckUserToSubscribe',
],
'user-successfully-completed-the-test' => [
'class' => 'common\modules\triggers\components\conditions\conditions\UserSuccessfullyCompletedTheTest',
],
......
......@@ -5,5 +5,5 @@ interface ConditionInterface {
// Функция инициализации
public static function init($conditionName=null);
public function check($model);
public function check($model=null, $params=array());
}
\ No newline at end of file
......@@ -3,11 +3,20 @@
namespace common\modules\triggers\controllers;
use common\components\BaseController;
use common\modules\bids\models\Bid;
use common\modules\content\models\CoContent;
use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\triggers\components\conditions\Conditions;
use common\modules\triggers\models\AuthHashes;
use common\modules\triggers\models\TriggerLogs;
use common\modules\triggers\models\TriggerSchedule;
use common\modules\triggers\models\TriggerTrigger;
use common\modules\users\models\User;
use \DateTime;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use common\modules\messageTemplate\components\Templates;
use common\components\UnisenderAPI;
/**
* Default controller for the `triggers` module
......@@ -18,10 +27,26 @@ class DefaultController extends BaseController
return [
'Index' => 'Главная страница модуля',
'Rechecktriggers' => 'Запуск проверки срабатывания триггеров',
'Recheckcases' => 'Запуск рассылки кейсов',
'Settimeoflogs' => 'Фиксация времени логов',
'Inittrigger' => 'Initiate trigger By id'
];
}
/**
* @param $id
* @param $value
*/
public function actionSettimeoflogs($id, $value)
{
/** @var TriggerLogs $model */
$model = TriggerLogs::findOne($id);
if (!is_null($model)) {
$model->presence_time = $value;
$model->save(false);
}
}
public function actionInittrigger($id){
if (\Yii::$app->request->isAjax) {
/** @var TriggerTrigger $trigger */
......@@ -43,6 +68,7 @@ class DefaultController extends BaseController
* Метод для крона и ручного вызова. Проверяет таблицу с расписанием, выполняет сработавшие триггеры.
*/
public function actionRechecktriggers(){
// Производим проверку по расписанию
/** @var TriggerTrigger[] $actualTriggers */
// Получили текущую дату и время
$timeNow = new DateTime();
......@@ -73,5 +99,69 @@ class DefaultController extends BaseController
$model->save();
}
}
// Производим проверку событий
$users = User::find()->where('id>0')->all();
foreach($users as $user) {
foreach($actualTriggers as $trigger) {
// Вызвали метод проверки срабатывания условий
$triggerResult = Conditions::init()->handleUserByTriggerId($user->getPrimaryKey(), $trigger->getPrimaryKey());
// Если триггер сработал инициируем действие
if ($triggerResult===true) {
$init = $trigger->initAction(['email' => $user->email]);
if ($init!==true)
echo $init;
}
}
}
}
public function actionRecheckcases($category_id = 4, $template_id=1, $neededTime=10) {
$date = new \DateTime();
/** @var User[] $users */
$users = User::find()->all();
// URL основной страницы
$baseUrl = 'http://task-on.com/';
// Получили массив url-ов в категории
$urls = ArrayHelper::map(CoContent::find()->where(['category_id'=>$category_id])->all(), 'id', 'url');
// Перебираем в цикле пользователей
foreach($users as $user) {
// Получили дату для дальнейшего сравнения
$deliveryDate = new \DateTime($user->delivery_date);
// Если пользователь подписан и дата соответствует требованиям
if (Bid::find()->where(['email' => $user->email])->exists() && $deliveryDate<=$date) {
// Перебираем все url-ы
foreach($urls as $url) {
// Получаем время просмотра каждой страницы
$watchingtime = TriggerLogs::getSummaryTimeByUrl($url, $user->id);
// Если суммарное время просмотра больше минимальной нормы
if ((int)$watchingtime>(int)$neededTime) {
// Производим отправку письма
// Получаем почту
$email = $user->email;
// Генерируем хеш
$hash=AuthHashes::setNewHash($email);
// Сформировали дату
$templateData = [
'case_link' => $baseUrl.$url.'?hash='.$hash.'&email='.$email
];
// Производим отправку
/** @var \DateTime $time_now */
TriggerSchedule::sendMessage($email, $template_id, $templateData, null);
}
}
// Создали дату следующей отправки
$updatedDate=new \DateTime();
// Произвели модификацию даты
$updatedDate->modify('+7 days');
/** @var User $user */
// Нашли пользователя
$user=User::findOne($this->id);
// Переопределили поле
$user->delivery_date = $updatedDate->format('Y-m-d');
// Сохранили изменения
$user->save(false);
}
}
}
}
......@@ -49,16 +49,15 @@ class TriggerAdminController extends AdminController {
return Json::encode($result);
}
public function actionTesting(){
// $trigger = \common\modules\triggers\components\conditions\conditions\CheckClickingOnTheLink::init();
// $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 actionTesting($hash=null, $email=null){
$thisLink = '/triggers/trigger-admin/testing';
$generatedLink = Yii::$app->request->getUrl();
$result = (strpos($generatedLink, $thisLink)!==false) ? 'true' : 'false';
echo $thisLink;
echo '<br>';
echo $generatedLink;
echo '<br>';
var_dump($result);
}
public function actionGetresult($id){
......
<?php
namespace common\modules\triggers\models;
use Yii;
/**
* This is the model class for table "auth_hashes".
*
* @property integer $id
* @property string $email
* @property string $hash
* @property integer $auth_count
* @property string $valid_date
*/
class AuthHashes extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'auth_hashes';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['email', 'hash', 'valid_date'], 'required'],
[['auth_count'], 'integer'],
[['valid_date'], 'safe'],
[['email'], 'string', 'max' => 255],
[['hash'], 'string', 'max' => 50],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'email' => 'Email',
'hash' => 'Hash',
'auth_count' => 'Auth Count',
'valid_date' => 'Valid Date',
];
}
/**
* @param $email
* @return string
*/
public static function setNewHash($email)
{
$validDate = new \DateTime();
$validDate->modify('+3 hours');
$hash = Yii::$app->security->generateRandomString(50);
$model = new AuthHashes();
$model->email = $email;
$model->hash = $hash;
$model->auth_count = 0;
$model->valid_date = $validDate->format('Y-m-d H:i:s');
if ($model->save())
return $hash;
}
}
<?php
namespace common\modules\triggers\models;
use Faker\Provider\DateTime;
use Yii;
use common\modules\users\models\User;
/**
* This is the model class for table "trigger_logs".
*
* @property integer $id
* @property integer $user_id
* @property string $action
* @property string $url
* @property string $datetime
* @property integer $presence_time
*
* @property User $user
*/
class TriggerLogs extends \yii\db\ActiveRecord
{
const USER_REGISTRATION = 'registration';
const USER_SUBSCRIBE = 'subscribe';
const USER_VISITED = 'visited';
public static function logAction()
{
if (!Yii::$app->user->isGuest && !Yii::$app->request->isAjax) {
$action = self::USER_VISITED;
if (Yii::$app->controller->action->id=='registration')
$action = self::USER_REGISTRATION;
if (Yii::$app->request->getUrl()=='/bids/bid/add')
$action = self::USER_SUBSCRIBE;
$date = new \DateTime();
$model = new TriggerLogs();
$model->user_id = Yii::$app->user->identity->id;
$model->action = $action;
$model->url = Yii::$app->request->getUrl();
$model->datetime = $date->format('Y-m-d H:i:s');
$model->presence_time = 1;
if ($model->save()) {
$view = \Yii::$app->controller->view;
// Создаем скрипт
$script ='$(document).ready(function() {
var id='.($model->getPrimaryKey()).';
var interval = 5;
var value = 5;
setInterval(function() {
$.ajax({
url: "http://taskon.task-on.com/triggers/default/settimeoflogs",
method: "GET",
async: false,
data: {
id: id,
value: value
},
});
value += interval;
}, (interval*1000));
});';
// Регистрируем его
$view->registerJs($script, $view::POS_READY);
}
}
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'trigger_logs';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id', 'action', 'datetime', 'url'], 'required'],
[['user_id', 'presence_time'], 'integer'],
[['datetime'], 'safe'],
[['action', 'url'], 'string', 'max' => 255],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'user_id' => 'User ID',
'action' => 'Action',
'datetime' => 'Datetime',
'presence_time' => 'Presence Time',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(User::className(), ['id' => 'user_id']);
}
public static function getSummaryTimeByUrl($url, $user_id) {
/** @var TriggerLogs[] $model */
$model = TriggerLogs::find()->where(['url' => $url, 'user_id' => $user_id])->all();
$summ = 0;
foreach($model as $item) {
$summ += $item->presence_time;
}
return $summ;
}
}
......@@ -3,6 +3,10 @@
namespace common\modules\triggers\models;
use Yii;
use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\messageTemplate\components\Templates;
use common\components\UnisenderAPI;
use yii\helpers\Json;
/**
* This is the model class for table "trigger_schedule".
......@@ -62,4 +66,64 @@ class TriggerSchedule extends \yii\db\ActiveRecord
'campaign_id' => 'Campaign ID',
];
}
public static function sendMessage($email, $template_id, $templateData, $trigger_id=null)
{
$time_now=new \DateTime();
/** @var MessageTemplate $templateModel */
$templateModel = MessageTemplate::findOne($template_id);
/** @var Templates $template */
$template = new Templates($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->template_id=$template_id;
$schedule->trigger_id=$trigger_id;
$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;
}
}
}
......@@ -240,63 +240,7 @@ class TriggerTrigger extends \common\components\ActiveRecordModel
$sendExist = false;
if (!$sendExist) {
/** @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->template_id=$this->message_template_id;
$schedule->trigger_id=$this->id;
$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;
}
return TriggerSchedule::sendMessage($email, $this->message_template_id, $templateData, $this->id);
}
}
}
......@@ -4,8 +4,12 @@ namespace common\modules\users\models;
use common\components\UnisenderAPI;
use common\modules\messageTemplate\controllers\TemplateAdminController;
use common\modules\messageTemplate\models\MessageTemplate;
use common\modules\triggers\components\conditions\Conditions;
use common\modules\triggers\components\conditions\conditions\CheckUserToRegistration;
use common\modules\triggers\components\conditions\conditions\CheckUserToSubscribe;
use common\modules\triggers\models\AuthHashes;
use common\modules\triggers\models\TriggerCondition;
use common\modules\triggers\models\TriggerLogs;
use common\modules\triggers\models\TriggerSchedule;
use common\modules\triggers\models\TriggerTrigger;
use Yii;
......@@ -24,12 +28,20 @@ use \common\modules\rbac\models\AuthAssignment;
use \common\modules\eauth\models\UserEAuth;
use yii\web\UrlManager;
/**
* Class User
* @package common\modules\users\models
*
* @property string $delivery_date
*/
class User extends \common\components\ActiveRecordModel implements IdentityInterface
{
public $created_at;
public $updated_at;
const PAGE_SIZE = 10;
const CACHE_SCORE = 'user.scores.';
const OCCUPATION_CHIEF_IT = 1;
const OCCUPATION_MANAGER_IT = 2;
......@@ -355,6 +367,23 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
return "Пользователи";
}
public function clearScoreCache()
{
Yii::$app->cache->delete(self::CACHE_SCORE . $this->id);
}
public function getScores()
{
$score = Yii::$app->cache->get(self::CACHE_SCORE . $this->id);
if($score === false)
{
Yii::$app->cache->set(self::CACHE_SCORE . $this->id, $score);
}
return $score;
}
public function getCustomName($user = null)
{
......@@ -500,11 +529,21 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
if (!parent::validate($attributeNames = null, $clearErrors = true))
return false;
// if ($this->scenario===self::SCENARIO_REGISTRATION || $this->scenario===self::SCENARIO_SOCIAL_REGISTRATION) {
// if (!$this->afterRegistration(['email' => $this->email, 'user_fio' => $this->getFio()]))
// return false;
// }
return true;
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if ($this->scenario===self::SCENARIO_REGISTRATION || $this->scenario===self::SCENARIO_SOCIAL_REGISTRATION) {
if (!$this->afterRegistration(['email' => $this->email, 'user_fio' => $this->getFio()]))
return false;
}
return true;
}
public function afterDelete()
......@@ -560,15 +599,64 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
* Если указан, выполняем действия триггера
*/
public function afterRegistration($params=array()){
$date = new \DateTime();
$model = new TriggerLogs();
$model->user_id = $this->getPrimaryKey();
$model->action = TriggerLogs::USER_REGISTRATION;
$model->url = Yii::$app->request->getUrl();
$model->datetime = $date->format('Y-m-d H:i:s');
$model->presence_time = 1;
if ($model->save()) {
/** @var TriggerTrigger[] $actualTriggers */
$actualTriggers = TriggerTrigger::getActualTriggers();
foreach($actualTriggers as $trigger) {
$exists = TriggerCondition::find()->where(['trigger_id'=>$trigger->id, 'condition_id'=>CheckUserToRegistration::CONDITION_ID])->exists();
$count = TriggerCondition::find()->where(['trigger_id'=>$trigger->id])->count();
// Добавляем в расписание срабатывание триггера регистрации только при условии что у триггера условие регистрации есть и оно там одно
if ($exists===true && $count==1) {
$init = $trigger->initAction($params);
if ($init===true) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, Yii::$app->urlManager->createAbsoluteUrl('/triggers/default/rechecktriggers'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if (!curl_exec($curl)) {
$this->addError('email', curl_error($curl));
return false;
}
return true;
} else {
$this->addError('email', $init);
return false;
}
}
}
} else {
$this->addError('email', current(current($model->getErrors())));
return false;
}
return true;
}
/**
* @param array $params
* @return bool
*/
public function afterSubscribe($params=array()){
$date = new \DateTime();
/** @var TriggerTrigger[] $actualTriggers */
$actualTriggers = TriggerTrigger::getActualTriggers();
foreach($actualTriggers as $trigger) {
$exists = TriggerCondition::find()->where(['trigger_id'=>$trigger->id, 'condition_id'=>CheckUserToRegistration::CONDITION_ID])->exists();
$exists = TriggerCondition::find()->where(['trigger_id'=>$trigger->id, 'condition_id'=>CheckUserToSubscribe::CONDITION_ID])->exists();
$count = TriggerCondition::find()->where(['trigger_id'=>$trigger->id])->count();
// Добавляем в расписание срабатывание триггера регистрации только при условии что у триггера условие регистрации есть и оно там одно
if ($exists===true && $count==1) {
$init = $trigger->initAction($params);
if ($init===true) {
// Указываем дату следующей отправки (по умолчанию сегодня, в момент срабатывания триггера)
$user=User::findOne($this->id);
$user->delivery_date = $date->format('Y-m-d');
$user->save(false);
// Вызываем перезапуск всех триггеров
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, Yii::$app->urlManager->createAbsoluteUrl('/triggers/default/rechecktriggers'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
......@@ -576,6 +664,14 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
$this->addError('email', curl_error($curl));
return false;
}
// Затем инициируем рассылку
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, Yii::$app->urlManager->createAbsoluteUrl('/triggers/default/recheckcases'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
if (!curl_exec($curl)) {
$this->addError('email', curl_error($curl));
return false;
}
return true;
} else {
$this->addError('email', $init);
......@@ -583,58 +679,30 @@ class User extends \common\components\ActiveRecordModel implements IdentityInter
}
}
}
return true;
}
/**
* @param $template_id
*/
public function afterSubscribe($template_id, $params=array()){
/** @var \DateTime $time_now */
$time_now=new \DateTime();
/** @var MessageTemplate $templateModel */
$templateModel = MessageTemplate::findOne($template_id);
/** @var Templates $template */
$template = new Templates($template_id, $params);
$email = $this->email;
$sender = new UnisenderAPI();
// Create the send list
$newList = $sender->createList();
$newListObject=Json::decode($newList);
if (array_key_exists('result', $newListObject) && 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($this->name, $email, $templateModel->subject, $template->getTemplate(), $newListId);
// Decode result
$newMessageObject=Json::decode($newMessage);
if (array_key_exists('result', $newMessageObject) && 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) && array_key_exists('campaign_id', $newCampaignObject['result'])) {
$newCampaignId = $newCampaignObject['result']['campaign_id'];
$schedule = new TriggerSchedule();
$schedule->sended=1;
$schedule->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()) {
echo 'Письмо не было отправлено';
}
}
}
}
}
/**
* @return bool
*/
public function checkToAutoAuthByHash($hash)
{
$date = new \DateTime();
/** @var AuthHashes $data */
$data = AuthHashes::find()->where(['hash' => $hash, 'email' => $this->email]);
if (!is_null($data)) {
$dataDate = new \DateTime($data->valid_date);
if ($date<=$dataDate)
return true;
}
return false;
}
/**
* @return bool
*/
public function authUser()
{
return Yii::$app->user->login($this, $this->rememberMe ? 3600 * 24 * 30 : 0);
}
}
<?php
use yii\db\Migration;
class m160315_022841_add_logs_table extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->createTable(
'trigger_logs',
[
'id' => $this->primaryKey(),
'user_id' => $this->integer()->notNull(),
'action' => $this->string(255)->notNull(),
'url' => $this->string(255)->notNull(),
'datetime' => $this->dateTime()->notNull(),
'presence_time' => $this->integer(11)->defaultValue(1)
]
);
$this->addForeignKey(
'trigger_logs_user_id',
'trigger_logs', 'user_id',
'users', 'id'
);
}
public function safeDown()
{
$this->dropForeignKey(
'trigger_logs_user_id',
'trigger_logs'
);
$this->dropTable('trigger_logs');
}
}
<?php
use yii\db\Schema;
use yii\db\Migration;
class m160316_114638_upgrade_content extends Migration
{
public function up()
{
$this->addColumn('co_content', 'type', Schema::TYPE_INTEGER . '(1) NOT NULL DEFAULT 1');
}
public function down()
{
$this->dropColumn('co_content', 'type');
}
}
<?php
use yii\db\Migration;
class m160316_125140_set_default_value_to_trigger_column_in_schedule_table extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->alterColumn(
'trigger_schedule',
'trigger_id',
$this->integer(11)->defaultValue(null)
);
}
public function safeDown()
{
$this->alterColumn(
'trigger_schedule',
'trigger_id',
$this->integer(11)->notNull()
);
}
}
<?php
use yii\db\Migration;
class m160317_141523_add_hashes_table_for_auth extends Migration
{
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
$this->createTable(
'auth_hashes',
[
'id' => $this->primaryKey(),
'email' => $this->string(255)->notNull(),
'hash' => $this->string(50)->notNull(),
'auth_count' => $this->integer(11)->defaultValue(0),
'valid_date' => $this->dateTime()->notNull()
]
);
}
public function safeDown()
{
$this->dropTable('auth_hashes');
}
}
<?php
use yii\db\Migration;
class m160318_140227_add_delivery_date_column_to_user_table extends Migration
{
public function up()
{
$this->addColumn(
'users',
'delivery_date',
$this->date()->defaultValue(null)
);
}
public function down()
{
$this->dropColumn(
'users',
'delivery_date'
);
}
}
......@@ -75,7 +75,7 @@ return [
'name' => '_frontendIdentity'
],
'enableAutoLogin' => true,
'loginUrl' => ['/site/login'],
'loginUrl' => ['/school'],
],
'support' => [
'class' => 'yii\web\User',
......
......@@ -3,11 +3,11 @@ namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Url;
use common\components\FrontendController;
use common\models\LoginForm;
use common\modules\users\models\User;
use common\modules\eauth\components\GoogleOAuth2Service;
......@@ -16,14 +16,10 @@ use common\modules\eauth\models\UserEAuth;
/**
* Site controller
*/
class SiteController extends Controller
class SiteController extends FrontendController
{
public $layout = '//main';
public $meta_title;
public $meta_description;
public $meta_keywords;
public static function actionsTitles(){
return [
'Index' => 'Главная страница',
......@@ -50,10 +46,10 @@ class SiteController extends Controller
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'only' => ['logout', 'signup', 'login'],
'rules' => [
[
'actions' => ['signup'],
'actions' => ['signup', 'login'],
'allow' => true,
'roles' => ['?'],
],
......@@ -64,12 +60,6 @@ class SiteController extends Controller
],
],
],
/* 'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],*/
'eauth' => [
// required to disable csrf validation on OpenID requests
'class' => \nodge\eauth\openid\ControllerBehavior::className(),
......@@ -163,7 +153,7 @@ class SiteController extends Controller
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->validate())
{
if($model->user->role == User::ROLE_USER || $model->user->role == User::ROLE_ADMIN)
if($model->user->role == User::ROLE_USER)
{
$model->login();
}
......@@ -172,7 +162,7 @@ class SiteController extends Controller
echo json_encode(['errors' => []]);
}
$this->redirect(array("/school/course/index"));
$this->redirect(['/support']);
}
else
{
......
......@@ -4,7 +4,7 @@ use yii\helpers\Html;
$reviews = Reviews::find()
->where(['state' => 'active'])
->orderBy('created_at DESC')
->orderBy(['priority' => SORT_ASC])
->limit(1)
->all();
?>
......
......@@ -57,4 +57,7 @@ use common\modules\bids\models\Bid;
<?php ActiveForm::end(); ?>
</div>
<?php echo \common\modules\users\widgets\LoginWidget::widget(); ?>
<?php echo \common\modules\users\widgets\RegistrationWidget::widget(); ?>
</div>
\ No newline at end of file
......@@ -38,6 +38,14 @@ $more = CoContent::find()
</div>
<?php endif; ?>
<?php
$show = true;
if (!Yii::$app->user->isGuest && Bid::find()->where(['email' => Yii::$app->user->identity->email])->exists())
$show = false;
if ($show===true):
?>
<div class="col-md-6 col-xs-6 col-sm-12">
<div class="subsc_block">
<h2 class="subsc_block_title">Подписаться на обновления</h2>
......@@ -80,6 +88,7 @@ $more = CoContent::find()
<?php ActiveForm::end(); ?>
</div>
</div>
<?php endif; ?>
</div>
<!-- </div>
</section> -->
......
......@@ -28,6 +28,7 @@ $caseCount = CoContent::find()->where([
<div>
<div class="others_project">
<span class="others_project__subtitle"><?=$model->lang->title?></span>
<a href="<?=Url::to(['/' . $model->url])?>" class="others_project__subtitle_a"><?=$model->lang->title?></a>
<p class="others_project__txt"><?=$model->lang->text?></p>
<a href="<?=Url::to(['/' . $model->url])?>" class="others_project__bt"><?=Yii::t('projects', 'See more')?></a>
<a href="<?=Url::to(['/portfolio'])?>" class="others_project__link"><?=Yii::t('projects', 'All projects')?> <?if($caseCount>20){?>(<?=$caseCount;?>)<?}?></a>
......
......@@ -4,7 +4,7 @@ use yii\helpers\Html;
$reviews = Reviews::find()
->where(['state' => 'active'])
->orderBy('created_at DESC')
->orderBy(['priority' => SORT_ASC])
->all();
?>
<?php if($reviews) : ?>
......
......@@ -26,4 +26,7 @@
<?php $this->registerJsFile('/js/jquery.form.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/connect-form.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/prism.js', ['position' => yii\web\View::POS_END ]);?>
<?php // $this->registerJsFile('/plugins/fusioncharts-suite-xt/js/fusioncharts.js', ['position' => yii\web\View::POS_END ]);?>
<?php $this->registerJsFile('/js/custom.js', ['position' => yii\web\View::POS_END ]);?>
\ No newline at end of file
<footer>
<div class="container">
<div class="footbottom_line">
<div class="row">
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="foot_logo">
<img src="/images/foot_logo.png" height="51" width="192" alt="">
</div>
</div>
<div class="col-md-6 col-xs-6 col-sm-12">
<?php echo $this->render('block/social'); ?>
</div>
<div class="col-md-3 col-xs-3 col-sm-12">
<div class="taskon"><img src="/images/taskon.png" height="31" width="100" alt=""></div>
<div class="copyring">Powered by Taskon <br> Собственная разработка Арт Проект</div>
</div>
</div>
</div>
</div>
</footer>
<div class="up-button-container">
<div class="up-button"></div>
</div>
<?php echo $this->render('block/callback'); ?>
\ No newline at end of file
......@@ -35,4 +35,7 @@ endif; ?>
<?php $this->registerCssFile('/css/screen.css');?>
<?php $this->registerCssFile('/css/media.css');?>
<?php $this->registerCssFile('/css/prism.css');?>
<?php $this->registerCssFile('/css/custom.css');?>
<?php $this->registerCssFile('/css/new_responsive.css');?>
<header>
<div class="container">
<div class="row">
<div class="col-md-2 col-xs-12 col-sm-12">
<a href="http://mikulin.cz/project/artproject/" class="logo_testing">
<img src="images/logo.png" height="34" width="125" alt="">
</a>
</div>
<div class="col-md-5 col-md-offset-1 col-xs-7 col-sm-12">
<div class="ball-block_testing">Накоплено баллов:
<span class="col-ball_testing">99 999</span>
<a href="#" class="ball-link_testing">Как увеличить?</a>
<div class="ball_hover">Текст как увеличить,<br/> текст как увеличить,</div>
</div>
</div>
<div class="col-md-3 col-md-offset-1 col-xs-5 col-sm-12">
<div class="prof_block_testing">
<span class="prof_name_testing"><?php echo Yii::$app->user->identity->name; ?></span>
<?php echo \yii\helpers\Html::a('Выход', ['/users/user/logout']); ?>
</div>
</div>
</div>
</div>
</header>
\ No newline at end of file
<section class="ks_header">
<div class="container">
<div class="row">
<div class="col-md-5 col-xs-7 col-sm-12">
<div class="ball-block">Накоплено баллов:
<span class="col-ball"><?=\Yii::$app->user->identity->getScores();?></span>
<a href="#" class="ball-link">Как увеличить?</a>
<div class="ball_hover">Текст как увеличить,<br> текст как увеличить,</div>
</div>
</div>
<div class="col-md-5 col-md-offset-2 col-xs-5 col-sm-12">
<?php echo \common\modules\users\widgets\UserBoxWidget::widget() ?>
</div>
</div>
</div>
</section>
\ No newline at end of file
......@@ -26,10 +26,11 @@ AppAsset::register($this);
<?php $this->beginBody() ?>
<?php echo (Yii::$app->user->isGuest) ? $this->render('header') : $this->render('header-auth'); // Добавить проверку на авторизацию и вывести другую шапку header-auth.php ?>
<?php echo $this->render('header'); ?>
<?php echo $content ?>
<script src="/plugins/fusioncharts-suite-xt/js/fusioncharts.js"></script>
<?php $this->endBody() ?>
......
This diff is collapsed.
......@@ -5,6 +5,14 @@
top: 307px;
}
.keis_slider_btn_poz {
position: absolute;
bottom: 0;
}
.others_project__subtitle_a {
display: none;
}
@media only screen and (max-width: 970px) {
.mackup_text {
......@@ -110,12 +118,13 @@ a.toggle_bottom {
margin-top: 15px;
margin: 35px;
display: block;
background: url(../images_new/puls_resp.png) 0 0 no-repeat;
background: url(../images/puls_resp.png) 0 0 no-repeat;
}
.section4 {
padding-bottom: 60px;
background: none;
min-height: 870px;
background: url(../images/testing_bg_resp_2.png) center bottom no-repeat;
}
ul.ul_check:last-child {
margin-top: 29px;
......@@ -124,7 +133,7 @@ ul.ul_check:last-child {
margin-top: -125px;
}
.green_title {
margin-top: 70px;
margin-top: 155px;
}
.cif_50 {
width: 50%;
......@@ -150,6 +159,10 @@ ul.ul_check:last-child {
}
.project_tit {
text-align: center;
margin-top: 100px;
}
.bx-wrapper {
margin-top: 25px;
}
.sup_block__item1 {
margin-bottom: 20px;
......@@ -205,6 +218,38 @@ filter: progid:DXImageTransform.
.file-upload_block {
display: none;
}
.inf_comanda {
margin-top: 40px;
}
.down_bg_last {
height: 520px;
}
.calk_form {
margin-top: 35px;
}
.others_project {
display: block;
position: absolute;
top: 520px;
left: 0;
z-index: 25;
}
.others_project__txt, .others_project__bt, .others_project__subtitle, .others_project__link, .others_project__subtitle {
display: none;
}
.bx-wrapper .bx-pager, .bx-wrapper .bx-controls-auto {
bottom: -155px;
}
.others_project__subtitle {
margin-bottom: 10px;
}
.others_project__subtitle_a {
display: block;
}
}
@media only screen and (max-width: 480px) {
......@@ -218,6 +263,7 @@ filter: progid:DXImageTransform.
.section6 {
padding-bottom: 80px;
min-height: 1250px;
}
.bx-wrapper .bx-pager, .bx-wrapper .bx-controls-auto {
bottom: -50px;
......@@ -236,17 +282,69 @@ filter: progid:DXImageTransform.
margin-left: -60px;
margin-right: 15px;
}
.section5 {
margin-top: -10px;
}
.section6 {
background-position: center -28px;
background-position: center -65px;
}
.inf_comanda {
margin-top: 120px;
}
.down_bg_last {
height: 475px;
}
.code_block__txt {
font-size: 14px;
}
.section8_title {
font-size: 18px;
}
.geentxt span {
font-size: 15px;
padding: 0 6px 6px;
}
@media only screen and (max-width: 368px) {
.others_project {
display: block;
position: absolute;
top: 300px;
left: 0;
z-index: 25;
width: auto;
}
.others_project__txt, .others_project__bt, .others_project__subtitle, .others_project__link, .others_project__subtitle {
display: none;
}
.bx-wrapper .bx-pager, .bx-wrapper .bx-controls-auto {
bottom: -95px;
}
.others_project__subtitle {
margin-bottom: 10px;
}
.others_project__subtitle_a {
display: block;
}
.others_project__subtitle_a {
font-size: 14px;
}
.section4 {
min-height: 930px;
}
.mackup_item3_on {
left: 20px;
}
.mackup_item2_on {
left: 0;
}
.section3 {
overflow: hidden;
}
}
@media only screen and (max-width: 320px) {
body {
min-width: 320px;
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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