Files
Verde-Web/app/Services/LiveTracking/TruckTracker.php
admin 15d56d0e98 feat(backend): finish Module 13 sub-modules + flow fixes
Notifications: notification_preferences + Laravel notifications inbox.
SmsChannel adapter for our SmsService. RoutesByPreferences trait reads
per-user toggles. HouseholdApproved/Rejected, QrBalanceLow, and
CodesPurchased notifications wired in via auto-discovered listeners
or direct dispatch from controllers/StoreOperations.

Payments: payments table + PaymentDriver interface. ManualPaymentDriver
works out of the box; PayMongoDriver activates when
PAYMONGO_SECRET_KEY is set, falls back to manual otherwise. Resident
initiates code-purchase, admin can mark paid manually, webhook applies
real provider events. Fulfillment runs StoreOperations::sellToHousehold.

Live tracking (HTTP polling): truck_location_history (with SPATIAL
INDEX + 7-day retention plan). Driver POST /driver/trucks/{uuid}/location
writes history, updates trucks.last_known_coordinates, caches in Redis,
flags geofence-trigger when entering active trip dumpsite. Admin
GET /admin/live/trucks returns active truck positions. Reverb broadcast
deferred.

Flow corrections:
- QrAllocator now idempotent — re-approving a household no longer
  re-dispenses free codes.
- arrive-dumpsite enforces dumpsite geofence via ST_Contains; can be
  bypassed with override_geofence: true.

171 feature tests passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 14:01:38 +08:00

103 lines
3.3 KiB
PHP

<?php
namespace App\Services\LiveTracking;
use App\Models\Trip;
use App\Models\Truck;
use App\Models\TruckLocationHistory;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use MatanYadaev\EloquentSpatial\Objects\Point;
class TruckTracker
{
/**
* 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;
}
}
return new TrackResult(true, $geofenceTriggered);
}
/**
* Return latest known position for each active truck (within last hour).
*/
public function activeTruckPositions(): array
{
$trucks = 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}";
}
}