This commit is contained in:
Stefanescu Mihai
2026-03-18 12:18:07 +02:00
parent a4383337f4
commit 6ad100d331
12 changed files with 513 additions and 77 deletions
@@ -0,0 +1,64 @@
<?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];
}
}
+3 -3
View File
@@ -31,11 +31,11 @@ class WebsiteController extends Controller
->with('success', 'Website added successfully.');
}
public function show(Website $website): View
public function show(Website $website): RedirectResponse
{
$this->authorize('view', $website);
return view('websites.show', compact('website'));
return redirect()->route('dashboard.show', $website);
}
public function edit(Website $website): View
@@ -54,7 +54,7 @@ class WebsiteController extends Controller
$website->update($data);
return redirect()
->route('websites.show', $website)
->route('dashboard.show', $website)
->with('success', 'Website updated successfully.');
}
+158
View File
@@ -0,0 +1,158 @@
<?php
namespace App\Services;
use App\Models\AnalyticsSession;
use App\Models\PageView;
use App\Models\Visitor;
use App\Models\Website;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class AnalyticsQueryService
{
public function __construct(
private readonly Website $website,
private readonly Carbon $from,
private readonly Carbon $to,
) {}
public static function for(Website $website, Carbon $from, Carbon $to): self
{
return new self($website, $from->startOfDay(), $to->endOfDay());
}
// ---- Summary Metrics ----
public function totalPageViews(): int
{
return PageView::where('website_id', $this->website->id)
->whereBetween('viewed_at', [$this->from, $this->to])
->count();
}
public function uniqueVisitors(): int
{
return PageView::where('website_id', $this->website->id)
->whereBetween('viewed_at', [$this->from, $this->to])
->distinct('visitor_id')
->count('visitor_id');
}
public function totalSessions(): int
{
return AnalyticsSession::where('website_id', $this->website->id)
->whereBetween('started_at', [$this->from, $this->to])
->count();
}
public function bounceRate(): float
{
$total = $this->totalSessions();
if ($total === 0) {
return 0;
}
$bounced = AnalyticsSession::where('website_id', $this->website->id)
->whereBetween('started_at', [$this->from, $this->to])
->where('is_bounce', true)
->count();
return round(($bounced / $total) * 100, 1);
}
public function avgSessionDuration(): float
{
return round(
(float) AnalyticsSession::where('website_id', $this->website->id)
->whereBetween('started_at', [$this->from, $this->to])
->avg('duration') ?? 0,
);
}
public function avgPagesPerSession(): float
{
return round(
(float) AnalyticsSession::where('website_id', $this->website->id)
->whereBetween('started_at', [$this->from, $this->to])
->avg('pages_count') ?? 0,
1,
);
}
public function summary(): array
{
return [
'page_views' => $this->totalPageViews(),
'visitors' => $this->uniqueVisitors(),
'sessions' => $this->totalSessions(),
'bounce_rate' => $this->bounceRate(),
'avg_duration' => $this->avgSessionDuration(),
'avg_pages' => $this->avgPagesPerSession(),
];
}
// ---- Time Series ----
public function visitorsOverTime(): Collection
{
$days = $this->from->diffInDays($this->to);
$groupFormat = $days <= 2 ? '%Y-%m-%d %H:00' : '%Y-%m-%d';
$carbonFormat = $days <= 2 ? 'Y-m-d H:00' : 'Y-m-d';
$pageViews = PageView::where('website_id', $this->website->id)
->whereBetween('viewed_at', [$this->from, $this->to])
->select(
DB::raw("strftime('{$groupFormat}', viewed_at) as period"),
DB::raw('COUNT(*) as page_views'),
DB::raw('COUNT(DISTINCT visitor_id) as visitors'),
)
->groupBy('period')
->orderBy('period')
->get()
->keyBy('period');
$sessions = AnalyticsSession::where('website_id', $this->website->id)
->whereBetween('started_at', [$this->from, $this->to])
->select(
DB::raw("strftime('{$groupFormat}', started_at) as period"),
DB::raw('COUNT(*) as sessions'),
)
->groupBy('period')
->orderBy('period')
->get()
->keyBy('period');
$periods = collect();
$cursor = $this->from->copy();
$increment = $days <= 2 ? 'addHour' : 'addDay';
while ($cursor->lte($this->to)) {
$key = $cursor->format($carbonFormat);
$pv = $pageViews->get($key);
$sess = $sessions->get($key);
$periods->push([
'period' => $key,
'page_views' => $pv ? $pv->page_views : 0,
'visitors' => $pv ? $pv->visitors : 0,
'sessions' => $sess ? $sess->sessions : 0,
]);
$cursor->$increment();
}
return $periods;
}
// ---- Real-Time ----
public static function activeVisitors(Website $website, int $minutes = 5): int
{
return AnalyticsSession::where('website_id', $website->id)
->where('ended_at', '>=', Carbon::now()->subMinutes($minutes))
->distinct('visitor_id')
->count('visitor_id');
}
}