feat: add PostcodeService and price validation with DB constraints
Some checks failed
linter / quality (push) Has been cancelled
tests / ci (8.3) (push) Has been cancelled
tests / ci (8.4) (push) Has been cancelled
tests / ci (8.5) (push) Has been cancelled

- Add PostcodeService to resolve UK postcodes, outcodes, and place names to coordinates via postcodes.io API with 30-day caching
- Add LocationResult value object for resolved location data
- Add per-fuel-type price validation (80p-1050p range) to FuelPriceService with warning logs for out-of-range prices
- Change price_pence column from unsignedSmallInteger to unsignedMediumInteger in station_prices tables
- Add CHECK constraints (5000-50000 range) on price_pence columns as database-level guard
- Improve error handling in PollFuelPrices command with file/line/trace output
- Add tests for PostcodeService covering full postcodes, outcodes, place names, caching, and error handling
- Add test for price validation range checks

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Ovidiu U
2026-04-04 12:40:43 +01:00
parent 097f1b0529
commit e532cc1208
8 changed files with 530 additions and 1 deletions

View File

@@ -17,6 +17,22 @@ class FuelPriceService
{
private const string TOKEN_CACHE_KEY = 'fuel_finder_access_token';
/**
* Per-fuel-type valid price range in pence (as returned by the API).
* Based on UK all-time records + 3075% headroom for future spikes.
* All-time records: petrol 191.6p, diesel 199.2p (Jul 2022).
*
* @var array<string, array{min: int, max: int}>
*/
private const array PRICE_LIMITS_PENCE = [
'e10' => ['min' => 80, 'max' => 750],
'e5' => ['min' => 80, 'max' => 840],
'b7_standard' => ['min' => 80, 'max' => 840],
'b7_premium' => ['min' => 80, 'max' => 960],
'b10' => ['min' => 80, 'max' => 840],
'hvo' => ['min' => 80, 'max' => 1050],
];
public function __construct(
private readonly StationTaggingService $taggingService,
private readonly ApiLogger $apiLogger,
@@ -56,6 +72,18 @@ class FuelPriceService
->withToken($token)
->get($baseUrl, $params));
if ($response->notFound()) {
break; // No more batches
}
if (! $response->successful()) {
Log::error('FuelPriceService: price batch returned error', [
'batch' => $batch,
'status' => $response->status(),
]);
break;
}
$stations = $response->json() ?? [];
} catch (Throwable $e) {
Log::error('FuelPriceService: price batch fetch failed', [
@@ -94,6 +122,18 @@ class FuelPriceService
->withToken($token)
->get($baseUrl, $params));
if ($response->notFound()) {
break; // No more batches
}
if (! $response->successful()) {
Log::error('FuelPriceService: station batch returned error', [
'batch' => $batch,
'status' => $response->status(),
]);
break;
}
$stations = $response->json() ?? [];
} catch (Throwable $e) {
Log::error('FuelPriceService: station batch fetch failed', [
@@ -152,6 +192,17 @@ class FuelPriceService
Station::upsert($rows, ['node_id'], array_keys($rows[0] ?? []));
}
private function isValidPrice(FuelType $fuelType, float $pricePence): bool
{
$limits = self::PRICE_LIMITS_PENCE[$fuelType->value] ?? null;
if ($limits === null) {
return false;
}
return $pricePence >= $limits['min'] && $pricePence <= $limits['max'];
}
/**
* Process one batch of API price data.
*
@@ -185,7 +236,20 @@ class FuelPriceService
continue; // Skip unknown fuel types
}
$pricePence = (int) round($priceData['price'] * 100);
$rawPrice = (float) $priceData['price'];
if (! $this->isValidPrice($fuelType, $rawPrice)) {
Log::warning('FuelPriceService: price out of valid range — skipped', [
'station_id' => $stationId,
'fuel_type' => $fuelType->value,
'price' => $rawPrice,
'limits' => self::PRICE_LIMITS_PENCE[$fuelType->value],
]);
continue;
}
$pricePence = (int) round($rawPrice * 100);
$effectiveAt = Carbon::parse($priceData['price_change_effective_timestamp']);
$reportedAt = Carbon::parse($priceData['price_last_updated']);
$currentPricePence = $currentPrices[$stationId][$fuelType->value]->price_pence ?? null;

View File

@@ -0,0 +1,13 @@
<?php
namespace App\Services;
readonly class LocationResult
{
public function __construct(
public string $query,
public string $displayName,
public float $lat,
public float $lng,
) {}
}

View File

@@ -0,0 +1,154 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Throwable;
class PostcodeService
{
private const string BASE_URL = 'https://api.postcodes.io';
private const int CACHE_TTL = 60 * 60 * 24 * 30; // 30 days
public function __construct(
private readonly ApiLogger $apiLogger,
) {}
/**
* Resolve a UK location query (full postcode, outcode, or place name) to coordinates.
* Returns null if the location cannot be resolved.
*/
public function resolve(string $query): ?LocationResult
{
$query = trim($query);
$cacheKey = 'postcode:'.strtolower(preg_replace('/\s+/', '', $query));
$cached = Cache::get($cacheKey);
if ($cached !== null) {
return $cached;
}
$result = match (true) {
$this->isFullPostcode($query) => $this->lookupPostcode($query),
$this->isOutcode($query) => $this->lookupOutcode($query),
default => $this->lookupPlace($query),
};
if ($result !== null) {
Cache::put($cacheKey, $result, self::CACHE_TTL);
}
return $result;
}
private function isFullPostcode(string $query): bool
{
return (bool) preg_match('/^[A-Z]{1,2}[0-9][0-9A-Z]?\s*[0-9][A-Z]{2}$/i', $query);
}
private function isOutcode(string $query): bool
{
return (bool) preg_match('/^[A-Z]{1,2}[0-9][0-9A-Z]?$/i', $query);
}
private function lookupPostcode(string $postcode): ?LocationResult
{
$normalised = strtoupper(preg_replace('/\s+/', '', $postcode));
$url = self::BASE_URL.'/postcodes/'.$normalised;
try {
$response = $this->apiLogger->send('postcodes_io', 'GET', $url, fn () => Http::timeout(10)->get($url));
if (! $response->successful()) {
return null;
}
$data = $response->json('result');
return new LocationResult(
query: $postcode,
displayName: $data['postcode'],
lat: $data['latitude'],
lng: $data['longitude'],
);
} catch (Throwable $e) {
Log::error('PostcodeService: postcode lookup failed', [
'postcode' => $postcode,
'error' => $e->getMessage(),
]);
return null;
}
}
private function lookupOutcode(string $outcode): ?LocationResult
{
$normalised = strtoupper(trim($outcode));
$url = self::BASE_URL.'/outcodes/'.$normalised;
try {
$response = $this->apiLogger->send('postcodes_io', 'GET', $url, fn () => Http::timeout(10)->get($url));
if (! $response->successful()) {
return null;
}
$data = $response->json('result');
return new LocationResult(
query: $outcode,
displayName: $data['outcode'],
lat: $data['latitude'],
lng: $data['longitude'],
);
} catch (Throwable $e) {
Log::error('PostcodeService: outcode lookup failed', [
'outcode' => $outcode,
'error' => $e->getMessage(),
]);
return null;
}
}
private function lookupPlace(string $place): ?LocationResult
{
$url = self::BASE_URL.'/places';
$logUrl = $url.'?q='.urlencode($place).'&limit=1';
try {
$response = $this->apiLogger->send('postcodes_io', 'GET', $logUrl, fn () => Http::timeout(10)
->get($url, ['q' => $place, 'limit' => 1]));
if (! $response->successful()) {
return null;
}
$results = $response->json('result');
if (empty($results)) {
return null;
}
$data = $results[0];
return new LocationResult(
query: $place,
displayName: $data['name_1'],
lat: $data['latitude'],
lng: $data['longitude'],
);
} catch (Throwable $e) {
Log::error('PostcodeService: place lookup failed', [
'place' => $place,
'error' => $e->getMessage(),
]);
return null;
}
}
}