feat: add GET /api/stations nearby stations endpoint with haversine query and search logging
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
72
app/Http/Controllers/Api/StationController.php
Normal file
72
app/Http/Controllers/Api/StationController.php
Normal file
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Requests\Api\NearbyStationsRequest;
|
||||
use App\Http\Resources\Api\StationResource;
|
||||
use App\Models\Search;
|
||||
use App\Models\Station;
|
||||
use Illuminate\Database\Query\JoinClause;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class StationController extends Controller
|
||||
{
|
||||
public function index(NearbyStationsRequest $request): JsonResponse
|
||||
{
|
||||
$lat = (float) $request->input('lat');
|
||||
$lng = (float) $request->input('lng');
|
||||
$fuelType = $request->fuelType();
|
||||
$radius = $request->radius();
|
||||
$sort = $request->sort();
|
||||
|
||||
$all = Station::query()
|
||||
->selectRaw(
|
||||
'stations.*, spc.price_pence, spc.fuel_type, spc.price_effective_at,
|
||||
(6371 * acos(MAX(-1.0, MIN(1.0,
|
||||
cos(radians(?)) * cos(radians(lat)) * cos(radians(lng) - radians(?))
|
||||
+ sin(radians(?)) * sin(radians(lat))
|
||||
)))) AS distance_km',
|
||||
[$lat, $lng, $lat],
|
||||
)
|
||||
->join('station_prices_current as spc', function (JoinClause $join) use ($fuelType): void {
|
||||
$join->on('stations.node_id', '=', 'spc.station_id')
|
||||
->where('spc.fuel_type', '=', $fuelType->value);
|
||||
})
|
||||
->where('stations.temporary_closure', false)
|
||||
->where('stations.permanent_closure', false)
|
||||
->get();
|
||||
|
||||
$stations = $all
|
||||
->filter(fn ($s) => (float) $s->distance_km <= $radius)
|
||||
->sortBy($sort === 'price' ? 'price_pence' : 'distance_km')
|
||||
->values();
|
||||
|
||||
$prices = $stations->pluck('price_pence');
|
||||
|
||||
Search::create([
|
||||
'lat_bucket' => round($lat, 2),
|
||||
'lng_bucket' => round($lng, 2),
|
||||
'fuel_type' => $fuelType->value,
|
||||
'results_count' => $stations->count(),
|
||||
'lowest_pence' => $prices->min(),
|
||||
'highest_pence' => $prices->max(),
|
||||
'avg_pence' => $prices->isNotEmpty() ? round($prices->avg(), 2) : null,
|
||||
'searched_at' => now(),
|
||||
'ip_hash' => hash('sha256', $request->ip() ?? ''),
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
'data' => StationResource::collection($stations),
|
||||
'meta' => [
|
||||
'count' => $stations->count(),
|
||||
'fuel_type' => $fuelType->value,
|
||||
'radius_km' => $radius,
|
||||
'lowest_pence' => $prices->min(),
|
||||
'highest_pence' => $prices->max(),
|
||||
'cheapest_price_pence' => $prices->min(),
|
||||
'avg_pence' => $prices->isNotEmpty() ? round($prices->avg(), 2) : null,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user