Skip to content

Commit 6738752

Browse files
committed
fix: views and visitor count issue
1 parent 8404615 commit 6738752

2 files changed

Lines changed: 22 additions & 3 deletions

File tree

src/Services/AnalyticsService.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,20 @@ public function getChartData($query, array $dateRange): array
6262
{
6363
$dateExpression = $this->getDateExpression('visited_at');
6464

65+
// Check if we should use session_id instead of visitor_id for counting
66+
$totalRecords = (clone $query)->count();
67+
$validVisitorIds = (clone $query)->whereNotNull('visitor_id')->where('visitor_id', '!=', '')->count();
68+
$useSessionId = $totalRecords > 0 && ($validVisitorIds / $totalRecords) < 0.5;
69+
70+
$visitorCountExpression = $useSessionId
71+
? 'COUNT(DISTINCT session_id) as visitors'
72+
: 'COUNT(DISTINCT visitor_id) as visitors';
73+
6574
$data = (clone $query)
6675
->select(
6776
DB::raw("{$dateExpression} as date"),
6877
DB::raw('COUNT(*) as views'),
69-
DB::raw('COUNT(DISTINCT visitor_id) as visitors')
78+
DB::raw($visitorCountExpression)
7079
)
7180
->groupBy(DB::raw($dateExpression))
7281
->orderBy('date')

src/Services/DashboardAnalyticsService.php

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,8 +115,18 @@ protected function getAverage(): array
115115
$startDate = $dateRange['start'];
116116
$baseQuery = $this->getBaseQuery($dateRange);
117117

118-
$totalViews = $baseQuery->count();
119-
$uniqueVisitors = $baseQuery->distinct('visitor_id')->count('visitor_id');
118+
$totalViews = (clone $baseQuery)->count();
119+
120+
// Try to count unique visitors by visitor_id, fallback to session_id if visitor_id is mostly null/empty
121+
$visitorIdCount = (clone $baseQuery)->whereNotNull('visitor_id')->where('visitor_id', '!=', '')->distinct('visitor_id')->count('visitor_id');
122+
$totalRecords = (clone $baseQuery)->count();
123+
124+
// If less than 50% of records have valid visitor_id, use session_id instead
125+
if ($totalRecords > 0 && ($visitorIdCount / $totalRecords) < 0.5) {
126+
$uniqueVisitors = (clone $baseQuery)->distinct('session_id')->count('session_id');
127+
} else {
128+
$uniqueVisitors = (clone $baseQuery)->distinct('visitor_id')->count('visitor_id');
129+
}
120130

121131
// Calculate bounce rate (percentage of sessions with only one page view)
122132
$tableName = config('request-analytics.database.table', 'request_analytics');

0 commit comments

Comments
 (0)