Reverse-geocode a general area label for logged searches

Each search now stores an `area_label` (district/town) reverse-geocoded from its
coarsened ~1km lat/lng bucket via postcodes.io, surfaced in the Filament Searches
admin as a sortable/searchable column plus an area filter. Geocoding is cached 30
days per bucket, queries a 2km radius so low-density buckets still match the
default 100m miss, and fails gracefully to null. Adds `searches:backfill-areas`
(scheduled hourly) to label existing rows and retry stragglers.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Ovidiu U
2026-06-12 09:05:03 +01:00
parent 040b2f627e
commit ea22387c9d
10 changed files with 331 additions and 1 deletions

View File

@@ -279,3 +279,76 @@ it('persists an outcode resolved via HTTP fallback', function (): void {
->and((float) $row->lat)->toBe(52.536397)
->and((float) $row->lng)->toBe(-0.210181);
});
// --- Reverse geocoding (area label) ---
it('reverse-geocodes coordinates to the admin district', function (): void {
Http::fake([
'*/postcodes?*' => Http::response([
'status' => 200,
'result' => [
['admin_district' => 'Peterborough', 'region' => 'East of England'],
],
]),
]);
expect($this->service->reverseResolve(52.5364, -0.2102))->toBe('Peterborough');
});
it('falls back to a broader area when admin district is missing', function (): void {
Http::fake([
'*/postcodes?*' => Http::response([
'status' => 200,
'result' => [
['admin_district' => null, 'region' => 'Scotland'],
],
]),
]);
expect($this->service->reverseResolve(57.4, -4.2))->toBe('Scotland');
});
it('returns null when reverse geocoding finds no area', function (): void {
Http::fake([
'*/postcodes?*' => Http::response(['status' => 200, 'result' => null]),
]);
expect($this->service->reverseResolve(0.0, 0.0))->toBeNull();
});
it('returns null when the reverse geocode request fails', function (): void {
Http::fake([
'*/postcodes?*' => Http::response([], 500),
]);
expect($this->service->reverseResolve(52.5364, -0.2102))->toBeNull();
});
it('caches the reverse-geocoded area per bucket', function (): void {
Http::fake([
'*/postcodes?*' => Http::response([
'status' => 200,
'result' => [['admin_district' => 'Peterborough']],
]),
]);
// Two coordinates inside the same ~1km (2dp) bucket → one HTTP call.
$this->service->reverseResolve(52.5364, -0.2102);
$this->service->reverseResolve(52.5359, -0.2148);
Http::assertSentCount(1);
});
it('queries postcodes.io with a wide radius so low-density buckets still match', function (): void {
Http::fake([
'*/postcodes?*' => Http::response([
'status' => 200,
'result' => [['admin_district' => 'Peterborough']],
]),
]);
$this->service->reverseResolve(52.54, -0.25);
// The default 100m radius misses the bucket centroid in rural areas; we send 2000m.
Http::assertSent(fn ($request) => str_contains($request->url(), 'radius=2000'));
});