Stats graphs

This commit is contained in:
Jérémy Munsch 2021-11-03 11:18:19 +01:00
parent 27fe3bcb34
commit 9f6ae7bd09
No known key found for this signature in database
GPG key ID: 55196BEE445F6049
9 changed files with 359 additions and 18 deletions

View file

@ -96,10 +96,7 @@ class CustomerController extends Controller
/** @var \Illuminate\Pagination\AbstractPaginator */
$customers = $query->paginate(config('crud.paginate', 50));
// use a crud controller (any) to gather crudModels
$modelsClasses = (new BrandController())->getCrudModels();
return view('customer.index', compact(
'modelsClasses',
'modelClass',
'modelTable',
'customers',
@ -114,10 +111,7 @@ class CustomerController extends Controller
$customerLogin = CustomerLogin::where('customer_id', $customer->id)
->where('brand_id', $brand->id)->first();
// use a crud controller (any) to gather crudModels
$modelsClasses = (new BrandController())->getCrudModels();
return view('customer.show', compact(
'modelsClasses',
'customerInfos',
'customerLogin'
));
@ -140,12 +134,9 @@ class CustomerController extends Controller
public function export()
{
// use a crud controller (any) to gather crudModels
$modelsClasses = (new BrandController())->getCrudModels();
$brands = Brand::all();
$brands = Brand::all();
return view('customer.export', compact(
'brands',
'modelsClasses'
'brands'
));
}

View file

@ -0,0 +1,20 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StatsByBrandRequest;
use App\Models\BrandStat;
class StatsController extends Controller
{
public function viewStatsByBrand(StatsByBrandRequest $request)
{
$stats = null;
if ($request->post()) {
$stats = BrandStat::whereDate('created_at', '>=', $request->start)
->whereDate('created_at', '<=', $request->end)
->whereBrandId($request->brand)->get();
}
return view('stats.view-stats-by-brands', \compact('stats'));
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace App\Http\Requests;
use Exception;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
class StatsByBrandRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return auth()->check();
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
if ($this->post()) {
try {
if ((Carbon::parse($this->end)->diffInDays(Carbon::parse($this->start)) + 1) > 365) {
throw ValidationException::withMessages([
'Vous devez sélectionner une période de maximum 1 ans'
]);
}
} catch (Exception $e) {
if (\get_class($e) !== ValidationException::class) {
throw ValidationException::withMessages([
'Les dates séléectionnées ne sembles pas être valides'
]);
}
throw $e;
}
return [
'brand' => 'required|exists:brands,id',
'start' => 'required|date|date_format:Y-m-d',
'end' => 'required|date|date_format:Y-m-d|after_or_equal:start',
];
}
return [];
}
}

View file

@ -2,13 +2,11 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
class BrandStat extends Model
{
use HasFactory;
public $timestamps = false;
@ -25,7 +23,9 @@ class BrandStat extends Model
protected static function booted()
{
static::creating(function (BrandStat $stat) {
$stat->created_at = Carbon::now();
if (!$stat->created_at) {
$stat->created_at = Carbon::now();
}
});
}

View file

@ -232,6 +232,7 @@ return [
'Brand' => App\Models\Brand::class,
'Customer' => App\Models\Customer::class,
'Answer' => App\Models\Answer::class,
'BrandController' => App\Http\Controllers\BrandController::class,
],
];

View file

@ -0,0 +1,50 @@
<?php
namespace Database\Seeders;
use App\Models\Brand;
use App\Models\BrandStat;
use Illuminate\Database\Seeder;
use Illuminate\Support\Carbon;
class BrandStatSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
BrandStat::truncate();
// on génère 2 an pour chaque marque
$brands = Brand::all();
/** @var \App\Models\Brand $brand*/
foreach ($brands as $brand) {
$startDay = Carbon::now();
$total = rand(100, 99999);
$active = rand(10, 89) / 100;
$new = rand(10, 89) / 100;
for ($i = 730; $i > 0; $i--) {
$total += floor($i / 2);
// pourcentage active
$pActive = $active * ((731 - $i) * 100 / 730);
// pourcentage nouveau
$pNew = $new * ($i * 100 / 730);
$brandStat = new BrandStat([
'active' => \floor($total * $pActive),
'inactive' => \ceil($total * $pActive),
'old_accounts' => \ceil($total * $pNew),
'new_accounts' => \floor($total * $pNew),
'total_accounts' => $total,
'total_opt_in' => ceil($total * 0.15) // 15% optin
]);
$brandStat->brand()->associate($brand);
$brandStat->created_at = $startDay;
$brandStat->save();
$startDay = $startDay->subDay();
}
}
}
}

View file

@ -9,17 +9,25 @@
<ul class="navbar-nav me-auto">
{{-- <li class="nav-item">Sample</li> --}}
</ul>
<ul class="navbar-nav ms-auto">
<ul class="navbar-nav me-auto ms-auto">
@auth()
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownExport" role="button"
<a class="nav-link @if(strpos('stats', request()->route()->getName()) === 0)active @endif" href="{{ route('stats.viewByBrand') }}">{{
__('Statistiques') }}</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link @if(in_array(request()->route()->getName(), ['customers.export', 'questions.export']))active @endif dropdown-toggle" href="#" id="navbarDarkDropdownExport" role="button"
data-bs-toggle="dropdown"
aria-expanded="false">{{ __('Exports') }}</a>
<ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownExport">
<li><a class="nav-link" href="{{ route('customers.export') }}">{{ __('Exporter un fichier CSV (newsletter)') }}</a></li>
<li><a class="nav-link" href="{{ route('questions.export') }}">{{ __('Exporter des questions') }}</a></li>
<li><a class="nav-link" href="{{ route('customers.export') }}">{{ __('Exporter des Clients') }}</a></li>
<li><a class="nav-link" href="{{ route('questions.export') }}">{{ __('Exporter des Questions/réponses') }}</a></li>
</ul>
</li>
@endauth
</ul>
<ul class="navbar-nav ms-auto">
@auth()
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button"
data-bs-toggle="dropdown"

View file

@ -0,0 +1,215 @@
@extends('layouts.app')
@section('title', __('Exporter stats par marque'))
@section('description', __('La page d\'export par marque avec un date donnée'))
@section('metaIndex', 'noindex,nofollow')
@section('content')
<div class="card">
@include('crud-policies::crud.modules.flashMessage')
<div class="card-header">
<nav aria-label="breadcrumb" class="d-inline">
<ol class="breadcrumb d-inline-flex">
<li class="breadcrumb-item"> {{ __('Statistiques') }} </li>
<li class="breadcrumb-item active" aria-current="page">{{__('Exporter un liste de client pour une newsletter') }}</li>
</ol>
</nav>
</div>
<div class="card-body">
<div class="row justify-content-end">
<div class="col-10">
<form action="{{ url()->current() }}" method="POST">
@csrf
<div class="input-group mb-3">
<button class="btn btn-secondary date today" type="button">{{ __('Aujourd\'hui') }}</button>
<button class="btn btn-secondary date month" type="button">{{ __('Ce mois-ci') }}</button>
<button class="btn btn-secondary date year" type="button">{{ __('Cette année') }}</button>
<span class="input-group-text">{{ __('Début') }}</span>
<input type="date" class="form-control date start" name="start" value="{{ request()->start ?? Carbon::now()->startOfMonth()->format('Y-m-d') }}" required>
<span class="input-group-text">{{ __('Fin') }}</span>
<input type="date" class="form-control date end" name="end" value="{{ request()->end ?? Carbon::now()->endOfMonth()->format('Y-m-d') }}" required>
<select name="brand" class="form-select" required>
<option value="" @if(!request()->brand) selected @endif>{{ __('Sélectionnez une marque') }}</option>
@foreach(Brand::all() as $brand)
<option value="{{ $brand->id }}" @if(request()->brand == $brand->id) selected @endif>{{ $brand->name }}</option>
@endforeach
</select>
<button type="submit" class="btn btn-primary">
{{ __('Visualiser') }}
</button>
</div>
</form>
</div>
</div>
@if($stats)
<div class="row justify-content-center">
<div class="col-10">
<canvas id="chart"></canvas>
</div>
</div>
@endif
</div>
</div>
@endsection
@push('scriptsConstants')
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.6.0/dist/chart.min.js" integrity="sha256-7lWo7cjrrponRJcS6bc8isfsPDwSKoaYfGIHgSheQkk=" crossorigin="anonymous"></script>
@endpush
@push('scripts')
<script>
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
document.addEventListener("DOMContentLoaded", function(event) {
let inputStart = document.getElementsByClassName('date start')[0];
let inputEnd = document.getElementsByClassName('date end')[0];
document.querySelectorAll('button.date').forEach((item) => {
item.addEventListener('click', (e) => {
if(e.target.classList.contains('today')) {
inputStart.value = (new Date()).getFromFormat('yyyy-mm-dd');
inputEnd.value = (new Date()).getFromFormat('yyyy-mm-dd');
return;
}
if(e.target.classList.contains('month')) {
inputStart.value = (new Date()).getFromFormat('yyyy-mm-') + '01';
inputEnd.value = (new Date()).getFromFormat('yyyy-mm-') +
new Date((new Date()).getFromFormat('yyyy'), (new Date()).getFromFormat('mm'), 0).getDate();
return;
}
if(e.target.classList.contains('year')) {
inputStart.value = (new Date()).getFromFormat('yyyy') + '-01-01';
inputEnd.value = (new Date()).getFromFormat('yyyy') + '-12-31';
return;
}
})
});
@if($stats)
let colors = {
active: '#EF476F',
inactive: '#FFD166',
old_accounts: '#06D6A0',
new_accounts: '#118AB2',
total_accounts: '#073B4C',
total_opt_in: '#EB5E28',
};
let chart = document.getElementById('chart');
if(chart) {
// Chart JS Thing
const config = {
type: 'line',
data: {
datasets: [
{
label: 'actifs',
borderColor: colors.active,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->active, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: false,
cubicInterpolationMode: 'monotone',
},
{
label: 'inactifs',
borderColor: colors.inactive,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->inactive, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: false,
cubicInterpolationMode: 'monotone',
},
{
label: 'vieux comptes',
borderColor: colors.old_accounts,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->old_accounts, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: false,
cubicInterpolationMode: 'monotone',
},
{
label: 'nouveaux comptes',
borderColor: colors.new_accounts,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->new_accounts, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: false,
cubicInterpolationMode: 'monotone',
},
{
label: 'total comptes',
borderColor: colors.total_accounts,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->total_accounts, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: true,
cubicInterpolationMode: 'monotone',
},
{
label: 'total optins',
borderColor: colors.total_opt_in,
data: @json($stats->map(function($brandStat) {
return ['y' => $brandStat->total_opt_in, 'x' => $brandStat->created_at->format('Y-m-d')];
})),
fill: false,
cubicInterpolationMode: 'monotone',
},
]
},
options: {
responsive: true,
@if(count($stats) < 180)
animation: true,
@else
// Turn off animations and data parsing for performance
animation: false,
@endif
parsing: true,
plugins: {
title: {
display: true,
text: '{{ __('Les statistiques crm par jour') }}'
},
decimation: {
enabled: false,
algorithm: 'min-max',
},
},
scales: {
x: {
display: true,
},
y: {
display: true,
beginAtZero: true,
type: 'logarithmic'
}
},
elements: {
point:{
radius: @if(count($stats) < 180) 3 @else 0 @endif
}
}
},
};
const chart = new Chart(
document.getElementById('chart'),
config
);
}
@endif
});
</script>
@endpush

View file

@ -7,6 +7,7 @@ use App\Http\Controllers\LoginController;
use App\Http\Controllers\QuestionController;
use App\Http\Controllers\ServiceController;
use App\Http\Controllers\SingleOptinController;
use App\Http\Controllers\StatsController;
use Illuminate\Support\Facades\Route;
/*
@ -58,4 +59,7 @@ Route::middleware(['auth'])->group(function () {
Route::post('/questions/export', [QuestionController::class, 'exportSubmit'])->name('questions.exportSubmit');
Route::resource('questions', QuestionController::class);
Route::resource('questions.answers', AnswerController::class);
// Stats
Route::match(['get', 'post'], '/stats', [StatsController::class, 'viewStatsByBrand'])->name('stats.viewByBrand');
});