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 @@
Goal completes when a session lasts at least this many seconds.
+Goal completes when a session views at least this many pages.
+Monetary value assigned to each conversion.
+{{ session('success') }}
+| Name | +Type | +Value | +Status | ++ |
|---|---|---|---|---|
| {{ $goal->name }} | +{{ $typeLabels[$goal->type] ?? $goal->type }} | +{{ $goal->default_value ? number_format($goal->default_value, 2) : '—' }} | ++ + {{ $goal->is_active ? 'Active' : 'Inactive' }} + + | ++ Edit + + | +
| Goal | +Type | +Completions | +Conversion Rate | +Value | +Status | +
|---|---|---|---|---|---|
| {{ $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' }} + + | +