Files
Verde-Web/app/Services/LiveTracking/TruckTracker.php
2026-07-02 13:02:29 +08:00

128 lines
4.5 KiB
PHP

<?php
namespace App\Services\LiveTracking;
use App\Events\TruckLocationBroadcast;
use App\Models\Trip;
use App\Models\Truck;
use App\Models\TruckLocationHistory;
use App\Services\Trip\TripExecutor;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use MatanYadaev\EloquentSpatial\Objects\Point;
class TruckTracker
{
public function __construct(private readonly TripExecutor $tripExecutor) {}
/**
* Record a truck's GPS reading. Writes to history (for replay), updates
* trucks.last_known_coordinates, caches the latest position keyed by
* truck for fast live-map polling.
*
* Returns whether a geofence trigger fired (e.g., entering the
* dumpsite for the active trip).
*/
public function record(
Truck $truck,
float $lat,
float $lng,
?int $heading = null,
?float $speedKmh = null,
?Trip $trip = null,
?\DateTimeInterface $recordedAt = null,
): TrackResult {
$when = $recordedAt ?? now();
$point = new Point($lat, $lng, 4326);
DB::transaction(function () use ($truck, $point, $heading, $speedKmh, $trip, $when) {
TruckLocationHistory::create([
'truck_id' => $truck->id,
'trip_id' => $trip?->id,
'coordinates' => $point,
'heading_degrees' => $heading,
'speed_kmh' => $speedKmh,
'recorded_at' => $when,
]);
$truck->forceFill([
'last_known_coordinates' => $point,
'last_location_updated_at' => $when,
])->save();
});
Cache::put($this->cacheKey($truck), [
'lat' => $lat, 'lng' => $lng,
'heading_degrees' => $heading,
'speed_kmh' => $speedKmh,
'recorded_at' => $when->toIso8601String(),
'trip_id' => $trip?->uuid,
], now()->addMinutes(5));
$geofenceTriggered = false;
if ($trip?->dumpsite && $trip->dumpsite->boundary_polygon
&& $trip->status === Trip::STATUS_IN_PROGRESS) {
if ($trip->dumpsite->containsPoint($lat, $lng)) {
$geofenceTriggered = true;
// Auto-fire arriveAtDumpsite once. The driver's app may
// also POST it manually; the executor's status guard
// prevents duplicate timeline events.
try {
$driver = $trip->team?->driver;
if ($driver) {
$this->tripExecutor->arriveAtDumpsite($trip, $driver, $lat, $lng);
}
} catch (\DomainException $e) {
// Already at-dumpsite or not in_progress — ignore.
}
}
}
// Broadcast over WebSocket for live admin map + resident truck
// tracking. Reverb (or any compatible driver) picks this up.
$truck->loadMissing('assignedTeam');
TruckLocationBroadcast::dispatch(
$truck, $lat, $lng, $heading, $speedKmh, $trip, $when,
);
return new TrackResult(true, $geofenceTriggered);
}
/**
* Return latest known position for each active truck (within last hour).
*/
public function activeTruckPositions(): array
{
$trucks = Cache::remember('active_truck_positions_list', now()->addSeconds(15), function () {
return Truck::query()
->where('status', Truck::STATUS_ACTIVE)
->whereNotNull('last_known_coordinates')
->where('last_location_updated_at', '>=', now()->subHour())
->with('assignedTeam')
->get();
});
return $trucks->map(function (Truck $t) {
$cached = Cache::get($this->cacheKey($t));
return [
'truck_id' => $t->uuid,
'plate_number' => $t->plate_number,
'team' => $t->assignedTeam?->name,
'lat' => $t->last_known_coordinates->latitude,
'lng' => $t->last_known_coordinates->longitude,
'heading_degrees' => $cached['heading_degrees'] ?? null,
'speed_kmh' => $cached['speed_kmh'] ?? null,
'recorded_at' => $t->last_location_updated_at?->toIso8601String(),
'active_trip_id' => $cached['trip_id'] ?? null,
];
})->all();
}
private function cacheKey(Truck $truck): string
{
return "truck:position:{$truck->id}";
}
}