diff --git a/PLAN.md b/PLAN.md index 407f351..bc56150 100644 --- a/PLAN.md +++ b/PLAN.md @@ -75,16 +75,16 @@ Individual report pages accessible from the dashboard sidebar. Allow users to define goals and track conversion rates. -- [ ] Build `GoalController` CRUD (create, edit, delete goals per website) -- [ ] Support goal types: +- [x] Build `GoalController` CRUD (create, edit, delete goals per website) +- [x] Support goal types: - **URL destination** — session visited a specific path - **Event match** — a specific event name/category was fired - **Duration** — session lasted longer than N seconds - **Pages per session** — session hit N+ page views -- [ ] Create a `GoalEvaluationService` that checks incoming data against active goals and records `GoalConversion` entries -- [ ] Hook goal evaluation into `CollectController` after recording page view / event -- [ ] Build a **Conversions report** — goal completion count, conversion rate (completions / sessions), goal value totals -- [ ] Add goal completion sparklines to the main dashboard +- [x] Create a `GoalEvaluationService` that checks incoming data against active goals and records `GoalConversion` entries +- [x] Hook goal evaluation into `CollectController` after recording page view / event +- [x] Build a **Conversions report** — goal completion count, conversion rate (completions / sessions), goal value totals +- [x] Add goal completion sparklines to the main dashboard --- diff --git a/app/Http/Controllers/CollectController.php b/app/Http/Controllers/CollectController.php index 657f3d0..fc49f1b 100644 --- a/app/Http/Controllers/CollectController.php +++ b/app/Http/Controllers/CollectController.php @@ -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]); } diff --git a/app/Http/Controllers/DashboardController.php b/app/Http/Controllers/DashboardController.php index dbb6e1b..5a02e76 100644 --- a/app/Http/Controllers/DashboardController.php +++ b/app/Http/Controllers/DashboardController.php @@ -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', )); } diff --git a/app/Http/Controllers/GoalController.php b/app/Http/Controllers/GoalController.php new file mode 100644 index 0000000..f347152 --- /dev/null +++ b/app/Http/Controllers/GoalController.php @@ -0,0 +1,78 @@ +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.'); + } +} diff --git a/app/Http/Controllers/ReportController.php b/app/Http/Controllers/ReportController.php index 5eae8d2..42c5afb 100644 --- a/app/Http/Controllers/ReportController.php +++ b/app/Http/Controllers/ReportController.php @@ -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(), + ]); + } } diff --git a/app/Http/Requests/StoreGoalRequest.php b/app/Http/Requests/StoreGoalRequest.php new file mode 100644 index 0000000..80b1f51 --- /dev/null +++ b/app/Http/Requests/StoreGoalRequest.php @@ -0,0 +1,34 @@ + ['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'], + ]; + } +} diff --git a/app/Http/Requests/UpdateGoalRequest.php b/app/Http/Requests/UpdateGoalRequest.php new file mode 100644 index 0000000..1f69ef2 --- /dev/null +++ b/app/Http/Requests/UpdateGoalRequest.php @@ -0,0 +1,34 @@ + ['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'], + ]; + } +} diff --git a/app/Services/AnalyticsQueryService.php b/app/Services/AnalyticsQueryService.php index 400ef47..cd5850d 100644 --- a/app/Services/AnalyticsQueryService.php +++ b/app/Services/AnalyticsQueryService.php @@ -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 diff --git a/app/Services/GoalEvaluationService.php b/app/Services/GoalEvaluationService.php new file mode 100644 index 0000000..dbd4e68 --- /dev/null +++ b/app/Services/GoalEvaluationService.php @@ -0,0 +1,114 @@ +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; + } +} diff --git a/resources/views/components/report-layout.blade.php b/resources/views/components/report-layout.blade.php index a56b6e8..6d59941 100644 --- a/resources/views/components/report-layout.blade.php +++ b/resources/views/components/report-layout.blade.php @@ -53,6 +53,11 @@

Events

Overview + +
+

Conversions

+ Goals +
diff --git a/resources/views/dashboard/show.blade.php b/resources/views/dashboard/show.blade.php index 22f538f..7894374 100644 --- a/resources/views/dashboard/show.blade.php +++ b/resources/views/dashboard/show.blade.php @@ -92,6 +92,44 @@ + {{-- Goal Completions --}} + @if ($goalConversions->isNotEmpty()) +
+
+

Goal Completions

+ +
+ +
+ @foreach ($goalConversions->where('is_active', true)->take(6) as $goal) +
+
+ {{ $goal->name }} + {{ $goal->conversion_rate }}% +
+
{{ number_format($goal->completions) }}
+ @if ($goal->total_value) +
${{ number_format($goal->total_value, 2) }} value
+ @endif +
+
+
+
+ @endforeach +
+ + {{-- Sparkline chart --}} + @if ($goalChartData->sum('completions') > 0) +
+ +
+ @endif +
+ @endif + {{-- Quick Report Links --}}

Reports

@@ -123,9 +161,11 @@
-

Events

+

Events & Conversions

Events Overview + Conversions + Manage Goals
@@ -218,6 +258,36 @@ }); }); + // Goal sparkline + const goalCanvas = document.getElementById('goal-sparkline'); + if (goalCanvas) { + const goalRaw = @json($goalChartData); + new Chart(goalCanvas, { + type: 'line', + data: { + labels: goalRaw.map(d => d.period), + datasets: [{ + data: goalRaw.map(d => d.completions), + borderColor: 'rgb(16, 185, 129)', + backgroundColor: 'rgba(16, 185, 129, 0.1)', + fill: true, + tension: 0.3, + pointRadius: 0, + borderWidth: 2, + }], + }, + options: { + responsive: true, + maintainAspectRatio: false, + plugins: { legend: { display: false }, tooltip: { enabled: false } }, + scales: { + x: { display: false }, + y: { display: false, beginAtZero: true }, + }, + }, + }); + } + function realtimeWidget(url) { return { count: {{ $activeVisitors }}, diff --git a/resources/views/goals/_form.blade.php b/resources/views/goals/_form.blade.php new file mode 100644 index 0000000..f17c59d --- /dev/null +++ b/resources/views/goals/_form.blade.php @@ -0,0 +1,95 @@ +@php + $goalType = old('type', $goal->type ?? ''); + $conditions = old('conditions', $goal->conditions ?? []); +@endphp + +
+
+ + + +
+ +
+ + + +
+ + {{-- URL Destination fields --}} +
+

URL Destination Conditions

+
+ + + +
+
+ + + +
+
+ + {{-- Event Match fields --}} +
+

Event Match Conditions

+
+ + + +
+
+ + + +
+
+ + {{-- Duration fields --}} +
+

Duration Condition

+
+ + +

Goal completes when a session lasts at least this many seconds.

+ +
+
+ + {{-- Pages per Session fields --}} +
+

Pages per Session Condition

+
+ + +

Goal completes when a session views at least this many pages.

+ +
+
+ +
+ + +

Monetary value assigned to each conversion.

+ +
+ +
+ +
+
diff --git a/resources/views/goals/create.blade.php b/resources/views/goals/create.blade.php new file mode 100644 index 0000000..bead744 --- /dev/null +++ b/resources/views/goals/create.blade.php @@ -0,0 +1,29 @@ + + +
+ + + + + +

Create Goal

+ {{ $website->domain }} +
+
+ +
+
+
+
+ @csrf + @include('goals._form', ['goal' => null]) + +
+ Create Goal + Cancel +
+
+
+
+
+
diff --git a/resources/views/goals/edit.blade.php b/resources/views/goals/edit.blade.php new file mode 100644 index 0000000..b39d5ac --- /dev/null +++ b/resources/views/goals/edit.blade.php @@ -0,0 +1,30 @@ + + +
+ + + + + +

Edit Goal: {{ $goal->name }}

+ {{ $website->domain }} +
+
+ +
+
+
+
+ @csrf + @method('PUT') + @include('goals._form', ['goal' => $goal]) + +
+ Save Changes + Cancel +
+
+
+
+
+
diff --git a/resources/views/goals/index.blade.php b/resources/views/goals/index.blade.php new file mode 100644 index 0000000..beaf4f0 --- /dev/null +++ b/resources/views/goals/index.blade.php @@ -0,0 +1,91 @@ + + +
+
+ + + + + +

Goals

+ {{ $website->domain }} +
+ + Add Goal + +
+
+ +
+
+ @if (session('success')) +
+

{{ session('success') }}

+
+ @endif + + @if ($goals->isEmpty()) +
+
+ + + +

No goals

+

Create goals to track conversions on your website.

+ +
+
+ @else +
+
+ + + + + + + + + + + + @php + $typeLabels = [ + 'url_destination' => 'URL Destination', + 'event_match' => 'Event Match', + 'duration' => 'Duration', + 'pages_per_session' => 'Pages / Session', + ]; + @endphp + @foreach ($goals as $goal) + + + + + + + + @endforeach + +
NameTypeValueStatus
{{ $goal->name }}{{ $typeLabels[$goal->type] ?? $goal->type }}{{ $goal->default_value ? number_format($goal->default_value, 2) : '—' }} + + {{ $goal->is_active ? 'Active' : 'Inactive' }} + + + Edit +
+ @csrf + @method('DELETE') + +
+
+
+
+ @endif +
+
+
diff --git a/resources/views/reports/conversions.blade.php b/resources/views/reports/conversions.blade.php new file mode 100644 index 0000000..1973cb6 --- /dev/null +++ b/resources/views/reports/conversions.blade.php @@ -0,0 +1,113 @@ + + +
+ {{-- Summary Cards --}} + @php + $totalCompletions = $goals->sum('completions'); + $totalValue = $goals->sum('total_value'); + $overallRate = $totalSessions > 0 ? round(($totalCompletions / $totalSessions) * 100, 2) : 0; + @endphp +
+
+
Total Completions
+
{{ number_format($totalCompletions) }}
+
+
+
Overall Conversion Rate
+
{{ $overallRate }}%
+
+
+
Total Goal Value
+
${{ number_format($totalValue, 2) }}
+
+
+ + {{-- Completions Chart --}} +
+

Goal Completions Over Time

+
+ +
+
+ + {{-- Per-Goal Table --}} +
+ @if ($goals->isEmpty()) +
+ No goals configured. + Create one. +
+ @else + @php + $typeLabels = [ + 'url_destination' => 'URL Destination', + 'event_match' => 'Event Match', + 'duration' => 'Duration', + 'pages_per_session' => 'Pages / Session', + ]; + @endphp +
+ + + + + + + + + + + + + @foreach ($goals as $goal) + + + + + + + + + @endforeach + +
GoalTypeCompletionsConversion RateValueStatus
{{ $goal->name }}{{ $typeLabels[$goal->type] ?? $goal->type }}{{ number_format($goal->completions) }}{{ $goal->conversion_rate }}%{{ $goal->total_value ? '$' . number_format($goal->total_value, 2) : '—' }} + + {{ $goal->is_active ? 'Active' : 'Inactive' }} + +
+
+ @endif +
+
+ + + + + + +
diff --git a/routes/web.php b/routes/web.php index b062bc1..6670236 100644 --- a/routes/web.php +++ b/routes/web.php @@ -38,6 +38,18 @@ Route::middleware(['auth', 'verified'])->group(function () { Route::get('events', [ReportController::class, 'events'])->name('events'); Route::get('events/{eventName}', [ReportController::class, 'eventDetail'])->name('event-detail'); + + Route::get('conversions', [ReportController::class, 'conversions'])->name('conversions'); + }); + + // Goals + Route::prefix('websites/{website}/goals')->name('goals.')->group(function () { + Route::get('/', [\App\Http\Controllers\GoalController::class, 'index'])->name('index'); + Route::get('create', [\App\Http\Controllers\GoalController::class, 'create'])->name('create'); + Route::post('/', [\App\Http\Controllers\GoalController::class, 'store'])->name('store'); + Route::get('{goal}/edit', [\App\Http\Controllers\GoalController::class, 'edit'])->name('edit'); + Route::put('{goal}', [\App\Http\Controllers\GoalController::class, 'update'])->name('update'); + Route::delete('{goal}', [\App\Http\Controllers\GoalController::class, 'destroy'])->name('destroy'); }); });