80 lines
3 KiB
PHP
80 lines
3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Http\Requests\StatsByBrandRequest;
|
|
use App\Http\Requests\StatsByQuestionRequest;
|
|
use App\Models\BrandStat;
|
|
use App\Models\CustomerAnswer;
|
|
use App\Models\Question;
|
|
use Illuminate\Support\Carbon;
|
|
|
|
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'));
|
|
}
|
|
|
|
public function viewByQuestion(StatsByQuestionRequest $request)
|
|
{
|
|
$question = null;
|
|
$answers = null;
|
|
$answersByDays = null;
|
|
if ($request->post()) {
|
|
$question = Question::findOrFail($request->question);
|
|
$answers = $question->answers;
|
|
|
|
// Totalize by date all answers
|
|
$answersByDays = CustomerAnswer::whereDate('created_at', '>=', $request->start)
|
|
->whereDate('created_at', '<=', $request->end)
|
|
->whereIn('answer_id', $answers->pluck('id'))
|
|
->get()->map(function ($custAnswer) {
|
|
return [
|
|
'answer_id' => $custAnswer->answer_id,
|
|
'created_at' => $custAnswer->created_at->format('Y-m-d'),
|
|
];
|
|
})->groupBy(['created_at', 'answer_id'])->map(function ($day) {
|
|
return $day->map(function ($custAnswers) {
|
|
return $custAnswers->count();
|
|
});
|
|
});
|
|
|
|
$start = Carbon::parse($request->start);
|
|
$end = Carbon::parse($request->end);
|
|
|
|
do {
|
|
$currentDate = $start->format('Y-m-d');
|
|
/** @var \Illuminate\Support\Collection $answersByDays */
|
|
if (!$answersByDays->has($currentDate)) {
|
|
$answersByDays->put(
|
|
$currentDate,
|
|
$answers->mapWithKeys(function ($answer) {
|
|
return [$answer->answer => 0];
|
|
})
|
|
);
|
|
} else {
|
|
$curentAnswers = $answersByDays->pull($currentDate);
|
|
$answersByDays->put(
|
|
$currentDate,
|
|
$answers->mapWithKeys(function ($answer) use ($curentAnswers) {
|
|
return [$answer->answer =>
|
|
$curentAnswers->has($answer->id) ?
|
|
$curentAnswers->get($answer->id) : 0];
|
|
})
|
|
);
|
|
}
|
|
|
|
$start = $start->addDay();
|
|
} while ($start->lessThanOrEqualTo($end));
|
|
}
|
|
|
|
return view('stats.view-stats-by-questions', \compact('question', 'answers', 'answersByDays'));
|
|
}
|
|
}
|