feat: add GET /api/stats/searches endpoint

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ovidiu U
2026-04-04 19:28:41 +01:00
parent 8bd43ee9e4
commit 0bea50b843
2 changed files with 113 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Search;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class StatsController extends Controller
{
public function searches(Request $request): JsonResponse
{
$period = $request->input('period', 'week');
$days = $period === 'month' ? 30 : 7;
$stats = Search::query()
->where('searched_at', '>=', now()->subDays($days))
->selectRaw('
COUNT(*) as total_searches,
COUNT(DISTINCT ip_hash) as unique_searchers,
AVG(results_count) as avg_results,
AVG(lowest_pence) as avg_lowest_pence,
AVG(highest_pence) as avg_highest_pence,
AVG(avg_pence) as avg_avg_pence
')
->first();
$totalSearches = (int) $stats->total_searches;
$uniqueSearchers = (int) $stats->unique_searchers;
$avgResults = $stats->avg_results !== null ? round((float) $stats->avg_results, 1) : 0.0;
$avgLowestPrice = $stats->avg_lowest_pence !== null ? round((float) $stats->avg_lowest_pence / 100, 1) : 0.0;
$avgHighestPrice = $stats->avg_highest_pence !== null ? round((float) $stats->avg_highest_pence / 100, 1) : 0.0;
$avgPrice = $stats->avg_avg_pence !== null ? round((float) $stats->avg_avg_pence / 100, 1) : 0.0;
$periodLabel = $period === 'month' ? 'month' : 'week';
return response()->json([
'total_searches' => $totalSearches,
'unique_searchers' => $uniqueSearchers,
'avg_results' => $avgResults,
'avg_lowest_price' => $avgLowestPrice,
'avg_highest_price' => $avgHighestPrice,
'avg_price' => $avgPrice,
'period' => $periodLabel,
'message' => "Helped {$uniqueSearchers} drivers find cheaper fuel this {$periodLabel} so far!",
]);
}
}