Skip to content

Commit

Permalink
Merge pull request #1 from irfanasri96/master
Browse files Browse the repository at this point in the history
feat: add date range filter on graft
  • Loading branch information
mazfreelance authored Nov 25, 2021
2 parents 867c824 + 48db8f3 commit 714042f
Show file tree
Hide file tree
Showing 10 changed files with 189 additions and 46 deletions.
22 changes: 16 additions & 6 deletions src/components/panels/RendersSummaryChartTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,31 @@ protected function getChartModel()
*
* @return array
*/
protected function getChartData()
protected function getChartData($start = null, $end = null)
{
//initialise defaults (0 entries) for each day
$defaults = [];
$startDate = strtotime('-6 days');
foreach (range(-6, 0) as $day) {
$defaults[date('D: Y-m-d', strtotime($day . 'days'))] = 0;
if(!$start && !$end) {
$startDate = date('Y-m-d 00:00:00', strtotime('-6 days'));
$endDate = date('Y-m-d 23:59:59');
foreach (range(-6, 0) as $day) {
$defaults[date('D: Y-m-d', strtotime($day . 'days'))] = 0;
}
} else {
$startDate = date('Y-m-d 00:00:00', strtotime($start));
$endDate = date('Y-m-d 23:59:59', strtotime($end));
$days = round(((strtotime($endDate) - strtotime($startDate))/ (60 * 60 * 24))-1);
foreach (range(0, $days) as $day) {
$defaults[date('D: Y-m-d', strtotime($startDate.'+' .$day . 'days'))] = 0;
}
}

$panelModel = $this->getChartModel();
$results = $panelModel::find()
->select(["COUNT(DISTINCT id) as count", "created AS day"])
->where(['between', 'created',
date('Y-m-d 00:00:00', $startDate),
date('Y-m-d 23:59:59')])
$startDate,
$endDate])
->groupBy("created")->indexBy('day')->column();

// replace defaults with data from db where available
Expand Down
13 changes: 11 additions & 2 deletions src/controllers/DefaultController.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use bedezign\yii2\audit\components\panels\RendersSummaryChartTrait;
use bedezign\yii2\audit\components\web\Controller;
use bedezign\yii2\audit\models\AuditEntry;
use bedezign\yii2\audit\models\AuditEntrySearch;
use bedezign\yii2\audit\models\AuditTrailSearch;
use Yii;

/**
Expand All @@ -21,8 +23,15 @@ class DefaultController extends Controller
*/
public function actionIndex()
{
$chartData = $this->getChartData();
return $this->render('index', ['chartData' => $chartData]);
$startDate = $endDate = null;
$searchModel = new AuditEntrySearch();
if(isset(Yii::$app->request->queryParams['AuditEntrySearch'])){
$startDate = Yii::$app->request->queryParams['AuditEntrySearch']['start_date'];
$endDate = Yii::$app->request->queryParams['AuditEntrySearch']['end_date'];
}
$chartData = $this->getChartData($startDate, $endDate);
$searchTrailModel = new AuditTrailSearch();
return $this->render('index', ['model' => $searchModel, 'chartData' => $chartData, 'trailModel' => $searchTrailModel]);
}

protected function getChartModel()
Expand Down
19 changes: 17 additions & 2 deletions src/models/AuditEntrySearch.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
*/
class AuditEntrySearch extends AuditEntry
{
public $start_date, $end_date;
/**
* @return array
*/
public function rules()
{
// only fields in rules() are searchable
return [
[['id', 'user_id', 'ip', 'created', 'duration', 'memory_max', 'route', 'request_method', 'ajax'], 'safe'],
[['id', 'user_id', 'ip', 'created', 'duration', 'memory_max', 'route', 'request_method', 'ajax', 'start_date', 'end_date'], 'safe'],
['start_date', 'validateDate'],
['end_date', 'validateDate']
];
}

Expand All @@ -39,7 +42,9 @@ public function scenarios()
*/
public function search($params)
{
$query = AuditEntry::find()->where(['NOT LIKE', 'route', 'site/login']);
$query = AuditEntry::find()
->where(['NOT LIKE', 'route', 'site/login'])
->andWhere(['NOT LIKE', 'request_method', 'CLI']);

$dataProvider = new ActiveDataProvider([
'query' => $query,
Expand Down Expand Up @@ -103,6 +108,15 @@ public function searchAccessLog($params)
return $dataProvider;
}

public function validateDate($attribute)
{
$dateTime = DateTime::createFromFormat('Y/m/d', $this->$attribute);
$errors = DateTime::getLastErrors();
if (!empty($errors['warning_count'])) {
$this->addError($attribute, 'Invalid date');
}
}

/**
* @return array
*/
Expand All @@ -125,6 +139,7 @@ static public function methodFilter()
$methods = AuditEntry::getDb()->cache(function () {
return AuditEntry::find()->distinct(true)
->select('request_method')->where(['is not', 'request_method', null])
->where(['NOT LIKE', 'request_method', 'CLI'])
->groupBy('request_method')->orderBy('request_method ASC')->column();
}, 240);
return array_combine($methods, $methods);
Expand Down
30 changes: 24 additions & 6 deletions src/models/AuditTrailSearch.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace bedezign\yii2\audit\models;


use bedezign\yii2\audit\Audit;
use yii\base\Model;
use yii\data\ActiveDataProvider;

Expand All @@ -12,14 +12,15 @@
*/
class AuditTrailSearch extends AuditTrail
{
public $start_date, $end_date;
/**
* @return array
*/
public function rules()
{
// Note: The model is used by both the entry and the trail index pages, hence the separate use of `id` and `entry_id`
return [
[['id', 'user_id', 'entry_id', 'action', 'model', 'model_id', 'field', 'created'], 'safe'],
[['id', 'user_id', 'entry_id', 'action', 'model', 'model_id', 'field', 'created', 'start_date', 'end_date'], 'safe'],
];
}

Expand Down Expand Up @@ -56,13 +57,14 @@ public function search($params, $query = null)
}

// adjust the query by adding the filters
$userId = $this->user_id;
if (strlen($this->user_id))
$userId = intval($this->user_id) ?: 0;
// $userId = $this->user_id;
// if (strlen($this->user_id))
// $userId = intval($this->user_id) ?: 0;

$query->andFilterWhere(['id' => $this->id]);
$this->filterUserId($this->user_id, $query);
$query->andFilterWhere(['entry_id' => $this->entry_id]);
$query->andFilterWhere(['user_id' => $userId]);
// $query->andFilterWhere(['user_id' => $userId]);
$query->andFilterWhere(['action' => $this->action]);
$query->andFilterWhere(['like', 'model', $this->model]);
$query->andFilterWhere(['model_id' => $this->model_id]);
Expand All @@ -87,4 +89,20 @@ static public function actionFilter()
'action'
);
}

/**
* @param $userId
* @param ActiveQuery $query
*/
protected function filterUserId($userId, $query)
{
if (strlen($userId)) {
if (!is_numeric($userId) && $callback = Audit::getInstance()->userFilterCallback) {
$userId = call_user_func($callback, $userId);
} else {
$userId = intval($userId) ?: 0;
}
$query->andWhere(['user_id' => $userId]);
}
}
}
12 changes: 9 additions & 3 deletions src/panels/TrailPanel.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,17 @@ protected function getChartModel()
/**
* @inheritdoc
*/
public function getChart()
public function getChart($request = null)
{
$start = $end = null;
if($request){
$start = Yii::$app->request->queryParams['AuditTrailSearch']['start_date'];
$end = Yii::$app->request->queryParams['AuditTrailSearch']['end_date'];
}

return \Yii::$app->view->render('panels/trail/chart', [
'panel' => $this,
'chartData' => $this->getChartData()
'start' => $start,
'end' => $end,
]);
}

Expand Down
79 changes: 74 additions & 5 deletions src/views/default/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@
use bedezign\yii2\audit\components\panels\Panel;
use dosamigos\chartjs\ChartJs;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\View;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('audit', 'Audit Module');
$this->title = Yii::t('audit', 'Summary');
$this->params['breadcrumbs'][] = $this->title;

$this->registerCss('canvas {width: 100% !important;height: 400px;}');
Expand All @@ -19,8 +21,35 @@

<div class="row">
<div class="col-md-12 col-lg-12">
<h2><?php echo Html::a(Yii::t('audit', 'Entries'), ['entry/index']); ?></h2>
<?php $form = ActiveForm::begin([
'id' => 'entryform',
'action' => [$this->context->action->id],
'method' => 'get',
'options' => [
'class' => 'form-inline'
],
]); ?>

<?= $form->field($model, 'start_date', ['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control', 'style' => 'margin-right: 10px;']])
->textInput()->textInput(['placeholder' => "Start Date"])
->label(false)
?>

<?= $form->field($model, 'end_date',
['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control', 'style' => 'margin-right: 10px;']])
->textInput()->textInput(['placeholder' => "End Date"])
->label(false)
?>


<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary', 'style' => 'margin-top: -10px']) ?>

<?php ActiveForm::end(); ?>
</div>

<div class="col-md-12 col-lg-12">
<h2><?php echo Html::a(Yii::t('audit', 'Activity Log'), ['entry/index']); ?></h2>

<div class="well">
<?php

Expand Down Expand Up @@ -51,17 +80,56 @@
</div>

<?php

foreach (Audit::getInstance()->panels as $panel) {
/** @var Panel $panel */
$chart = $panel->getChart();
if($panel->getName() == 'Trails'){
$request = null;
if(isset(Yii::$app->request->queryParams['AuditTrailSearch'])){
$request = Yii::$app->request->queryParams['AuditTrailSearch'];
}
$chart = $panel->getChart($request);
} else {
$chart = $panel->getChart();
}

if (!$chart) {
continue;
}
$indexUrl = $panel->getIndexUrl();
?>
<div class="col-md-3 col-lg-3">
<h2><?php echo $indexUrl ? Html::a($panel->getName(), $indexUrl) : $panel->getName(); ?></h2>
<div class="col-md-12 col-lg-12">
<?php
$title = $panel->getName();
if($panel->getName() == 'Trails'){
$title = Yii::t('audit', 'Database Log');
}
?>
<h2><?php echo $indexUrl ? Html::a($title, $indexUrl) : $title; ?></h2>
<?php $form = ActiveForm::begin([
'id' => 'trailform',
'action' => [$this->context->action->id],
'method' => 'get',
'options' => [
'class' => 'form-inline'
],
]); ?>

<?= $form->field($trailModel, 'start_date', ['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control', 'style' => 'margin-right: 10px;']])
->textInput()->textInput(['placeholder' => "Start Date"])
->label(false)
?>

<?= $form->field($trailModel, 'end_date',
['inputOptions' => ['autofocus' => 'autofocus', 'class' => 'form-control', 'style' => 'margin-right: 10px;']])
->textInput()->textInput(['placeholder' => "End Date"])
->label(false)
?>


<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary', 'style' => 'margin-top: -10px']) ?>

<?php ActiveForm::end(); ?>
<div class="well">
<?php echo $chart; ?>
</div>
Expand All @@ -71,3 +139,4 @@
</div>

</div>

43 changes: 27 additions & 16 deletions src/views/default/panels/trail/chart.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,45 +6,56 @@
use dosamigos\chartjs\ChartJs;

//initialise defaults (0 entries) for each day
// dd($chartData);
$defaults = [];
$startDate = strtotime('-6 days');
foreach (range(-6, 0) as $day) {
$defaults[date('D: Y-m-d', strtotime($day . 'days'))] = 0;
if(!$start && !$end) {
$startDate = date('Y-m-d 00:00:00', strtotime('-6 days'));
$endDate = date('Y-m-d 23:59:59');
foreach (range(-6, 0) as $day) {
$defaults[date('D: Y-m-d', strtotime($day . 'days'))] = 0;
}
} else {
$startDate = date('Y-m-d 00:00:00', strtotime($start));
$endDate = date('Y-m-d 23:59:59', strtotime($end));
$days = round(((strtotime($endDate) - strtotime($startDate))/ (60 * 60 * 24))-1);
foreach (range(0, $days) as $day) {
$defaults[date('D: Y-m-d', strtotime($startDate.'+' .$day . 'days'))] = 0;
}
}

$results = AuditTrail::find()
->select(["COUNT(DISTINCT id) as count", "created AS day"])
->where(['between', 'created',
date('Y-m-d 00:00:00', $startDate),
date('Y-m-d 23:59:59')])
$startDate,
$endDate])
->groupBy("created")->indexBy('day')->column();

// format dates properly
$formattedData = [];
foreach ($results as $date => $count) {
$date = date('D: Y-m-d', strtotime($date));
$formattedData[$date] = $count;
$defaults[$date] += $count;
}
$results = $formattedData;

// replace defaults with data from db where available
$results = array_merge($defaults, $results);

// return $defaults;
// dd($defaults);
echo ChartJs::widget([
'type' => 'bar',
'options' => [
'height' => '400',
],
'clientOptions' => [
'legend' => ['display' => false],
'tooltips' => ['enabled' => false],
],
'data' => [
'labels' => array_keys($chartData),
'labels' => array_keys($defaults),
'datasets' => [
[
'fillColor' => 'rgba(151,187,205,0.5)',
'strokeColor' => 'rgba(151,187,205,1)',
'pointColor' => 'rgba(151,187,205,1)',
'fillColor' => 'rgba(255, 99, 71, 0.8)',
'strokeColor' => 'rgba(255, 99, 71, 0.8)',
'pointColor' => 'rgba(255, 99, 71, 0.8)',
'pointStrokeColor' => '#fff',
'data' => array_values($chartData),
'data' => array_values($defaults),
],
],
]
Expand Down
Loading

0 comments on commit 714042f

Please sign in to comment.