65 lines
1.8 KiB
PHP
65 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Website;
|
|
use App\Services\AnalyticsQueryService;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Carbon;
|
|
use Illuminate\View\View;
|
|
|
|
class DashboardController extends Controller
|
|
{
|
|
public function show(Request $request, Website $website): View
|
|
{
|
|
$this->authorize('view', $website);
|
|
|
|
[$from, $to] = $this->parseDateRange($request);
|
|
|
|
$service = AnalyticsQueryService::for($website, $from, $to);
|
|
$metrics = $service->summary();
|
|
$chartData = $service->visitorsOverTime();
|
|
$activeVisitors = AnalyticsQueryService::activeVisitors($website);
|
|
|
|
return view('dashboard.show', compact(
|
|
'website', 'metrics', 'chartData', 'activeVisitors', 'from', 'to',
|
|
));
|
|
}
|
|
|
|
public function realtime(Website $website): JsonResponse
|
|
{
|
|
$this->authorize('view', $website);
|
|
|
|
return response()->json([
|
|
'active' => AnalyticsQueryService::activeVisitors($website),
|
|
]);
|
|
}
|
|
|
|
private function parseDateRange(Request $request): array
|
|
{
|
|
$range = $request->get('range', '7d');
|
|
|
|
$to = Carbon::today();
|
|
|
|
$from = match ($range) {
|
|
'today' => Carbon::today(),
|
|
'7d' => Carbon::today()->subDays(6),
|
|
'30d' => Carbon::today()->subDays(29),
|
|
'90d' => Carbon::today()->subDays(89),
|
|
'custom' => Carbon::parse($request->get('from', Carbon::today()->subDays(6)->toDateString())),
|
|
default => Carbon::today()->subDays(6),
|
|
};
|
|
|
|
if ($range === 'custom' && $request->has('to')) {
|
|
$to = Carbon::parse($request->get('to'));
|
|
}
|
|
|
|
if ($from->gt($to)) {
|
|
[$from, $to] = [$to, $from];
|
|
}
|
|
|
|
return [$from, $to];
|
|
}
|
|
}
|