This commit is contained in:
Stefanescu Mihai
2026-03-18 16:59:39 +02:00
parent 274f6a378e
commit 9fb575ae70
17 changed files with 800 additions and 8 deletions
@@ -7,6 +7,7 @@ use App\Models\Event;
use App\Models\PageView;
use App\Models\Visitor;
use App\Models\Website;
use App\Services\GoalEvaluationService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
@@ -120,6 +121,10 @@ class CollectController extends Controller
'is_bounce' => $session->pageViews()->count() <= 1,
]);
$session->refresh();
app(GoalEvaluationService::class)->evaluate($website, $visitor, $session, $payload, $now);
return response()->json(['ok' => true]);
}
+4 -1
View File
@@ -23,9 +23,12 @@ class DashboardController extends Controller
$metrics = $service->summary();
$chartData = $service->visitorsOverTime();
$activeVisitors = AnalyticsQueryService::activeVisitors($website);
$goalConversions = $service->conversionsReport();
$goalChartData = $service->goalCompletionsOverTime();
return view('dashboard.show', compact(
'website', 'metrics', 'chartData', 'activeVisitors', 'from', 'to',
'website', 'metrics', 'chartData', 'activeVisitors',
'goalConversions', 'goalChartData', 'from', 'to',
));
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreGoalRequest;
use App\Http\Requests\UpdateGoalRequest;
use App\Models\Goal;
use App\Models\Website;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;
class GoalController extends Controller
{
public function index(Website $website): View
{
$this->authorize('view', $website);
$goals = $website->goals()->latest()->get();
return view('goals.index', compact('website', 'goals'));
}
public function create(Website $website): View
{
$this->authorize('view', $website);
return view('goals.create', compact('website'));
}
public function store(StoreGoalRequest $request, Website $website): RedirectResponse
{
$this->authorize('view', $website);
$data = $request->validated();
$data['is_active'] = $request->boolean('is_active', true);
$website->goals()->create($data);
return redirect()
->route('goals.index', $website)
->with('success', 'Goal created successfully.');
}
public function edit(Website $website, Goal $goal): View
{
$this->authorize('view', $website);
abort_unless($goal->website_id === $website->id, 404);
return view('goals.edit', compact('website', 'goal'));
}
public function update(UpdateGoalRequest $request, Website $website, Goal $goal): RedirectResponse
{
$this->authorize('view', $website);
abort_unless($goal->website_id === $website->id, 404);
$data = $request->validated();
$data['is_active'] = $request->boolean('is_active', true);
$goal->update($data);
return redirect()
->route('goals.index', $website)
->with('success', 'Goal updated successfully.');
}
public function destroy(Website $website, Goal $goal): RedirectResponse
{
$this->authorize('view', $website);
abort_unless($goal->website_id === $website->id, 404);
$goal->delete();
return redirect()
->route('goals.index', $website)
->with('success', 'Goal deleted successfully.');
}
}
+18
View File
@@ -193,4 +193,22 @@ class ReportController extends Controller
'trending' => $service->eventTrending($eventName),
]);
}
// ---- Conversions ----
public function conversions(Request $request, Website $website): View
{
$this->authorize('view', $website);
[$from, $to] = $this->parseDateRange($request);
$service = AnalyticsQueryService::for($website, $from, $to);
return view('reports.conversions', [
'website' => $website,
'from' => $from,
'to' => $to,
'goals' => $service->conversionsReport(),
'chartData' => $service->goalCompletionsOverTime(),
'totalSessions' => $service->totalSessions(),
]);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreGoalRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::in(['url_destination', 'event_match', 'duration', 'pages_per_session'])],
'default_value' => ['nullable', 'numeric', 'min:0'],
'is_active' => ['sometimes', 'boolean'],
'conditions.path' => ['required_if:type,url_destination', 'nullable', 'string', 'max:2048'],
'conditions.match_type' => ['required_if:type,url_destination', 'nullable', Rule::in(['exact', 'starts_with', 'contains', 'regex'])],
'conditions.event_name' => ['required_if:type,event_match', 'nullable', 'string', 'max:255'],
'conditions.event_category' => ['nullable', 'string', 'max:255'],
'conditions.seconds' => ['required_if:type,duration', 'nullable', 'integer', 'min:1'],
'conditions.page_count' => ['required_if:type,pages_per_session', 'nullable', 'integer', 'min:1'],
];
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateGoalRequest extends FormRequest
{
public function authorize(): bool
{
return true;
}
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'type' => ['required', Rule::in(['url_destination', 'event_match', 'duration', 'pages_per_session'])],
'default_value' => ['nullable', 'numeric', 'min:0'],
'is_active' => ['sometimes', 'boolean'],
'conditions.path' => ['required_if:type,url_destination', 'nullable', 'string', 'max:2048'],
'conditions.match_type' => ['required_if:type,url_destination', 'nullable', Rule::in(['exact', 'starts_with', 'contains', 'regex'])],
'conditions.event_name' => ['required_if:type,event_match', 'nullable', 'string', 'max:255'],
'conditions.event_category' => ['nullable', 'string', 'max:255'],
'conditions.seconds' => ['required_if:type,duration', 'nullable', 'integer', 'min:1'],
'conditions.page_count' => ['required_if:type,pages_per_session', 'nullable', 'integer', 'min:1'],
];
}
}
+61
View File
@@ -432,6 +432,67 @@ class AnalyticsQueryService
->get();
}
// ---- Conversions ----
public function conversionsReport(): Collection
{
$goals = \App\Models\Goal::where('website_id', $this->website->id)->get();
$totalSessions = $this->totalSessions();
return $goals->map(function ($goal) use ($totalSessions) {
$completions = \App\Models\GoalConversion::where('goal_id', $goal->id)
->whereBetween('converted_at', [$this->from, $this->to])
->count();
$totalValue = \App\Models\GoalConversion::where('goal_id', $goal->id)
->whereBetween('converted_at', [$this->from, $this->to])
->sum('value');
return (object) [
'id' => $goal->id,
'name' => $goal->name,
'type' => $goal->type,
'is_active' => $goal->is_active,
'completions' => $completions,
'conversion_rate' => $totalSessions > 0 ? round(($completions / $totalSessions) * 100, 2) : 0,
'total_value' => $totalValue,
];
});
}
public function goalCompletionsOverTime(): 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';
$data = \App\Models\GoalConversion::where('website_id', $this->website->id)
->whereBetween('converted_at', [$this->from, $this->to])
->select(
DB::raw("strftime('{$groupFormat}', converted_at) as period"),
DB::raw('COUNT(*) as completions'),
)
->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);
$periods->push([
'period' => $key,
'completions' => $data->get($key)?->completions ?? 0,
]);
$cursor->$increment();
}
return $periods;
}
// ---- Real-Time ----
public static function activeVisitors(Website $website, int $minutes = 5): int
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Services;
use App\Models\AnalyticsSession;
use App\Models\Goal;
use App\Models\GoalConversion;
use App\Models\Visitor;
use App\Models\Website;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
class GoalEvaluationService
{
public function evaluate(
Website $website,
Visitor $visitor,
AnalyticsSession $session,
array $payload,
Carbon $now,
): void {
$goals = $website->goals()->where('is_active', true)->get();
foreach ($goals as $goal) {
if ($this->alreadyConverted($goal, $session)) {
continue;
}
if ($this->matches($goal, $session, $payload)) {
GoalConversion::create([
'goal_id' => $goal->id,
'website_id' => $website->id,
'visitor_id' => $visitor->id,
'analytics_session_id' => $session->id,
'value' => $goal->default_value,
'converted_at' => $now,
]);
}
}
}
private function alreadyConverted(Goal $goal, AnalyticsSession $session): bool
{
return GoalConversion::where('goal_id', $goal->id)
->where('analytics_session_id', $session->id)
->exists();
}
private function matches(Goal $goal, AnalyticsSession $session, array $payload): bool
{
return match ($goal->type) {
'url_destination' => $this->matchesUrlDestination($goal, $payload),
'event_match' => $this->matchesEvent($goal, $payload),
'duration' => $this->matchesDuration($goal, $session),
'pages_per_session' => $this->matchesPagesPerSession($goal, $session),
default => false,
};
}
private function matchesUrlDestination(Goal $goal, array $payload): bool
{
$conditions = $goal->conditions;
$path = $payload['path'] ?? '';
$targetPath = $conditions['path'] ?? '';
$matchType = $conditions['match_type'] ?? 'exact';
if (! $path || ! $targetPath) {
return false;
}
return match ($matchType) {
'exact' => $path === $targetPath,
'starts_with' => str_starts_with($path, $targetPath),
'contains' => str_contains($path, $targetPath),
'regex' => (bool) @preg_match($targetPath, $path),
default => false,
};
}
private function matchesEvent(Goal $goal, array $payload): bool
{
if (($payload['type'] ?? '') !== 'event') {
return false;
}
$conditions = $goal->conditions;
$eventName = $conditions['event_name'] ?? '';
if (! $eventName || ($payload['event_name'] ?? '') !== $eventName) {
return false;
}
$requiredCategory = $conditions['event_category'] ?? null;
if ($requiredCategory && ($payload['event_category'] ?? '') !== $requiredCategory) {
return false;
}
return true;
}
private function matchesDuration(Goal $goal, AnalyticsSession $session): bool
{
$requiredSeconds = $goal->conditions['seconds'] ?? 0;
return $session->duration >= $requiredSeconds;
}
private function matchesPagesPerSession(Goal $goal, AnalyticsSession $session): bool
{
$requiredPages = $goal->conditions['page_count'] ?? 0;
return $session->pages_count >= $requiredPages;
}
}