Переделал виджет, более читаем

This commit is contained in:
maxim 2021-09-13 16:40:37 +03:00
parent 4b08696ed2
commit 358ffbf794
12 changed files with 255 additions and 249 deletions

View File

@ -4,22 +4,29 @@ namespace backend\modules\calendar\controllers;
use backend\modules\card\models\UserCardSearch; use backend\modules\card\models\UserCardSearch;
use Yii; use Yii;
use yii\helpers\ArrayHelper;
use yii\web\Response; use yii\web\Response;
class AjaxController extends \yii\web\Controller class AjaxController extends \yii\web\Controller
{ {
public function actionGetBirthdayByMonth($month )
public function actionGetBirthdayDate($date)
{
$searchModel = new UserCardSearch();
$dataProvider = $searchModel->search(['date' => $date]);
return $this->render('_gridView', [
'dataProvider' => $dataProvider
]);
}
public function actionGetBirthdayDatesByMonth($month )
{ {
$searchModel = new UserCardSearch(); $searchModel = new UserCardSearch();
$models = $searchModel->search(Yii::$app->request->queryParams)->getModels(); $models = $searchModel->search(Yii::$app->request->queryParams)->getModels();
$models_array = ArrayHelper::toArray($models, [ $models_array = array_map(function ($date){return date('Y').substr($date, 4,6);},
'backend\modules\card\models\UserCard' => [ array_column($models, 'dob')
'id', );
'dob',
'fio'
],
]);
$response = Yii::$app->response; $response = Yii::$app->response;
$response->format = Response::FORMAT_JSON; $response->format = Response::FORMAT_JSON;

View File

@ -42,11 +42,11 @@ class CalendarController extends Controller
* Renders the index view for the module * Renders the index view for the module
* @return string * @return string
*/ */
public function actionCalendar(){ public function actionIndex(){
return $this->render('calendar'); return $this->render('index');
} }
public function actionIndex() public function actionTable()
{ {
$searchModel = new UserCardSearch(); $searchModel = new UserCardSearch();
$user_card = \common\models\UserCard::find()->all(); $user_card = \common\models\UserCard::find()->all();
@ -67,7 +67,7 @@ class CalendarController extends Controller
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
} }
return $this->render('index', [ return $this->render('table', [
'searchModel' => $searchModel, 'searchModel' => $searchModel,
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
]); ]);

View File

@ -0,0 +1,18 @@
<?php
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'fio',
'dob',
['class' => 'yii\grid\ActionColumn'],
],
]);
die();

View File

@ -1,59 +0,0 @@
<?php
use yii\helpers\Html;
$this->title = 'Календарь ДР';
?>
<?= \backend\widgets\Calendar::widget([
'css' => '.success{color: orange;}',
'button' => Html::a('<i class="fas fa-long-arrow-alt-left"></i> Назад',
Yii::$app->request->referrer, ['class' => 'btn btn-primary',]),
'runBuild' => "function (date, content){
this.build(date, content)
}",
'updateContent' => "function(date){
let monthNumber = date.substr(5, 2);
return fetch('../ajax/get-birthday-by-month?' +
'month=' + monthNumber)
.then((res) => {
return res.json()
})
}",
'getColor' => "function (date, dates = null) {
for (let contentDate of dates) {
if (contentDate['dob'].substr(8, 2) == DateHelper.intToDate(date.getDate())) {
return 'success';
}
}
}",
'getHtmlContentForDate' => 'function (content, date) {
let flag = false
let html = `<table class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>ФИО</th>
<th>Дата рождения</th>
<th class="action-column">&nbsp;</th>
</tr>
</thead><tbody>`;
for (let i = 1; i <= content.length; i++) {
let model = content[i - 1];
if (model["dob"].substr(8, 2) == date.substr(8, 2)) {
flag = true;
html += `<tr data-key="${model["id"]}">`
html += `<td>${i}</td>`
html += `<td>${model["fio"]}</td>`
html += `<td>${model["dob"]}</td>`
html += CalendarHelper._getActionColumn(`secure/calendar/calendar`,model[`id`])
html += `</tr>`
}
}
html += `</tbody></table>`
if (flag) return html;
return "empty"
}'
]) ?>

View File

@ -1,45 +1,25 @@
<?php <?php
/* @var $searchModel backend\modules\card\models\UserCardSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
use yii\grid\GridView;
use yii\helpers\Html; use yii\helpers\Html;
use yii\widgets\Pjax; use yii\helpers\Url;
$this->title = 'Календарь ДР';
?> ?>
<div style="display: flex;align-items: flex-start;"> <?= \backend\widgets\Calendar::widget([
<p>
<select id="options" class="btn btn-secondary dropdown-toggle"> 'css' => '.success{color: orange;}',
<option selected="selected" value="?month=00">Выберите месяц</option>
<option value="?month=00">Показать все</option> 'button' => Html::a('<i class="fa fa-table" aria-hidden="true"></i> Таблица',
<option value="?month=01">январь</option> ['table'], ['class' => 'btn btn-primary',]),
<option value="?month=02">февраль</option>
<option value="?month=03">март</option> 'monthUpdate' => [
<option value="?month=04">апрель</option> 'url' => Url::base() . '/calendar/ajax/get-birthday-dates-by-month'
<option value="?month=05">май</option>
<option value="?month=06">июнь</option>
<option value="?month=07">июль</option>
<option value="?month=08">август</option>
<option value="?month=09">сентябрь</option>
<option value="?month=10">октябрь</option>
<option value="?month=11">ноябрь</option>
<option value="?month=12">декабрь</option>
</select>
</p>
<?=Html::a('Календарь дней рождений '.Html::tag('i', null, ['class' => 'far fa-calendar-alt']),
['calendar'], ['class' => 'btn btn-success', 'style' => 'margin-left: 10px'])?>
</div>
<?php
Pjax::begin(['id' => 'reload']);
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'fio',
'dob',
['class' => 'yii\grid\ActionColumn'],
], ],
]); 'dayUpdate' => [
Pjax::end(); 'url' => Url::base() . '/calendar/ajax/get-birthday-date'
?> ],
'colorClasses' => ['accept' => 'success', 'default' => '', 'offDay' => ''],
'offDaysShow' => 0,
]) ?>

View File

@ -0,0 +1,45 @@
<?php
/* @var $searchModel backend\modules\card\models\UserCardSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
use yii\grid\GridView;
use yii\helpers\Html;
use yii\widgets\Pjax;
?>
<div style="display: flex;align-items: flex-start;">
<p>
<select id="options" class="btn btn-secondary dropdown-toggle">
<option selected="selected" value="?month=00">Выберите месяц</option>
<option value="?month=00">Показать все</option>
<option value="?month=01">январь</option>
<option value="?month=02">февраль</option>
<option value="?month=03">март</option>
<option value="?month=04">апрель</option>
<option value="?month=05">май</option>
<option value="?month=06">июнь</option>
<option value="?month=07">июль</option>
<option value="?month=08">август</option>
<option value="?month=09">сентябрь</option>
<option value="?month=10">октябрь</option>
<option value="?month=11">ноябрь</option>
<option value="?month=12">декабрь</option>
</select>
</p>
<?=Html::a('Календарь дней рождений '.Html::tag('i', null, ['class' => 'far fa-calendar-alt']),
['index'], ['class' => 'btn btn-success', 'style' => 'margin-left: 10px'])?>
</div>
<?php
Pjax::begin(['id' => 'reload']);
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'fio',
'dob',
['class' => 'yii\grid\ActionColumn'],
],
]);
Pjax::end();
?>

View File

@ -66,6 +66,13 @@ class UserCardSearch extends UserCard
if (isset($params['month'])) { if (isset($params['month'])) {
$query->andFilterWhere(['=', 'MONTH(dob)', $params['month']]); $query->andFilterWhere(['=', 'MONTH(dob)', $params['month']]);
} }
if (isset($params['day'])) {
$query->andFilterWhere(['=', 'DAY(dob)', $params['day']]);
}
if (isset($params['date'])) {
$query->andFilterWhere(['=', 'MONTH(dob)', substr($params['date'], 5,2)]);
$query->andFilterWhere(['=', 'DAY(dob)', substr($params['date'],8,2)]);
}
// grid filtering conditions // grid filtering conditions
$query->andFilterWhere([ $query->andFilterWhere([

View File

@ -2,35 +2,29 @@
namespace backend\modules\reports\controllers; namespace backend\modules\reports\controllers;
use backend\modules\reports\models\Month;
use Yii; use Yii;
use backend\modules\reports\models\ReportsSearch; use backend\modules\reports\models\ReportsSearch;
use yii\helpers\ArrayHelper;
use yii\web\Response; use yii\web\Response;
class AjaxController extends \yii\web\Controller class AjaxController extends \yii\web\Controller
{ {
public function actionGetReportsForMonthByIdYearMonth($user_id, $year, $month){ public function actionGetReportsForDayByDate($user_id, $date)
{
$searchModel = new ReportsSearch(); $searchModel = new ReportsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams); $params = ['ReportsSearch' => ['created_at' => $date], 'user_id' => $user_id];
$reports_array = ArrayHelper::toArray($dataProvider->getModels(), [ $dataProvider = $searchModel->search($params);
'common\models\Reports' => [ return $this->render('_gridView', [
'id', 'dataProvider' => $dataProvider
'created_at',
'difficulties',
'tomorrow',
'user_card_id',
'today' => function ($report) {
return ArrayHelper::toArray($report->task, [
'common\models\ReportsTask' => [
'hours_spent',
'task'
],
]); ]);
} }
],
]); public function actionGetReportsForMonthByIdYearMonth($user_id, $year, $month)
{
$searchModel = new ReportsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$reports_array = array_column($dataProvider->getModels(), 'created_at');
$response = Yii::$app->response; $response = Yii::$app->response;
$response->format = Response::FORMAT_JSON; $response->format = Response::FORMAT_JSON;

View File

@ -0,0 +1,34 @@
<?php
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */
echo GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute' => 'today',
'format' => 'raw',
'value' => function ($model) {
$text = '';
if ($model->task) {
$i = 1;
foreach ($model->task as $task) {
$text .= "<p>$i. ($task->hours_spent ч.) $task->task</p>";
$i++;
}
}
return $text;
}
],
'difficulties',
'tomorrow',
['class' => 'yii\grid\ActionColumn'],
],
]);
die();

View File

@ -2,6 +2,7 @@
use backend\widgets\Calendar; use backend\widgets\Calendar;
use yii\helpers\Html; use yii\helpers\Html;
use yii\helpers\Url;
/* @var $this yii\web\View */ /* @var $this yii\web\View */
/* @var $fio */ /* @var $fio */
@ -15,75 +16,15 @@ $this->title = 'Календарь пользователя - ' . $fio;
'button' => Html::a('<i class="fas fa-long-arrow-alt-left"></i> Назад', 'button' => Html::a('<i class="fas fa-long-arrow-alt-left"></i> Назад',
Yii::$app->request->referrer, ['class' => 'btn btn-primary',]), Yii::$app->request->referrer, ['class' => 'btn btn-primary',]),
'runBuild' => "function (date, content){ 'monthUpdate' => [
contentDays = [] 'url' => Url::base() . '/reports/ajax/get-reports-for-month-by-id-year-month',
for (let item of content){ 'data' => ['user_id' => $USER_ID]
contentDays.push(item['created_at']) ],
} 'dayUpdate' => [
this.build(date, contentDays) 'url' => Url::base() . '/reports/ajax/get-reports-for-day-by-date',
}", 'data' => ['user_id' => $USER_ID]
],
'colorClasses' => ['accept' => 'success', 'default' => 'danger', 'offDay' => ''],
'offDaysShow' => 1,
'updateContent' => "function(date){
let monthNumber = date.substr(5, 2);
let yearNumber = date.substr(0, 4);
return fetch('../ajax/get-reports-for-month-by-id-year-month?user_id='+".$USER_ID."+
'&month=' + monthNumber +
'&year=' + yearNumber)
.then((res) => {
return res.json()
})
}",
'getColor' => "function (date, dates = null) {
let d = date;
if ([6, 0].includes(d.getDay()))
return;
for (let i = 0; i < dates.length; i++) {
if (dates[i] == DateHelper.dateToString(date)) {
return 'success';
}
}
return 'danger';
}",
'getHtmlContentForDate' => "function (content, date) {
if ([0, 6].includes(new Date(date).getDay())) {
return 'Выходной день';
}
let j = 0;
let html = `<ul class='sidebar__list'>
<table class='table table-striped table-bordered'>
<thead>
<tr>
<th>#</th>
<th>Что было сделано сегодня?</th>
<th>Какие сложности возникли?</th>
<th>Что планируется сделать завтра?</th>
<th class='action-column'>&nbsp;</th>
</tr>
</thead>
<tbody>`;
for (let k = 0, i = 0; i < content.length; i++) {
let report = content[i];
if (report['created_at'] == date) {
k++;
html += `<tr data-key='\${report['id']}'>
<td>\${k}</td><td>`;
for (j = 0; j < Object.keys(report['today']).length; j++) {
html += `<p>\${j + 1}. (\${report['today'][j]['hours_spent']} ч.)
\${report['today'][j]['task']}</p>`
}
html += `</td>
<td>\${report['difficulties']}</td>
<td>\${report['tomorrow']}</td>
\${CalendarHelper._getActionColumn(`/secure/reports/reports`, report['id'])}`;
}
}
if (j == 0) {
return 'За этот день не было отчетов';
}
return html;
}"
]) ?> ]) ?>

View File

@ -13,30 +13,13 @@ class Calendar extends Widget
public $css; public $css;
public $runBuild = 'function (date, content){ public $dayUpdate;
this.build(date, content)
}';
public $updateContent = "function(){ public $monthUpdate;
return [];
/*
Example, return [model1, model2, model3 , ...] :
let monthNumber = date.substr(5, 2); public $colorClasses = ['accept' => 'access', 'default' => 'danger', 'offDay' => ''];
return fetch('../ajax/get-birthday-by-month?' +
'month=' + monthNumber)
.then((res) => {
return res.json()
})*/
}";
public $getColor = "function (date, dates = null) { public $offDaysShow = 1;
return `className`;
}";
public $getHtmlContentForDate = 'function (content, date) {
return `<div class="content">${content}</div>`;
}';
public $script = 'CalendarHelper.main()'; public $script = 'CalendarHelper.main()';
@ -62,12 +45,59 @@ class Calendar extends Widget
echo Html::beginTag('section', ['class' => 'calendar__days']); echo Html::beginTag('section', ['class' => 'calendar__days']);
echo Html::endTag('section'); echo Html::endTag('section');
echo Html::endTag('section'); echo Html::endTag('section');
$this->view->registerJs(' $this->view->registerJs('
CalendarHelper._runBuild = ' . $this->runBuild . '; CalendarHelper._getDayContent = async function(date){
CalendarHelper._getHtmlContentForDate = ' . $this->getHtmlContentForDate . '; let url = `'.$this->dayUpdate['url'].'?`;
CalendarHelper._updateContent = async ' . $this->updateContent . '; '.(isset($this->dayUpdate['data'])?'
CalendarHelper._getColor = ' . $this->getColor . '; let data = '.json_encode($this->dayUpdate['data']):'
let data = {};
').'
if(Object.keys(data).length){
for (let key in data){
url += key+`=`+ data[key]+`&`
}
}
return fetch(url+
`date=` + DateHelper.dateToString(date))
.then((res) => {
return res.text()
})
};
CalendarHelper._getMonth = async function(month, year){
let url = `'.$this->monthUpdate['url'].'?`;
'.(isset($this->monthUpdate['data'])?'
let data = '.json_encode($this->monthUpdate['data']):'
let data = {};
').'
if(Object.keys(data).length){
for (let key in data){
url += key+`=`+ data[key]+`&`
}
}
return fetch(url+
`&month=` + month +
`&year=` + year)
.then((res) => {
return res.json()
})
};
CalendarHelper._getColor = function (date, dates = null) {
if ('.$this->offDaysShow.')
if ([6, 0].includes(date.getDay()))
return `'.$this->colorClasses['offDay'].'`;
for (let i = 0; i<dates.length; i++){
if (dates[i] == DateHelper.dateToString(date)){
return `'.$this->colorClasses['accept'].'`
}
}
return `'.$this->colorClasses['default'].'`;
}
'.$this->script '.$this->script
); );

View File

@ -48,42 +48,44 @@ class CalendarHelper {
let nameDateBoard = document.querySelector('.sidebar__heading'); let nameDateBoard = document.querySelector('.sidebar__heading');
let contentBoard = document.querySelector('.sidebar__list'); let contentBoard = document.querySelector('.sidebar__list');
this._updateContent(datePicker.value) this._getMonth(datePicker.value.substr(5, 2), datePicker.value.substr(0, 4))
.then(content => { .then(dates => {
this._runBuild(DateHelper.stringToDate(datePicker.value), content) this.build(DateHelper.stringToDate(datePicker.value), dates)
datePicker.onchange = function (day = null) { datePicker.onchange = async function (day = null) {
let days = document.querySelectorAll('.calendar__day ') let days = document.querySelectorAll('.calendar__day ')
for (let i = 0; i < days.length; i++) { for (let i = 0; i < days.length; i++) {
if (parseInt(days[i].textContent)===parseInt(datePicker.value.substr(8,2))){ if (parseInt(days[i].textContent) === parseInt(datePicker.value.substr(8, 2)) &&
!days[i].classList.contains('inactive')) {
days[i].classList.add('active_day') days[i].classList.add('active_day')
} else } else if (days[i].classList.contains('active_day'))
if (days[i].classList.contains('active_day'))
days[i].classList.remove('active_day') days[i].classList.remove('active_day')
} }
if (!CalendarHelper.isOldDatePicker(datePicker, oldDate)) { if (!CalendarHelper.isOldDatePicker(datePicker, oldDate)) {
oldDate = datePicker.value.substr(0, 7); oldDate = datePicker.value.substr(0, 7);
CalendarHelper._updateContent(datePicker.value) CalendarHelper._getMonth(datePicker.value.substr(5, 2), datePicker.value.substr(0, 4))
.then(content => { .then(dates => {
CalendarHelper.main(day) CalendarHelper.main(day)
let date = new Date(datePicker.value); let date = new Date(datePicker.value);
let monthName = date.toLocaleString('default', {month: 'long'}); let monthName = date.toLocaleString('default', {month: 'long'});
let dayWeekName = date.toLocaleString('default', {weekday: 'long'}); let dayWeekName = date.toLocaleString('default', {weekday: 'long'});
nameDateBoard.innerHTML = `${dayWeekName} <br>${monthName} ${datePicker.value.substr(8, 2)}`; nameDateBoard.innerHTML = `${dayWeekName} <br>${monthName} ${datePicker.value.substr(8, 2)}`;
contentBoard.innerHTML = CalendarHelper._getHtmlContentForDate(content, datePicker.value) contentBoard.innerHTML = CalendarHelper._getHtmlContentForDate(dates, datePicker.value)
}) })
} }
let date = new Date(datePicker.value); let date = new Date(datePicker.value);
let monthName = date.toLocaleString('default', {month: 'long'}); let monthName = date.toLocaleString('default', {month: 'long'});
let dayWeekName = date.toLocaleString('default', {weekday: 'long'}); let dayWeekName = date.toLocaleString('default', {weekday: 'long'});
nameDateBoard.innerHTML = `${dayWeekName} <br>${monthName} ${datePicker.value.substr(8, 2)}`; nameDateBoard.innerHTML = `${dayWeekName} <br>${monthName} ${datePicker.value.substr(8, 2)}`;
contentBoard.innerHTML = CalendarHelper._getHtmlContentForDate(content, datePicker.value) contentBoard.innerHTML = await CalendarHelper._getDayContent(date)
} }
let days = document.querySelectorAll('.calendar__day'); let days = document.querySelectorAll('.calendar__day');
@ -125,10 +127,9 @@ class CalendarHelper {
} }
static static
async _updateContent(date) { async _getMonth(month, year) {
let monthNumber = date.substr(5, 2);
return fetch('../ajax/get-birthday-by-month?' + return fetch('../ajax/get-birthday-by-month?' +
'month=' + monthNumber) 'month=' + month)
.then((res) => { .then((res) => {
return res.json() return res.json()
}) })
@ -156,13 +157,19 @@ class CalendarHelper {
} }
static _getColor(date, dates = null) { static _getColor(date, dates = null) {
if (dates != null && dates.includes(DateHelper.dateToString(date))) { if (dates == null || dates.length == 0) {
return 'success'; return ``;
}
for (dateContent of dates){
if (dateContent['date'] == date){
return dateContent['class'];
}
}
return ``;
} }
if ([6, 0].includes(date.getDay()))
return;
return 'danger'; static async _getDayContent(date){
} }
static _getFutureDate(dat, value) { static _getFutureDate(dat, value) {
@ -218,3 +225,5 @@ class CalendarHelper {
} }
} }