94 lines
3.0 KiB
PHP
94 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Jobs;
|
|
|
|
use App\Models\City;
|
|
use App\Services\WikipediaService;
|
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
|
use Illuminate\Foundation\Queue\Queueable;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class FetchCityDataJob implements ShouldQueue
|
|
{
|
|
use Queueable;
|
|
|
|
public int $tries = 3;
|
|
public int $timeout = 60;
|
|
|
|
/**
|
|
* Create a new job instance.
|
|
*/
|
|
public function __construct(
|
|
public City $city,
|
|
public bool $forceRefresh = false
|
|
) {
|
|
}
|
|
|
|
/**
|
|
* Execute the job.
|
|
*/
|
|
public function handle(WikipediaService $wikipediaService): void
|
|
{
|
|
try {
|
|
// Check if we need to refresh the data
|
|
if (!$this->forceRefresh && $this->city->wikipedia_cached_at) {
|
|
$cacheAge = now()->diffInDays($this->city->wikipedia_cached_at);
|
|
$cacheTtl = config('services.wikipedia.cache_ttl', 30);
|
|
|
|
if ($cacheAge < $cacheTtl) {
|
|
Log::info("City data is still fresh, skipping fetch", [
|
|
'city_id' => $this->city->id,
|
|
'cache_age' => $cacheAge,
|
|
]);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Fetch data from Wikipedia
|
|
$data = $wikipediaService->getCitySummary($this->city->name);
|
|
|
|
if ($data) {
|
|
// Update city with Wikipedia data
|
|
$this->city->update([
|
|
'wikipedia_summary' => $data['summary'],
|
|
'wikipedia_url' => $data['url'],
|
|
'thumbnail_url' => $data['thumbnail'] ?? null,
|
|
'image_url' => $data['image'] ?? null,
|
|
'wikipedia_page_id' => $data['page_id'],
|
|
'wikipedia_cached_at' => now(),
|
|
]);
|
|
|
|
// Update coordinates if they exist in Wikipedia data and not set
|
|
if (isset($data['latitude']) && isset($data['longitude'])) {
|
|
if (!$this->city->latitude || !$this->city->longitude) {
|
|
$this->city->update([
|
|
'latitude' => $data['latitude'],
|
|
'longitude' => $data['longitude'],
|
|
]);
|
|
}
|
|
}
|
|
|
|
Log::info("City data fetched successfully", [
|
|
'city_id' => $this->city->id,
|
|
'city_name' => $this->city->name,
|
|
]);
|
|
|
|
// Dispatch job to fetch attractions
|
|
FetchAttractionsJob::dispatch($this->city);
|
|
} else {
|
|
Log::warning("Failed to fetch city data from Wikipedia", [
|
|
'city_id' => $this->city->id,
|
|
'city_name' => $this->city->name,
|
|
]);
|
|
}
|
|
} catch (\Exception $e) {
|
|
Log::error("Error in FetchCityDataJob", [
|
|
'city_id' => $this->city->id,
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
|
|
throw $e; // Re-throw to trigger retry
|
|
}
|
|
}
|
|
}
|