@@ -46,7 +46,7 @@ public function getBaseQuery(array $dateRange, ?string $requestCategory = null):
4646 public function getSummary ($ query ): array
4747 {
4848 $ totalViews = (clone $ query )->count ();
49- $ uniqueVisitors = ( clone $ query )-> distinct ( ' visitor_id ' )-> count ( ' visitor_id ' );
49+ $ uniqueVisitors = $ this -> getUniqueVisitorCount ( $ query );
5050 $ uniqueSessions = (clone $ query )->distinct ('session_id ' )->count ('session_id ' );
5151 $ avgResponseTime = (clone $ query )->avg ('response_time ' );
5252
@@ -61,11 +61,7 @@ public function getSummary($query): array
6161 public function getChartData ($ query , array $ dateRange ): array
6262 {
6363 $ dateExpression = $ this ->getDateExpression ('visited_at ' );
64-
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 ;
64+ $ useSessionId = $ this ->shouldUseSessionId ($ query );
6965
7066 $ visitorCountExpression = $ useSessionId
7167 ? 'COUNT(DISTINCT session_id) as visitors '
@@ -294,6 +290,7 @@ protected function getCountriesData($query, bool $withPercentages): array
294290 public function getOperatingSystems ($ query , bool $ withPercentages = false ): array
295291 {
296292 $ totalVisitors = (clone $ query )->distinct ('session_id ' )->count ('session_id ' );
293+
297294 if ($ totalVisitors === 0 ) {
298295 return [];
299296 }
@@ -390,6 +387,27 @@ public function getDateExpression(string $column): string
390387 };
391388 }
392389
390+ protected function shouldUseSessionId ($ query ): bool
391+ {
392+ $ totalRecords = (clone $ query )->count ();
393+ if ($ totalRecords === 0 ) {
394+ return false ;
395+ }
396+
397+ $ validVisitorIds = (clone $ query )->whereNotNull ('visitor_id ' )->where ('visitor_id ' , '!= ' , '' )->count ();
398+
399+ return ($ validVisitorIds / $ totalRecords ) < 0.5 ;
400+ }
401+
402+ public function getUniqueVisitorCount ($ query ): int
403+ {
404+ if ($ this ->shouldUseSessionId ($ query )) {
405+ return (clone $ query )->distinct ('session_id ' )->count ('session_id ' );
406+ }
407+
408+ return (clone $ query )->distinct ('visitor_id ' )->count ('visitor_id ' );
409+ }
410+
393411 public function getDomainExpression (string $ column ): string
394412 {
395413 $ connection = config ('request-analytics.database.connection ' );
0 commit comments