diff --git a/app/Http/Controllers/Counter/CounterController.php b/app/Http/Controllers/Counter/CounterController.php index ac95193d69..a005b599dc 100644 --- a/app/Http/Controllers/Counter/CounterController.php +++ b/app/Http/Controllers/Counter/CounterController.php @@ -35,25 +35,31 @@ use App\Models\Visitor; use App\Models\CounterPage; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use App\Http\Controllers\Controller; use App\Models\Profil; class CounterController extends Controller { + private const CACHE_TOP_PAGES = 'counter.top_pages'; + + private const CACHE_TTL_MINUTES = 5; + public function index() { $page_title = 'Statistik Pengunjung'; $page_description = 'Jumlah Statistik Pengunjung Website'; - // hitung statistik + // hitung statistik: enam periode dalam satu query, di-cache agar tidak dihitung ulang setiap buka halaman + $summary = Visitor::cachedSummaryStats(); $visitors = [ - 'todayVisitors' => Visitor::stats(VisitorFilterEnum::TODAY), - 'yesterdayVisitors' => Visitor::stats(VisitorFilterEnum::YESTERDAY), - 'weeklyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_WEEK), - 'monthlyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_MONTH), - 'yearlyVisitors' => Visitor::stats(VisitorFilterEnum::THIS_YEAR), - 'totalVisitors' => Visitor::stats(VisitorFilterEnum::ALL), + 'todayVisitors' => $summary['today'], + 'yesterdayVisitors' => $summary['yesterday'], + 'weeklyVisitors' => $summary['thisWeek'], + 'monthlyVisitors' => $summary['thisMonth'], + 'yearlyVisitors' => $summary['thisYear'], + 'totalVisitors' => $summary['all'], ]; // request url query parameter 'filter' @@ -67,7 +73,7 @@ public function index() ]; // Halaman populer - $top_pages_visited = Visitor::getTopPagesVisited(); + $top_pages_visited = Cache::remember(self::CACHE_TOP_PAGES, now()->addMinutes(self::CACHE_TTL_MINUTES), fn () => Visitor::getTopPagesVisited()); return view('counter.index', compact( 'page_title', diff --git a/app/Http/Middleware/TrackVisitors.php b/app/Http/Middleware/TrackVisitors.php index ff02867123..78012c10b2 100644 --- a/app/Http/Middleware/TrackVisitors.php +++ b/app/Http/Middleware/TrackVisitors.php @@ -48,12 +48,12 @@ public function handle(Request $request, Closure $next) $ipAddress = $request->ip(); $hashedIpAddress = hash('sha256', $ipAddress); // Hash IP address $url = $request->fullUrl(); - $today = now()->toDateString(); $userAgent = $request->userAgent(); - $visitor = Visitor::where('ip_address', $hashedIpAddress) - ->where('url', $url) - ->whereDate('visited_at', $today) + // Lookup memakai index (ip_address, url_hash, visited_at), bukan membandingkan kolom TEXT url. + $visitor = Visitor::filter(\App\Enums\VisitorFilterEnum::TODAY) + ->where('ip_address', $hashedIpAddress) + ->where('url_hash', hash('sha256', $url)) ->first(); if ($visitor) { diff --git a/app/Models/Visitor.php b/app/Models/Visitor.php index ce85369276..44f9ebdc83 100644 --- a/app/Models/Visitor.php +++ b/app/Models/Visitor.php @@ -21,33 +21,100 @@ class Visitor extends Model 'visited_at' => 'datetime', ]; - /* Query scope filter date */ + protected static function booted(): void + { + // url_hash menjadi kunci pengelompokan dan lookup, karena kolom url berupa TEXT (tidak bisa di-index penuh). + static::saving(function (Visitor $visitor) { + if ($visitor->isDirty('url') && $visitor->url !== null) { + $visitor->url_hash = hash('sha256', $visitor->url); + } + }); + } + + /* Query scope filter date. Memakai rentang [awal, akhir) agar index visited_at bisa dipakai. */ public function scopeFilter($query, $filter = null) { switch ($filter) { case VisitorFilterEnum::YESTERDAY: - $query->whereDate('visited_at', Carbon::yesterday()); - break; + $start = Carbon::yesterday()->startOfDay(); + return self::applyRange($query, $start, $start->copy()->addDay()); case VisitorFilterEnum::THIS_WEEK: - $query->whereBetween('visited_at', [now()->startOfWeek(), now()->endOfWeek()]); - break; + $start = now()->startOfWeek(); + return self::applyRange($query, $start, $start->copy()->addWeek()); case VisitorFilterEnum::THIS_MONTH: - $query->whereMonth('visited_at', now()->month) - ->whereYear('visited_at', now()->year); - break; + $start = now()->startOfMonth(); + return self::applyRange($query, $start, $start->copy()->addMonth()); case VisitorFilterEnum::THIS_YEAR: - $query->whereYear('visited_at', now()->year); - break; + $start = now()->startOfYear(); + return self::applyRange($query, $start, $start->copy()->addYear()); case VisitorFilterEnum::ALL: // tidak ada filter break; default: - $query->whereDate('visited_at', Carbon::today()); + $start = Carbon::today(); + return self::applyRange($query, $start, $start->copy()->addDay()); } return $query; } + private static function applyRange($query, Carbon $start, Carbon $end) + { + return $query->where('visited_at', '>=', $start)->where('visited_at', '<', $end); + } + + /** + * Ringkasan enam periode dalam satu kali pemindaian tabel. + * Mengembalikan array dengan kunci: today, yesterday, thisWeek, thisMonth, thisYear, all. + * Setiap nilai berupa object dengan properti page_views dan unique_visitors. + */ + public static function summaryStats(): array + { + $now = now(); + $todayStart = $now->copy()->startOfDay(); + $weekStart = $now->copy()->startOfWeek(); + $monthStart = $now->copy()->startOfMonth(); + $yearStart = $now->copy()->startOfYear(); + + $periods = [ + 'today' => [$todayStart, $todayStart->copy()->addDay()], + 'yesterday' => [$todayStart->copy()->subDay(), $todayStart], + 'thisWeek' => [$weekStart, $weekStart->copy()->addWeek()], + 'thisMonth' => [$monthStart, $monthStart->copy()->addMonth()], + 'thisYear' => [$yearStart, $yearStart->copy()->addYear()], + 'all' => null, + ]; + + $columns = []; + $bindings = []; + foreach ($periods as $key => $range) { + if ($range === null) { + $columns[] = "SUM(page_views) AS {$key}_page_views"; + $columns[] = "COUNT(DISTINCT ip_address) AS {$key}_unique_visitors"; + + continue; + } + + [$start, $end] = $range; + $condition = 'visited_at >= ? AND visited_at < ?'; + $columns[] = "SUM(CASE WHEN {$condition} THEN page_views ELSE 0 END) AS {$key}_page_views"; + $columns[] = "COUNT(DISTINCT CASE WHEN {$condition} THEN ip_address END) AS {$key}_unique_visitors"; + array_push($bindings, $start, $end, $start, $end); + } + + $row = self::query()->selectRaw(implode(', ', $columns), $bindings)->first(); + + $summary = []; + foreach (array_keys($periods) as $key) { + $summary[$key] = (object) [ + 'page_views' => (int) $row->{"{$key}_page_views"}, + 'unique_visitors' => (int) $row->{"{$key}_unique_visitors"}, + ]; + } + + return $summary; + } + public static function stats($filter = null) { return self::filter($filter) @@ -75,21 +142,32 @@ public static function groupedStats($filter) ->get(); } - /* data untuk halaman populer */ + /* data untuk halaman populer. Dikelompokkan per url_hash (indexed), bukan url (TEXT). */ public static function getTopPagesVisited() { - return self::select('url') + return self::select('url_hash') + ->selectRaw('MAX(url) as url') ->selectRaw('SUM(page_views) as total_views') ->selectRaw('COUNT(DISTINCT ip_address) as unique_visitors') ->selectRaw('SUM(CASE WHEN page_views = 1 THEN 1 ELSE 0 END) as bounces') - ->groupBy('url') + ->groupBy('url_hash') ->orderByDesc('total_views') ->limit(10) ->get(); } + /* Ringkasan di-cache bersama, sehingga sidebar (dipanggil di setiap halaman admin) tidak memindai tabel lagi. */ + public static function cachedSummaryStats(): array + { + return \Illuminate\Support\Facades\Cache::remember( + 'counter.summary', + now()->addMinutes(5), + fn () => self::summaryStats() + ); + } + public static function countAllVisitors() { - return \Illuminate\Support\Facades\DB::table('visitors')->distinct('ip_address')->count('ip_address'); + return self::cachedSummaryStats()['all']->unique_visitors; } } diff --git a/database/migrations/2026_11_26_000000_add_url_hash_and_indexes_to_visitors_table.php b/database/migrations/2026_11_26_000000_add_url_hash_and_indexes_to_visitors_table.php new file mode 100644 index 0000000000..b9a81f0dfc --- /dev/null +++ b/database/migrations/2026_11_26_000000_add_url_hash_and_indexes_to_visitors_table.php @@ -0,0 +1,44 @@ +char('url_hash', 64)->nullable()->after('url'); + }); + } + + // Backfill data lama. SHA2 dijalankan di sisi database agar tidak memuat 500 ribu baris ke PHP. + DB::statement('UPDATE visitors SET url_hash = SHA2(url, 256) WHERE url_hash IS NULL'); + + Schema::table('visitors', function (Blueprint $table) { + $table->index('visited_at', 'visitors_visited_at_index'); + $table->index('url_hash', 'visitors_url_hash_index'); + $table->index(['ip_address', 'url_hash', 'visited_at'], 'visitors_ip_url_visited_index'); + }); + } + + public function down(): void + { + Schema::table('visitors', function (Blueprint $table) { + $table->dropIndex('visitors_visited_at_index'); + $table->dropIndex('visitors_url_hash_index'); + $table->dropIndex('visitors_ip_url_visited_index'); + }); + + Schema::table('visitors', function (Blueprint $table) { + $table->dropColumn('url_hash'); + }); + } +}; diff --git a/tests/Feature/CounterPerformanceTest.php b/tests/Feature/CounterPerformanceTest.php new file mode 100644 index 0000000000..654b950c69 --- /dev/null +++ b/tests/Feature/CounterPerformanceTest.php @@ -0,0 +1,147 @@ +delete(); +}); + +function buatKunjungan(array $attributes = []): Visitor +{ + return Visitor::create(array_merge([ + 'ip_address' => hash('sha256', '10.0.0.'.random_int(1, 254)), + 'url' => 'http://localhost/halaman-a', + 'user_agent' => 'test-agent', + 'visited_at' => now(), + 'page_views' => 1, + ], $attributes)); +} + +// ============================================================================= +// INDEX & SKEMA +// ============================================================================= + +test('tabel visitors memiliki kolom url_hash', function () { + expect(Schema::hasColumn('visitors', 'url_hash'))->toBeTrue(); +}); + +test('tabel visitors memiliki index pada visited_at, url_hash, dan kombinasi ip_address-url_hash-visited_at', function () { + $indexes = collect(Schema::getIndexes('visitors'))->map(fn ($index) => $index['columns']); + + expect($indexes->contains(['visited_at']))->toBeTrue() + ->and($indexes->contains(['url_hash']))->toBeTrue() + ->and($indexes->contains(['ip_address', 'url_hash', 'visited_at']))->toBeTrue(); +}); + +// ============================================================================= +// PENULISAN url_hash +// ============================================================================= + +test('url_hash terisi otomatis dari sha256 url saat kunjungan disimpan', function () { + $kunjungan = buatKunjungan(['url' => 'http://localhost/berita/1?x=2']); + + expect($kunjungan->fresh()->url_hash)->toBe(hash('sha256', 'http://localhost/berita/1?x=2')); +}); + +test('TrackVisitors menyimpan url_hash untuk request GET', function () { + $url = 'http://localhost/profil/desa'; + + (new TrackVisitors)->handle(Request::create($url, 'GET'), fn () => response('ok')); + + expect(Visitor::latest('id')->first()->url_hash)->toBe(hash('sha256', $url)); +}); + +test('TrackVisitors menaikkan page_views untuk ip dan url yang sama di hari yang sama', function () { + $url = 'http://localhost/profil/desa'; + $middleware = new TrackVisitors; + + $middleware->handle(Request::create($url, 'GET'), fn () => response('ok')); + $middleware->handle(Request::create($url, 'GET'), fn () => response('ok')); + + expect(Visitor::count())->toBe(1) + ->and(Visitor::first()->page_views)->toBe(2); +}); + +// ============================================================================= +// RINGKASAN STATISTIK +// ============================================================================= + +test('summaryStats mengembalikan enam periode dalam satu query', function () { + buatKunjungan(['visited_at' => now(), 'page_views' => 2]); + buatKunjungan(['visited_at' => now()->subDay(), 'page_views' => 3]); + + DB::flushQueryLog(); + DB::enableQueryLog(); + $summary = Visitor::summaryStats(); + $queries = DB::getQueryLog(); + DB::disableQueryLog(); + + expect($queries)->toHaveCount(1) + ->and($summary)->toHaveKeys(['today', 'yesterday', 'thisWeek', 'thisMonth', 'thisYear', 'all']) + ->and((int) $summary['today']->page_views)->toBe(2) + ->and((int) $summary['yesterday']->page_views)->toBe(3) + ->and((int) $summary['all']->page_views)->toBe(5); +}); + +test('summaryStats konsisten dengan stats per periode', function () { + buatKunjungan(['visited_at' => now(), 'page_views' => 4]); + buatKunjungan(['visited_at' => now()->subYears(2), 'page_views' => 6]); + + $summary = Visitor::summaryStats(); + + expect((int) $summary['today']->page_views)->toBe((int) Visitor::stats(\App\Enums\VisitorFilterEnum::TODAY)->page_views) + ->and((int) $summary['thisYear']->page_views)->toBe((int) Visitor::stats(\App\Enums\VisitorFilterEnum::THIS_YEAR)->page_views) + ->and((int) $summary['all']->page_views)->toBe((int) Visitor::stats(\App\Enums\VisitorFilterEnum::ALL)->page_views); +}); + +// ============================================================================= +// HALAMAN POPULER +// ============================================================================= + +test('getTopPagesVisited mengelompokkan per url dan menjumlahkan page_views', function () { + buatKunjungan(['url' => 'http://localhost/a', 'page_views' => 3]); + buatKunjungan(['url' => 'http://localhost/a', 'page_views' => 2]); + buatKunjungan(['url' => 'http://localhost/b', 'page_views' => 1]); + + $top = Visitor::getTopPagesVisited(); + + expect($top)->toHaveCount(2) + ->and($top[0]->url)->toBe('http://localhost/a') + ->and((int) $top[0]->total_views)->toBe(5) + ->and((int) $top[0]->unique_visitors)->toBe(2); +}); + +// ============================================================================= +// JUMLAH QUERY HALAMAN COUNTER +// ============================================================================= + +test('halaman statistik pengunjung menjalankan paling banyak 3 query ke tabel visitors', function () { + $this->actingAs(User::factory()->create()); + buatKunjungan(['visited_at' => now()]); + buatKunjungan(['visited_at' => now()->subDays(40)]); + + DB::flushQueryLog(); + DB::enableQueryLog(); + $this->get(route('counter.index'))->assertSuccessful(); + $queries = collect(DB::getQueryLog()); + DB::disableQueryLog(); + + $queriesVisitors = $queries->filter(fn ($query) => str_contains($query['query'], 'visitors')); + + expect($queriesVisitors->count())->toBeLessThanOrEqual(3); +});