mivita/app/Jobs/TrackShipmentJob.php

174 lines
5.5 KiB
PHP

<?php
namespace App\Jobs;
use Acme\Dhl\Models\DhlShipment;
use App\Services\DhlTrackingService;
use DateTime;
use Exception;
use Illuminate\Bus\Queueable as BusQueueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
/**
* Job to track DHL shipments asynchronously
*
* This job handles the tracking of DHL shipments in the background,
* updating tracking status and details automatically.
*/
class TrackShipmentJob implements ShouldQueue
{
use BusQueueable, Dispatchable, InteractsWithQueue, SerializesModels;
/**
* @var DhlShipment
*/
public $dhlShipment;
/**
* @var array
*/
public $options;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 2;
/**
* The maximum number of seconds the job can run before timing out.
*
* @var int
*/
public $timeout = 60;
/**
* Create a new job instance.
*
* @param array<string, mixed> $options
*/
public function __construct(DhlShipment $dhlShipment, array $options = [])
{
$this->dhlShipment = $dhlShipment;
$this->options = $options;
// Set queue name - tracking is usually lower priority
$this->onQueue('dhl-tracking');
}
/**
* Execute the job.
*/
public function handle(DhlTrackingService $trackingService): void
{
try {
Log::info('[DHL Queue] Starting shipment tracking job', [
'shipment_id' => $this->dhlShipment->id,
'dhl_shipment_no' => $this->dhlShipment->dhl_shipment_no,
'attempt' => $this->attempts(),
]);
$result = $trackingService->updateTrackingNow($this->dhlShipment, $this->options);
Log::info('[DHL Queue] Shipment tracking updated successfully', [
'shipment_id' => $this->dhlShipment->id,
'success' => $result['success'] ?? false,
'tracking_status' => $result['tracking_status'] ?? 'unknown',
'tracking_completed' => $result['tracking_completed'] ?? false,
]);
// Schedule next tracking update if shipment is still in transit
if (($this->options['auto_retrack'] ?? false) && ! ($result['tracking_completed'] ?? false)) {
$this->dhlShipment->refresh();
$status = $this->dhlShipment->status ?? '';
if ($this->shouldContinueTracking($status)) {
// Schedule next tracking in 2-6 hours based on current status
$nextTrackingDelay = $this->getNextTrackingDelay($status);
TrackShipmentJob::dispatch($this->dhlShipment, $this->options)
->delay(now()->addMinutes($nextTrackingDelay));
Log::info('[DHL Queue] Next tracking job scheduled', [
'shipment_id' => $this->dhlShipment->id,
'delay_minutes' => $nextTrackingDelay,
]);
}
}
} catch (Exception $e) {
Log::warning('[DHL Queue] Shipment tracking failed', [
'shipment_id' => $this->dhlShipment->id,
'dhl_shipment_no' => $this->dhlShipment->dhl_shipment_no,
'error' => $e->getMessage(),
'attempt' => $this->attempts(),
'max_tries' => $this->tries,
]);
// For tracking, we don't necessarily need to fail hard
if ($this->attempts() >= $this->tries) {
Log::warning('[DHL Queue] Shipment tracking permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'error' => $e->getMessage(),
]);
// Don't re-throw for final attempt - just log and continue
return;
}
throw $e; // Re-throw to trigger retry mechanism
}
}
/**
* Handle a job failure.
*/
public function failed(Exception $exception): void
{
Log::warning('[DHL Queue] TrackShipmentJob permanently failed', [
'shipment_id' => $this->dhlShipment->id,
'dhl_shipment_no' => $this->dhlShipment->dhl_shipment_no,
'error' => $exception->getMessage(),
]);
// Tracking failures are less critical - just log them
}
/**
* Determine if we should continue tracking this shipment
*/
private function shouldContinueTracking(string $status): bool
{
return ! in_array(strtolower($status), DhlShipment::TERMINAL_STATUSES, true);
}
/**
* Get delay for next tracking update based on current status
*/
private function getNextTrackingDelay(string $status): int
{
switch (strtolower($status)) {
case 'picked_up':
case 'in_transit':
return 120; // 2 hours for active shipments
case 'out_for_delivery':
return 60; // 1 hour when out for delivery
case 'exception':
case 'failed_attempt':
return 240; // 4 hours for problem shipments
default:
return 180; // 3 hours default
}
}
/**
* Determine the time at which the job should timeout.
*/
public function retryUntil(): DateTime
{
return now()->addMinutes(30); // Short timeout for tracking
}
}