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

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 Yii;
use yii\helpers\ArrayHelper;
use yii\web\Response;
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();
$models = $searchModel->search(Yii::$app->request->queryParams)->getModels();
$models_array = ArrayHelper::toArray($models, [
'backend\modules\card\models\UserCard' => [
'id',
'dob',
'fio'
],
]);
$models_array = array_map(function ($date){return date('Y').substr($date, 4,6);},
array_column($models, 'dob')
);
$response = Yii::$app->response;
$response->format = Response::FORMAT_JSON;

View File

@ -42,11 +42,11 @@ class CalendarController extends Controller
* Renders the index view for the module
* @return string
*/
public function actionCalendar(){
return $this->render('calendar');
public function actionIndex(){
return $this->render('index');
}
public function actionIndex()
public function actionTable()
{
$searchModel = new UserCardSearch();
$user_card = \common\models\UserCard::find()->all();
@ -67,7 +67,7 @@ class CalendarController extends Controller
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
}
return $this->render('index', [
return $this->render('table', [
'searchModel' => $searchModel,
'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
/* @var $searchModel backend\modules\card\models\UserCardSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
use yii\grid\GridView;
use yii\helpers\Html;
use yii\widgets\Pjax;
use yii\helpers\Url;
$this->title = 'Календарь ДР';
?>
<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']),
['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'],
<?= \backend\widgets\Calendar::widget([
'css' => '.success{color: orange;}',
'button' => Html::a('<i class="fa fa-table" aria-hidden="true"></i> Таблица',
['table'], ['class' => 'btn btn-primary',]),
'monthUpdate' => [
'url' => Url::base() . '/calendar/ajax/get-birthday-dates-by-month'
],
]);
Pjax::end();
?>
'dayUpdate' => [
'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'])) {
$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
$query->andFilterWhere([

View File

@ -2,35 +2,29 @@
namespace backend\modules\reports\controllers;
use backend\modules\reports\models\Month;
use Yii;
use backend\modules\reports\models\ReportsSearch;
use yii\helpers\ArrayHelper;
use yii\web\Response;
class AjaxController extends \yii\web\Controller
{
public function actionGetReportsForMonthByIdYearMonth($user_id, $year, $month){
public function actionGetReportsForDayByDate($user_id, $date)
{
$searchModel = new ReportsSearch();
$params = ['ReportsSearch' => ['created_at' => $date], 'user_id' => $user_id];
$dataProvider = $searchModel->search($params);
return $this->render('_gridView', [
'dataProvider' => $dataProvider
]);
}
public function actionGetReportsForMonthByIdYearMonth($user_id, $year, $month)
{
$searchModel = new ReportsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$reports_array = ArrayHelper::toArray($dataProvider->getModels(), [
'common\models\Reports' => [
'id',
'created_at',
'difficulties',
'tomorrow',
'user_card_id',
'today' => function ($report) {
return ArrayHelper::toArray($report->task, [
'common\models\ReportsTask' => [
'hours_spent',
'task'
],
]);
}
],
]);
$reports_array = array_column($dataProvider->getModels(), 'created_at');
$response = Yii::$app->response;
$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 yii\helpers\Html;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $fio */
@ -10,80 +11,20 @@ use yii\helpers\Html;
$this->title = 'Календарь пользователя - ' . $fio;
?>
<?=Calendar::widget([
<?= Calendar::widget([
'button' => Html::a('<i class="fas fa-long-arrow-alt-left"></i> Назад',
Yii::$app->request->referrer, ['class' => 'btn btn-primary',]),
'runBuild' => "function (date, content){
contentDays = []
for (let item of content){
contentDays.push(item['created_at'])
}
this.build(date, contentDays)
}",
'monthUpdate' => [
'url' => Url::base() . '/reports/ajax/get-reports-for-month-by-id-year-month',
'data' => ['user_id' => $USER_ID]
],
'dayUpdate' => [
'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 $runBuild = 'function (date, content){
this.build(date, content)
}';
public $dayUpdate;
public $updateContent = "function(){
return [];
/*
Example, return [model1, model2, model3 , ...] :
let monthNumber = date.substr(5, 2);
return fetch('../ajax/get-birthday-by-month?' +
'month=' + monthNumber)
.then((res) => {
return res.json()
})*/
}";
public $monthUpdate;
public $getColor = "function (date, dates = null) {
return `className`;
}";
public $colorClasses = ['accept' => 'access', 'default' => 'danger', 'offDay' => ''];
public $getHtmlContentForDate = 'function (content, date) {
return `<div class="content">${content}</div>`;
}';
public $offDaysShow = 1;
public $script = 'CalendarHelper.main()';
@ -62,12 +45,59 @@ class Calendar extends Widget
echo Html::beginTag('section', ['class' => 'calendar__days']);
echo Html::endTag('section');
echo Html::endTag('section');
$this->view->registerJs('
CalendarHelper._runBuild = ' . $this->runBuild . ';
CalendarHelper._getHtmlContentForDate = ' . $this->getHtmlContentForDate . ';
CalendarHelper._updateContent = async ' . $this->updateContent . ';
CalendarHelper._getColor = ' . $this->getColor . ';
CalendarHelper._getDayContent = async function(date){
let url = `'.$this->dayUpdate['url'].'?`;
'.(isset($this->dayUpdate['data'])?'
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
);

View File

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