From 561aaceee1c3c82445976ec183809217718ac390 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 4 Nov 2026 16:08:03 +0800 Subject: [PATCH 01/29] chore(carbon): make diffIn calls behave the same on Carbon 2 and 3 Pins every diffIn* call as an explicit absolute or signed integer so results read the same on Carbon 2 and 3. Carbon 2 values are unchanged; tests pin direction and type at the priority sites. --- .../Commands/ReplayVehicleLocations.php | 2 +- .../Commands/SimulateGeofenceEvents.php | 2 +- server/src/Constraints/HOSConstraint.php | 6 +- server/src/Events/GeofenceDwelled.php | 2 +- .../Controllers/Api/v1/DriverController.php | 4 +- .../Controllers/Api/v1/VehicleController.php | 2 +- .../Internal/v1/PositionController.php | 6 +- .../Internal/v1/RadarController.php | 2 +- server/src/Jobs/ReplayPositions.php | 2 +- server/src/Jobs/SyncTelematicDevicesJob.php | 2 +- server/src/Models/Device.php | 2 +- server/src/Models/DeviceEvent.php | 4 +- server/src/Models/Equipment.php | 8 +- server/src/Models/Maintenance.php | 4 +- server/src/Models/Telematic.php | 2 +- server/src/Models/Warranty.php | 2 +- server/src/Models/WorkOrder.php | 4 +- server/src/Support/Radar/RadarAgenda.php | 12 +- server/src/Support/Radar/RadarRules.php | 16 +-- .../Support/Telematics/TelematicService.php | 2 +- .../Support/Telematics/Telemetry/Ingestor.php | 2 +- .../src/Tracking/TrackingContextBuilder.php | 2 +- server/src/Traits/Maintainable.php | 4 +- .../Unit/Support/CarbonDiffContractTest.php | 118 ++++++++++++++++++ .../TrackingIntelligenceAndContextTest.php | 3 +- 25 files changed, 167 insertions(+), 48 deletions(-) create mode 100644 server/tests/Unit/Support/CarbonDiffContractTest.php diff --git a/server/src/Console/Commands/ReplayVehicleLocations.php b/server/src/Console/Commands/ReplayVehicleLocations.php index ede009996..f72e96bbf 100644 --- a/server/src/Console/Commands/ReplayVehicleLocations.php +++ b/server/src/Console/Commands/ReplayVehicleLocations.php @@ -259,7 +259,7 @@ protected function calculateReplayDelay(string $previousTimestamp, string $creat { $currentTime = Carbon::parse($createdAt); $previousTime = Carbon::parse($previousTimestamp); - $diffInSeconds = $currentTime->diffInSeconds($previousTime); + $diffInSeconds = (int) $currentTime->diffInSeconds($previousTime, true); return [$diffInSeconds, $diffInSeconds / $speedMultiplier]; } diff --git a/server/src/Console/Commands/SimulateGeofenceEvents.php b/server/src/Console/Commands/SimulateGeofenceEvents.php index 95044f89c..f2928899d 100644 --- a/server/src/Console/Commands/SimulateGeofenceEvents.php +++ b/server/src/Console/Commands/SimulateGeofenceEvents.php @@ -273,6 +273,6 @@ protected function calculateDwellMinutes(string $subjectType, Driver|Vehicle $su return $fallback; } - return max(1, Carbon::parse($state->entered_at)->diffInMinutes(now())); + return max(1, (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true)); } } diff --git a/server/src/Constraints/HOSConstraint.php b/server/src/Constraints/HOSConstraint.php index 80304b524..378692e49 100644 --- a/server/src/Constraints/HOSConstraint.php +++ b/server/src/Constraints/HOSConstraint.php @@ -128,7 +128,7 @@ protected function check14HourDutyWindow(ScheduleItem $item, $recentItems): bool $dutyStart = Carbon::parse($lastOffDutyPeriod); $itemEnd = Carbon::parse($item->end_at); - $hoursSinceDutyStart = $dutyStart->diffInHours($itemEnd); + $hoursSinceDutyStart = (int) $dutyStart->diffInHours($itemEnd, true); return $hoursSinceDutyStart <= 14; } @@ -172,7 +172,7 @@ protected function check30MinuteBreak(ScheduleItem $item, $recentItems): bool foreach ($recentItems as $recentItem) { if ($recentItem->break_start_at && $recentItem->break_end_at) { - $breakDuration = Carbon::parse($recentItem->break_start_at)->diffInMinutes($recentItem->break_end_at); + $breakDuration = (int) Carbon::parse($recentItem->break_start_at)->diffInMinutes($recentItem->break_end_at, true); if ($breakDuration >= 30) { $lastBreak = $recentItem->break_end_at; $drivingHours = 0; // Reset driving hours after break @@ -188,7 +188,7 @@ protected function check30MinuteBreak(ScheduleItem $item, $recentItems): bool // If more than 8 hours of driving, require a 30-minute break if ($drivingHours > 8) { return $item->break_start_at && $item->break_end_at - && Carbon::parse($item->break_start_at)->diffInMinutes($item->break_end_at) >= 30; + && (int) Carbon::parse($item->break_start_at)->diffInMinutes($item->break_end_at, true) >= 30; } return true; diff --git a/server/src/Events/GeofenceDwelled.php b/server/src/Events/GeofenceDwelled.php index cbaae7832..092e084b0 100644 --- a/server/src/Events/GeofenceDwelled.php +++ b/server/src/Events/GeofenceDwelled.php @@ -103,7 +103,7 @@ public function __construct(Driver|Vehicle $subject, $geofence, string $geofence $this->geofence = $geofence; $this->geofenceType = $geofenceType; $this->enteredAt = $enteredAt; - $this->dwellDurationMinutes = (int) $enteredAt->diffInMinutes(now()); + $this->dwellDurationMinutes = (int) $enteredAt->diffInMinutes(now(), true); $this->timestamp = now(); $this->modelRecordName = $geofence->name ?? $geofence->public_id ?? $geofence->uuid ?? null; $this->userSession = session('user'); diff --git a/server/src/Http/Controllers/Api/v1/DriverController.php b/server/src/Http/Controllers/Api/v1/DriverController.php index fd006cb2c..8748b7f0b 100644 --- a/server/src/Http/Controllers/Api/v1/DriverController.php +++ b/server/src/Http/Controllers/Api/v1/DriverController.php @@ -335,7 +335,7 @@ public function track(string $id, Request $request) return $this->driverResource($driver); } - $isGeocodable = Carbon::parse($driver->updated_at)->diffInMinutes(Carbon::now(), false) > 10 || empty($driver->country) || empty($driver->city); + $isGeocodable = (int) Carbon::parse($driver->updated_at)->diffInMinutes(Carbon::now(), false) > 10 || empty($driver->country) || empty($driver->city); $positionData = [ 'location' => new Point($latitude, $longitude), @@ -1309,7 +1309,7 @@ private function processSubjectGeofenceCrossings(Driver|Vehicle $subject, Point $dwellMinutes = null; if ($state && $state->entered_at) { - $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now()); + $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true); } DB::table($stateTable) diff --git a/server/src/Http/Controllers/Api/v1/VehicleController.php b/server/src/Http/Controllers/Api/v1/VehicleController.php index 387d8a2d2..5c419a0aa 100644 --- a/server/src/Http/Controllers/Api/v1/VehicleController.php +++ b/server/src/Http/Controllers/Api/v1/VehicleController.php @@ -369,7 +369,7 @@ private function processVehicleGeofenceCrossings(Vehicle $vehicle, Point $newLoc $dwellMinutes = null; if ($state && $state->entered_at) { - $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now()); + $dwellMinutes = (int) Carbon::parse($state->entered_at)->diffInMinutes(now(), true); } DB::table('vehicle_geofence_states') diff --git a/server/src/Http/Controllers/Internal/v1/PositionController.php b/server/src/Http/Controllers/Internal/v1/PositionController.php index 0d6865e9c..9e798150d 100644 --- a/server/src/Http/Controllers/Internal/v1/PositionController.php +++ b/server/src/Http/Controllers/Internal/v1/PositionController.php @@ -167,7 +167,7 @@ private function calculateMetrics($positions) } } else { if ($dwellStart !== null) { - $dwellDuration = $previousPosition->created_at->diffInSeconds($dwellStart); + $dwellDuration = (int) $previousPosition->created_at->diffInSeconds($dwellStart, true); if ($dwellDuration >= $dwellThreshold) { $dwellTimes[] = [ 'start' => $dwellStart->toDateTimeString(), @@ -181,7 +181,7 @@ private function calculateMetrics($positions) // Calculate acceleration if ($previousSpeed !== null) { - $timeDiff = $position->created_at->diffInSeconds($previousPosition->created_at); + $timeDiff = (int) $position->created_at->diffInSeconds($previousPosition->created_at, true); if ($timeDiff > 0) { $acceleration = abs($speed - $previousSpeed) / $timeDiff; if ($acceleration > $accelerationThreshold) { @@ -207,7 +207,7 @@ private function calculateMetrics($positions) // Calculate total duration $firstPosition = $positions->first(); $lastPosition = $positions->last(); - $totalDuration = $lastPosition->created_at->diffInSeconds($firstPosition->created_at); + $totalDuration = (int) $lastPosition->created_at->diffInSeconds($firstPosition->created_at, true); return [ 'total_distance' => round($totalDistance / 1000, 2), // Convert to km diff --git a/server/src/Http/Controllers/Internal/v1/RadarController.php b/server/src/Http/Controllers/Internal/v1/RadarController.php index 9cd1e7961..7f46fdf5f 100644 --- a/server/src/Http/Controllers/Internal/v1/RadarController.php +++ b/server/src/Http/Controllers/Internal/v1/RadarController.php @@ -861,7 +861,7 @@ protected function snoozeMinutes(Request $request): ?int if (!$until || $until->lte($this->now())) { return null; } - $minutes = (int) ceil($this->now()->diffInMinutes($until)); + $minutes = (int) $this->now()->diffInMinutes($until, true); return $minutes >= 1 && $minutes <= $max ? $minutes : null; } diff --git a/server/src/Jobs/ReplayPositions.php b/server/src/Jobs/ReplayPositions.php index 2a7d67bc6..c8a2b253b 100644 --- a/server/src/Jobs/ReplayPositions.php +++ b/server/src/Jobs/ReplayPositions.php @@ -45,7 +45,7 @@ public function handle(): void foreach ($this->positions as $index => $position) { $currentTime = Carbon::parse($position->created_at); - $offset = $baseTime->diffInSeconds($currentTime, false) / $this->speed; + $offset = (int) $baseTime->diffInSeconds($currentTime, false) / $this->speed; // Schedule a small job for each event with its own delay $this->dispatchReplayPosition($position, $index, max(0, $offset)); diff --git a/server/src/Jobs/SyncTelematicDevicesJob.php b/server/src/Jobs/SyncTelematicDevicesJob.php index d32093fb3..4add5b8a0 100644 --- a/server/src/Jobs/SyncTelematicDevicesJob.php +++ b/server/src/Jobs/SyncTelematicDevicesJob.php @@ -125,7 +125,7 @@ public function handle(TelematicProviderRegistry $registry, TelematicService $se &$inventoryFetched, &$inventoryLinked, &$inventorySkipped, &$totalEnrichment, &$totalEnrichmentCompleted, &$totalEnrichmentFailures ): void { - if (!$force && $itemsSinceCheckpoint < 25 && $lastCheckpointAt->diffInSeconds(now(), true) < 5) { + if (!$force && $itemsSinceCheckpoint < 25 && (int) $lastCheckpointAt->diffInSeconds(now(), true) < 5) { return; } $this->telematic->status = 'synchronizing'; diff --git a/server/src/Models/Device.php b/server/src/Models/Device.php index d38ecf3c4..52621bf8c 100644 --- a/server/src/Models/Device.php +++ b/server/src/Models/Device.php @@ -373,7 +373,7 @@ public function getConnectionStatusAttribute(): string return 'never_connected'; } - $minutesOffline = $this->last_online_at->diffInMinutes(now()); + $minutesOffline = (int) $this->last_online_at->diffInMinutes(now(), true); if ($minutesOffline <= 10) { return 'online'; diff --git a/server/src/Models/DeviceEvent.php b/server/src/Models/DeviceEvent.php index 5b5d4a16f..375926858 100644 --- a/server/src/Models/DeviceEvent.php +++ b/server/src/Models/DeviceEvent.php @@ -311,7 +311,7 @@ public function getAgeMinutesAttribute(): int { $startTime = $this->occurred_at ?? $this->created_at; - return $startTime->diffInMinutes(now()); + return (int) $startTime->diffInMinutes(now(), true); } /** @@ -325,7 +325,7 @@ public function getProcessingDelayMinutesAttribute(): ?int $startTime = $this->occurred_at ?? $this->created_at; - return $startTime->diffInMinutes($this->processed_at); + return (int) $startTime->diffInMinutes($this->processed_at, true); } /** diff --git a/server/src/Models/Equipment.php b/server/src/Models/Equipment.php index ee53004fd..b6fabb1f1 100644 --- a/server/src/Models/Equipment.php +++ b/server/src/Models/Equipment.php @@ -297,7 +297,7 @@ public function getIsEquippedAttribute(): bool public function getAgeInDaysAttribute(): ?int { if ($this->purchased_at) { - return $this->purchased_at->diffInDays(now()); + return (int) $this->purchased_at->diffInDays(now(), true); } return null; @@ -314,7 +314,7 @@ public function getDepreciatedValueAttribute(): ?float $meta = $this->meta ?? []; $depreciationRate = $meta['depreciation_rate'] ?? 0.1; // 10% per year default - $yearsOld = $this->purchased_at->diffInYears(now()); + $yearsOld = (int) $this->purchased_at->diffInYears(now(), true); $depreciatedAmount = $this->purchase_price * ($depreciationRate * $yearsOld); $currentValue = $this->purchase_price - $depreciatedAmount; @@ -460,7 +460,7 @@ public function needsMaintenance(): bool ->first(); $lastMaintenanceDate = $lastMaintenance?->completed_at ?? $this->purchased_at; - $daysSinceLastMaintenance = $lastMaintenanceDate->diffInDays(now()); + $daysSinceLastMaintenance = (int) $lastMaintenanceDate->diffInDays(now(), true); return $daysSinceLastMaintenance >= $maintenanceIntervalDays; } @@ -534,7 +534,7 @@ public function getReplacementCostEstimate(): ?float // Estimate based on purchase price with inflation if ($this->purchase_price && $this->purchased_at) { - $yearsOld = $this->purchased_at->diffInYears(now()); + $yearsOld = (int) $this->purchased_at->diffInYears(now(), true); $inflationRate = $meta['inflation_rate'] ?? 0.03; // 3% default return $this->purchase_price * pow(1 + $inflationRate, $yearsOld); diff --git a/server/src/Models/Maintenance.php b/server/src/Models/Maintenance.php index 10457ef0f..847880fdc 100644 --- a/server/src/Models/Maintenance.php +++ b/server/src/Models/Maintenance.php @@ -234,7 +234,7 @@ public function getPerformedByNameAttribute(): ?string public function getDurationHoursAttribute(): ?float { if ($this->started_at && $this->completed_at) { - return $this->started_at->diffInHours($this->completed_at); + return (int) $this->started_at->diffInHours($this->completed_at, true); } return null; @@ -261,7 +261,7 @@ public function getDaysUntilDueAttribute(): ?int return null; } - return now()->diffInDays($this->scheduled_at, false); + return (int) now()->diffInDays($this->scheduled_at, false); } /** diff --git a/server/src/Models/Telematic.php b/server/src/Models/Telematic.php index 513f9aa1e..c89e30ba0 100644 --- a/server/src/Models/Telematic.php +++ b/server/src/Models/Telematic.php @@ -377,7 +377,7 @@ public function getConnectionStatus(): string return 'never_connected'; } - $minutesOffline = $this->last_seen_at->diffInMinutes(now()); + $minutesOffline = (int) $this->last_seen_at->diffInMinutes(now(), true); if ($minutesOffline <= 5) { return 'online'; diff --git a/server/src/Models/Warranty.php b/server/src/Models/Warranty.php index e5da4e2be..e0e858161 100644 --- a/server/src/Models/Warranty.php +++ b/server/src/Models/Warranty.php @@ -226,7 +226,7 @@ public function getDaysRemainingAttribute(): ?int return 0; } - return now()->diffInDays($this->end_date, false); + return (int) now()->diffInDays($this->end_date, false); } /** diff --git a/server/src/Models/WorkOrder.php b/server/src/Models/WorkOrder.php index f6688816a..4520644e8 100644 --- a/server/src/Models/WorkOrder.php +++ b/server/src/Models/WorkOrder.php @@ -261,7 +261,7 @@ public function getDaysUntilDueAttribute(): ?int return null; } - $days = now()->diffInDays($this->due_at, false); + $days = (int) now()->diffInDays($this->due_at, false); return $days; } @@ -526,7 +526,7 @@ public function getActualDuration(): ?float return null; } - return $this->opened_at->diffInHours($this->closed_at); + return (int) $this->opened_at->diffInHours($this->closed_at, true); } /** diff --git a/server/src/Support/Radar/RadarAgenda.php b/server/src/Support/Radar/RadarAgenda.php index c81cc25b5..d9cb74712 100644 --- a/server/src/Support/Radar/RadarAgenda.php +++ b/server/src/Support/Radar/RadarAgenda.php @@ -177,7 +177,7 @@ public static function handovers(array $open, array $shifts, array $drivers, arr 'key' => $item['key'], 'driver' => $item['subject'], 'rule' => $item['rule'], - 'shift' => ($item['window'] ?? []) + ['uuid' => $item['source']['uuid'] ?? null, 'public_id' => $item['source']['public_id'] ?? null, 'minutes_left' => $end ? max(0, $now->diffInMinutes($end, false)) : null], + 'shift' => ($item['window'] ?? []) + ['uuid' => $item['source']['uuid'] ?? null, 'public_id' => $item['source']['public_id'] ?? null, 'minutes_left' => $end ? max(0, (int) $now->diffInMinutes($end, false)) : null], 'orders' => array_map(fn ($order) => $order + ['finishes_after_shift' => self::finishesAfter($order, $end)], $driverOrders), 'active_orders' => (int) ($item['source']['active_orders'] ?? count($driverOrders)), 'suggested' => $suggested, @@ -276,7 +276,7 @@ protected static function entry(array $item, ?Carbon $at, bool $planned, Carbon if ($lane === RadarRules::LANE_ANYTIME) { $lane = self::LANE_BY_CATEGORY[$item['category'] ?? ''] ?? RadarRules::LANE_MAINTENANCE; } - $hours = max(1, $start->diffInHours($end)); + $hours = max(1, (int) $start->diffInHours($end, true)); return [ 'kind' => 'item', @@ -290,7 +290,7 @@ protected static function entry(array $item, ?Carbon $at, bool $planned, Carbon 'meta_line' => $item['meta_line'] ?? null, 'lane' => $lane, 'at' => $at?->toIso8601String(), - 'label' => $at ? $at->format($start->diffInHours($end) > 24 ? 'D H:i' : 'H:i') : null, + 'label' => $at ? $at->format((int) $start->diffInHours($end, true) > 24 ? 'D H:i' : 'H:i') : null, 'planned' => $planned, 'pct' => $at ? self::pct($at, $start, $hours) : null, 'state' => $item['state'] ?? null, @@ -308,7 +308,7 @@ protected static function shiftBar(array $shift, array $byDriver, Carbon $start, return null; } - $hours = max(1, $start->diffInHours($end)); + $hours = max(1, (int) $start->diffInHours($end, true)); $gaps = $byDriver[$driver['uuid'] ?? ''] ?? []; $handover = null; $worst = null; @@ -334,7 +334,7 @@ protected static function shiftBar(array $shift, array $byDriver, Carbon $start, 'end_at' => $to->toIso8601String(), 'label' => $from->format('H:i') . '–' . $to->format('H:i'), 'pct' => self::pct($from->max($start), $start, $hours), - 'width_pct' => max(1.0, round(($from->max($start)->diffInMinutes($to->min($end)) / 60) / $hours * 100, 2)), + 'width_pct' => max(1.0, round(((int) $from->max($start)->diffInMinutes($to->min($end), true) / 60) / $hours * 100, 2)), 'lane' => RadarRules::LANE_SHIFTS, 'severity' => $worst, 'gap_keys' => array_column($gaps, 'key'), @@ -365,7 +365,7 @@ protected static function ticks(Carbon $start, int $hours): array protected static function pct(Carbon $at, Carbon $start, int $hours): float { - return round(max(0, min(100, $start->diffInMinutes($at, false) / 60 / $hours * 100)), 2); + return round(max(0, min(100, (int) $start->diffInMinutes($at, false) / 60 / $hours * 100)), 2); } protected static function severityRank(?string $severity): int diff --git a/server/src/Support/Radar/RadarRules.php b/server/src/Support/Radar/RadarRules.php index e0bd123c2..125c17df4 100644 --- a/server/src/Support/Radar/RadarRules.php +++ b/server/src/Support/Radar/RadarRules.php @@ -477,7 +477,7 @@ public static function shiftItems(array $shifts, Carbon $now): array $source = ['type' => 'shift', 'uuid' => $shift['uuid'] ?? null, 'public_id' => $shift['public_id'] ?? null, 'driver_uuid' => $driver['uuid'] ?? null]; $record = self::record('management.drivers.index.details', $driver['public_id'] ?? null); - $minutesLate = $start->diffInMinutes($now, false); + $minutesLate = (int) $start->diffInMinutes($now, false); if (empty($shift['driver_online']) && in_array($status, self::SHIFT_NOT_STARTED_STATUSES, true) && $minutesLate >= self::LATE_START_MINUTES) { $items[] = self::item('shift_late_start', $driver, sprintf('%s scheduled %s, not online', $name, $start->format('H:i')), [ 'severity' => $minutesLate >= self::LATE_START_CRITICAL ? self::SEVERITY_CRITICAL : self::SEVERITY_WARNING, @@ -492,7 +492,7 @@ public static function shiftItems(array $shifts, Carbon $now): array if (empty($shift['driver_vehicle_uuid'])) { $items[] = self::item('shift_no_vehicle', $driver, sprintf('%s on shift since %s, no vehicle assigned', $name, $start->format('H:i')), [ 'severity' => self::SEVERITY_WARNING, - 'meta_line' => self::minutesWords($start->diffInMinutes($now)) . ' on shift', + 'meta_line' => self::minutesWords((int) $start->diffInMinutes($now, true)) . ' on shift', 'window' => $window, 'record' => $record, 'source' => $source, @@ -501,7 +501,7 @@ public static function shiftItems(array $shifts, Carbon $now): array } $activeOrders = (int) ($shift['active_orders'] ?? 0); - $minutesToEnd = $now->diffInMinutes($end, false); + $minutesToEnd = (int) $now->diffInMinutes($end, false); if ($activeOrders > 0 && $minutesToEnd <= self::HANDOVER_MINUTES) { $items[] = self::item('shift_handover', $driver, sprintf('%s shift ends in %s, %d active order%s still assigned', $name, self::minutesWords($minutesToEnd), $activeOrders, $activeOrders === 1 ? '' : 's'), [ 'severity' => self::SEVERITY_WARNING, @@ -1146,16 +1146,16 @@ public static function dueLabel(?Carbon $due, Carbon $now): ?string public static function overdueWords(Carbon $due, Carbon $now): string { - $minutes = $due->diffInMinutes($now); + $minutes = (int) $due->diffInMinutes($now, true); if ($minutes < 60) { return max(1, $minutes) . 'm overdue'; } - $hours = $due->diffInHours($now); + $hours = (int) $due->diffInHours($now, true); if ($hours < 24) { return $hours . 'h overdue'; } - return $due->diffInDays($now) . 'd overdue'; + return (int) $due->diffInDays($now, true) . 'd overdue'; } public static function dueInWords(Carbon $due, Carbon $now): string @@ -1167,7 +1167,7 @@ public static function dueInWords(Carbon $due, Carbon $now): string return 'tomorrow'; } - $days = $now->copy()->startOfDay()->diffInDays($due->copy()->startOfDay()); + $days = (int) $now->copy()->startOfDay()->diffInDays($due->copy()->startOfDay(), true); if ($days <= self::DUE_SOON_DAYS) { return sprintf('in %d day%s', $days, $days === 1 ? '' : 's'); } @@ -1180,7 +1180,7 @@ public static function dueInWords(Carbon $due, Carbon $now): string */ public static function agoWords(Carbon $then, Carbon $now): string { - $minutes = max(0, $then->diffInMinutes($now, false)); + $minutes = max(0, (int) $then->diffInMinutes($now, false)); if ($minutes < 60) { return max(1, $minutes) . 'm ago'; } diff --git a/server/src/Support/Telematics/TelematicService.php b/server/src/Support/Telematics/TelematicService.php index 250ea5374..dfe50ff8b 100644 --- a/server/src/Support/Telematics/TelematicService.php +++ b/server/src/Support/Telematics/TelematicService.php @@ -674,7 +674,7 @@ protected function connectionStatusForDevice(Device $device, ?Carbon $lastSeen = return 'never_connected'; } - $minutesOffline = Carbon::parse($lastSeen)->diffInMinutes(now()); + $minutesOffline = (int) Carbon::parse($lastSeen)->diffInMinutes(now(), true); if ($minutesOffline <= 10) { return 'online'; diff --git a/server/src/Support/Telematics/Telemetry/Ingestor.php b/server/src/Support/Telematics/Telemetry/Ingestor.php index 9b790900d..e20b6e170 100644 --- a/server/src/Support/Telematics/Telemetry/Ingestor.php +++ b/server/src/Support/Telematics/Telemetry/Ingestor.php @@ -79,7 +79,7 @@ public function ingest(Telematic $telematic, TelemetryProviderInterface $provide $device->last_online_at = Carbon::parse($contact)->utc()->toDateTimeString(); $device->online = $device->last_online_at->gt(now()->subMinutes(10)); if (in_array($device->status, ['online', 'recently_offline', 'offline', 'long_offline', 'never_connected'], true)) { - $minutes = $device->last_online_at->diffInMinutes(now()); + $minutes = (int) $device->last_online_at->diffInMinutes(now(), true); $device->status = $minutes <= 10 ? 'online' : ($minutes <= 60 ? 'recently_offline' : ($minutes <= 1440 ? 'offline' : 'long_offline')); } $device->meta = array_replace_recursive($device->meta ?? [], ['telemetry' => ['provider_at' => $contact, 'last_received_at' => $received]]); diff --git a/server/src/Tracking/TrackingContextBuilder.php b/server/src/Tracking/TrackingContextBuilder.php index 870e2b223..ac3db93c3 100644 --- a/server/src/Tracking/TrackingContextBuilder.php +++ b/server/src/Tracking/TrackingContextBuilder.php @@ -30,7 +30,7 @@ public function build(Order $order, TrackingOptions $options): TrackingContext $payload = $order->payload; $driver = $order->driverAssigned; $warnings = []; - $driverLocationAge = $driver?->updated_at ? now()->diffInSeconds($driver->updated_at) : null; + $driverLocationAge = $driver?->updated_at ? (int) now()->diffInSeconds($driver->updated_at, true) : null; $origin = null; $driverLocation = null; diff --git a/server/src/Traits/Maintainable.php b/server/src/Traits/Maintainable.php index 2dcbb02f6..06e07afeb 100644 --- a/server/src/Traits/Maintainable.php +++ b/server/src/Traits/Maintainable.php @@ -111,7 +111,7 @@ protected function checkIntervalsSinceDate($date): bool // Check time-based intervals $maintenanceIntervalDays = $specs['maintenance_interval_days'] ?? $meta['maintenance_interval_days'] ?? null; - if ($maintenanceIntervalDays && $date->diffInDays(now()) >= $maintenanceIntervalDays) { + if ($maintenanceIntervalDays && (int) $date->diffInDays(now(), true) >= $maintenanceIntervalDays) { return true; } @@ -199,7 +199,7 @@ public function getAverageMaintenanceDuration(int $days = 365): ?float } $totalHours = $maintenances->sum(function ($maintenance) { - return $maintenance->started_at->diffInHours($maintenance->completed_at); + return (int) $maintenance->started_at->diffInHours($maintenance->completed_at, true); }); return $totalHours / $maintenances->count(); diff --git a/server/tests/Unit/Support/CarbonDiffContractTest.php b/server/tests/Unit/Support/CarbonDiffContractTest.php new file mode 100644 index 000000000..c795aa81d --- /dev/null +++ b/server/tests/Unit/Support/CarbonDiffContractTest.php @@ -0,0 +1,118 @@ +copy()->subSeconds(90), $now))->toBe('1m overdue') + ->and(RadarRules::overdueWords($now->copy()->subMinutes(150), $now))->toBe('2h overdue') + ->and(RadarRules::overdueWords($now->copy()->subHours(60), $now))->toBe('2d overdue'); +}); + +test('due words count whole days forward', function () { + $now = Carbon::parse('2026-09-15 12:00:00', 'UTC'); + + expect(RadarRules::dueInWords($now->copy()->addDays(3)->addHours(6), $now))->toBe('in 3 days'); +}); + +test('ago words clamp a future time and keep whole minutes', function () { + $now = Carbon::parse('2026-09-15 12:00:00', 'UTC'); + + expect(RadarRules::agoWords($now->copy()->addMinutes(5), $now))->toBe('1m ago') + ->and(RadarRules::agoWords($now->copy()->subSeconds(150), $now))->toBe('2m ago'); +}); + +test('agenda percentages use whole minutes and whole hours', function () { + $start = Carbon::parse('2026-09-15 08:00:00', 'UTC'); + $pct = new ReflectionMethod(RadarAgenda::class, 'pct'); + + expect($pct->invoke(null, $start->copy()->addSeconds(5430), $start, 10))->toBe(15.0) + ->and($pct->invoke(null, $start->copy()->subHour(), $start, 10))->toBe(0.0); +}); + +test('replay delay is a whole absolute number of seconds', function () { + $command = (new ReflectionClass(ReplayVehicleLocations::class))->newInstanceWithoutConstructor(); + $delay = new ReflectionMethod(ReplayVehicleLocations::class, 'calculateReplayDelay'); + + expect($delay->invoke($command, '2026-01-01T10:00:00Z', '2026-01-01T10:00:08.900Z', 2.0))->toBe([8, 4.0]) + ->and($delay->invoke($command, '2026-01-01T10:00:08.900Z', '2026-01-01T10:00:00Z', 2.0))->toBe([8, 4.0]); +}); + +test('position metrics keep dwell, acceleration and duration positive and whole', function () { + $position = fn (string $uuid, float $speed, string $at) => (object) [ + 'uuid' => $uuid, + 'speed' => $speed, + 'coordinates' => new Point(1.30, 103.80), + 'created_at' => Carbon::parse($at, 'UTC'), + ]; + $positions = collect([ + $position('a', 0.0, '2026-07-28 08:00:00'), + $position('b', 0.0, '2026-07-28 08:05:00.700000'), + $position('c', 10.0, '2026-07-28 08:05:02.900000'), + ]); + + $metrics = (new ReflectionMethod(PositionController::class, 'calculateMetrics')) + ->invoke(new PositionController(), $positions); + + expect($metrics['total_duration'])->toBe(302) + ->and($metrics['dwell_count'])->toBe(1) + ->and($metrics['dwell_times'][0]['duration'])->toBe(300) + ->and($metrics['acceleration_count'])->toBe(1) + ->and($metrics['acceleration_events'][0]['acceleration'])->toBe(5.0); +}); + +test('equipment age, depreciation and replacement cost use whole years', function () { + $equipment = new Equipment(); + $equipment->setRawAttributes([ + 'purchased_at' => Carbon::parse('2023-03-15 00:00:00', 'UTC'), + 'purchase_price' => 1000, + 'meta' => ['depreciation_rate' => 0.1, 'inflation_rate' => 0.1], + ], true); + + expect($equipment->age_in_days)->toBe(1280) + ->and($equipment->depreciated_value)->toEqualWithDelta(700.0, 0.0001) + ->and($equipment->getReplacementCostEstimate())->toEqualWithDelta(1331.0, 0.0001); +}); + +test('days until due stay signed whole days', function () { + $maintenance = new Maintenance(); + $maintenance->setRawAttributes(['scheduled_at' => now()->addHours(36), 'status' => 'scheduled'], true); + $overdue = new WorkOrder(); + $overdue->setRawAttributes(['due_at' => now()->subHours(36), 'status' => 'open'], true); + + expect($maintenance->days_until_due)->toBe(1) + ->and($overdue->days_until_due)->toBe(-1); +}); + +test('repair durations stay whole hours', function () { + $maintenance = new Maintenance(); + $maintenance->setRawAttributes(['started_at' => now()->subMinutes(150), 'completed_at' => now()], true); + $workOrder = new WorkOrder(); + $workOrder->setRawAttributes(['opened_at' => now()->subMinutes(150), 'closed_at' => now()], true); + + expect($maintenance->duration_hours)->toBe(2.0) + ->and($workOrder->getActualDuration())->toBe(2.0); +}); diff --git a/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php b/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php index 50b4ce66b..807f3ebfe 100644 --- a/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php +++ b/server/tests/Unit/Tracking/TrackingIntelligenceAndContextTest.php @@ -196,7 +196,8 @@ function fleetopsTrackingSeedOrder(SQLiteConnection $connection, bool $withDrive ->and($context->stops)->toHaveCount(2) ->and($context->remainingStops)->toHaveCount(2) ->and($context->activeStop)->not->toBeNull() - ->and($context->warnings)->toContain('stale_driver_location'); + ->and($context->warnings)->toContain('stale_driver_location') + ->and($context->driverLocationAgeSeconds)->toBeInt()->toBeGreaterThanOrEqual(3600); }); test('context builder falls back to payload origin without a driver', function () { From 3e1ddef159e24d23f51ed493522d70a38369d516 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 4 Nov 2026 16:42:28 +0800 Subject: [PATCH 02/29] chore(l12): keep fresh-install columns identical without Doctrine Restate nullable on ->change() calls, which Laravel 11+ no longer preserves. Replace unsignedDecimal with decimal()->unsigned(), set DOUBLE(12,2) on routes in SQL since Blueprint::double() drops total and places, and check indexes through TableIndexes. Fresh MySQL schema is unchanged on Laravel 10. --- .../2023_04_27_053456_create_routes_table.php | 11 +++++++++-- ...023_11_03_072503_refactor_issues_table_columns.php | 4 ++-- ...2024_02_18_100209_add_avatar_url_columns_table.php | 4 ++-- ...03_004854_increase_service_quote_amount_column.php | 4 ++-- ...itional_spec_columns_for_assets_vehicles_table.php | 4 ++-- ...dd_performance_indexes_to_fleetops_core_tables.php | 7 ++----- ...001_add_orchestrator_columns_to_vehicles_table.php | 4 ++-- ...004_add_orchestrator_columns_to_payloads_table.php | 4 ++-- ...redundant_capacity_columns_from_payloads_table.php | 4 ++-- ...0002_rename_capacity_columns_on_vehicles_table.php | 2 +- 10 files changed, 26 insertions(+), 22 deletions(-) diff --git a/server/migrations/2023_04_27_053456_create_routes_table.php b/server/migrations/2023_04_27_053456_create_routes_table.php index 0c22f685a..f1f0899db 100644 --- a/server/migrations/2023_04_27_053456_create_routes_table.php +++ b/server/migrations/2023_04_27_053456_create_routes_table.php @@ -19,12 +19,19 @@ public function up() $table->char('company_uuid', 36)->nullable()->index(); $table->char('order_uuid', 36)->nullable()->index(); $table->json('details')->nullable(); - $table->double('total_distance', 12, 2)->nullable(); - $table->double('total_time', 12, 2)->nullable(); + $table->double('total_distance')->nullable(); + $table->double('total_time')->nullable(); $table->softDeletes(); $table->timestamp('created_at')->nullable()->index(); $table->timestamp('updated_at')->nullable(); }); + + // Blueprint::double() only takes total and places before Laravel 11, so set them in SQL. + if (Schema::getConnection()->getDriverName() === 'mysql') { + Schema::getConnection()->statement( + 'ALTER TABLE `routes` MODIFY COLUMN `total_distance` DOUBLE(12,2) NULL, MODIFY COLUMN `total_time` DOUBLE(12,2) NULL' + ); + } } /** diff --git a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php index 3727a3a03..42e4e4886 100644 --- a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php +++ b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php @@ -17,7 +17,7 @@ public function up() $table->string('category')->nullable()->after('type'); $table->json('tags')->nullable()->after('priority'); $table->json('meta')->nullable()->after('priority'); - $table->mediumText('report')->change(); + $table->mediumText('report')->nullable()->change(); $table->foreignUuid('reported_by_uuid')->nullable()->after('assigned_to_uuid')->references('uuid')->on('users')->onDelete('cascade'); }); } @@ -33,7 +33,7 @@ public function down() $table->string('longitude')->nullable()->after('location'); $table->string('latitude')->nullable()->after('location'); $table->string('odometer')->nullable()->after('location'); - $table->string('report')->change(); + $table->string('report')->nullable()->change(); $table->dropForeign(['reported_by_uuid']); $table->dropColumn(['reported_by_uuid', 'meta', 'tags', 'category']); }); diff --git a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php index 13bb4c1be..ecc5166fa 100644 --- a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php +++ b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php @@ -14,7 +14,7 @@ public function up() { // Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->mediumText('avatar_url')->change(); + $table->mediumText('avatar_url')->nullable()->change(); }); // Add avatar url column to places @@ -38,7 +38,7 @@ public function down() // @todo this can break migrations if avatar url is over 300 characters to we need to remove this and keep mediumtext // Reverse: Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->string('avatar_url', 300)->change(); + $table->string('avatar_url', 300)->nullable()->change(); }); // Reverse: Add avatar url column to places diff --git a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php index 2b658b3d8..acb915210 100644 --- a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php +++ b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php @@ -11,7 +11,7 @@ public function up(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->bigInteger('amount')->change(); + $table->bigInteger('amount')->nullable()->change(); }); } @@ -21,7 +21,7 @@ public function up(): void public function down(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->integer('amount')->change(); + $table->integer('amount')->nullable()->change(); }); } }; diff --git a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php index 00f072dd9..da5711049 100644 --- a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php +++ b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php @@ -23,7 +23,7 @@ public function up(): void $table->mediumText('notes')->after('meta')->nullable(); $table->string('usage_type')->after('type')->nullable(); $table->string('measurement_system')->after('type')->nullable(); - $table->json('vin_data')->change(); + $table->json('vin_data')->nullable()->change(); $table->renameColumn('model_data', 'specs'); }); @@ -70,7 +70,7 @@ public function down(): void $table->dropColumn('usage_type'); $table->dropColumn('measurement_system'); $table->dropColumn('ownership_type'); - $table->mediumText('vin_data')->change(); + $table->mediumText('vin_data')->nullable()->change(); $table->renameColumn('specs', 'model_data'); }); } diff --git a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php index 17b129cc5..a1065bdf4 100644 --- a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php +++ b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php @@ -1,5 +1,6 @@ getDoctrineSchemaManager(); - $indexes = $doctrineSchemaManager->listTableIndexes($table); - - return isset($indexes[$index]); + return isset(TableIndexes::for($table)[$index]); } catch (Exception $e) { return false; } diff --git a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php index e9555ac8f..e4725974e 100644 --- a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php +++ b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php @@ -25,8 +25,8 @@ public function up(): void // Skills / capabilities $table->json('skills')->nullable()->after('status'); // Multi-dimensional capacity - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); // Route constraints diff --git a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php index 002226d38..5703f5c7a 100644 --- a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php +++ b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php @@ -20,8 +20,8 @@ public function up(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php index 2b028548a..df1eed0c3 100644 --- a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php +++ b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php @@ -35,8 +35,8 @@ public function up(): void public function down(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php index 0f5e809d7..e9f65903a 100644 --- a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php +++ b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php @@ -39,7 +39,7 @@ public function down(): void { Schema::table('vehicles', function (Blueprint $table) { // Restore the dropped column - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); // Reverse the renames $table->renameColumn('payload_capacity_volume', 'capacity_volume_m3'); From 9d144ba257a1c617f0b9377402ab2fd184320a63 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 17:34:40 +0800 Subject: [PATCH 03/29] feat(customers): add rider routes with owner checks Give a rider app what it needs on /v1/customers, limited to the rider's own records: - request-code answers the same for known and unknown numbers - verify-code reports new_customer only after the code is proven - places/search, geocode, and saving, editing and deleting places - dispatch, cancel, driver, tracker and ETA for the rider's own orders - a narrow customer socket principal Also: - Make the signup password optional - Require a code for the new number to change phone on customers/me - Refuse expired fares when a rider books - Stop fare previews storing a place per request - Treat another company's service quote as not found --- .../Controllers/Api/v1/CustomerController.php | 415 +++++++++++++++++- .../Api/v1/ServiceQuoteController.php | 3 +- .../Http/Requests/CreateCustomerRequest.php | 2 +- server/src/Models/ServiceQuote.php | 12 +- server/src/Support/SocketChannels.php | 35 ++ server/src/routes.php | 12 + .../ApiCustomerControllerContractsTest.php | 180 +++++++- server/tests/CustomerEndpointTest.php | 2 +- 8 files changed, 649 insertions(+), 12 deletions(-) diff --git a/server/src/Http/Controllers/Api/v1/CustomerController.php b/server/src/Http/Controllers/Api/v1/CustomerController.php index 0fc7479c8..0ce732914 100644 --- a/server/src/Http/Controllers/Api/v1/CustomerController.php +++ b/server/src/Http/Controllers/Api/v1/CustomerController.php @@ -18,6 +18,7 @@ use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Support\CustomerAuth; +use Fleetbase\FleetOps\Support\PlaceSearch; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; use Fleetbase\LaravelMysqlSpatial\Types\Point as SpatialPoint; @@ -48,6 +49,11 @@ class CustomerController extends Controller public const DEACTIVATED_LOGIN_MESSAGE = 'This customer login has been deactivated.'; + /** + * Relations a rider's order is returned with. + */ + protected const RIDER_ORDER_RELATIONS = ['payload', 'payload.pickup', 'payload.dropoff']; + /** * Wrong guesses a single code tolerates before it locks itself (core's check()). */ @@ -183,7 +189,10 @@ public function create(CreateCustomerRequest $request) 'email' => $isEmail ? $identity : $request->input('email'), 'phone' => $isEmail ? static::phone($request->input('phone')) : $identity, ]); - $user->password = $request->input('password'); + // Phone riders sign in with a code, so they may have no password at all. + if ($request->filled('password')) { + $user->password = $request->input('password'); + } $user->save(); $user->setUserType('customer'); } else { @@ -200,7 +209,9 @@ public function create(CreateCustomerRequest $request) $update['email'] = $request->input('email'); } $user->fill($update); - $user->password = $request->input('password'); // mutator hashes + if ($request->filled('password')) { + $user->password = $request->input('password'); // mutator hashes + } $user->save(); if (!$user->type) { $user->setUserType('customer'); @@ -431,6 +442,28 @@ public function loginWithPhone(Request $request) return static::sendFailureResponse($smsFailure, 'Unable to send verification code.'); } + /** + * Send a code to a phone number without revealing whether it has an account. An + * existing rider gets a login code and a new one gets a signup code; both answer the + * same way. {@see verifyCode} tells them apart once the code is proven. + */ + public function requestCode(Request $request) + { + $phone = $request->input('phone') ?? $request->input('identity'); + if (!$phone || $this->isEmail($phone)) { + return response()->apiError('A phone number is required.', 400); + } + + $phone = static::phone($phone); + $input = ['phone' => $phone, 'identity' => $phone, 'mode' => 'sms']; + + $response = $this->findActiveUserByIdentity($phone, 'phone') + ? $this->loginWithPhone(Request::create('', 'POST', $input)) + : $this->requestCreationCode(VerifyCreateCustomerRequest::create('', 'POST', $input)); + + return $response->getStatusCode() === 200 ? response()->json(['status' => 'ok']) : $response; + } + /** * Verify the SMS/email code from {@see loginWithPhone} and issue a token. */ @@ -446,7 +479,17 @@ public function verifyCode(Request $request) $user = $this->findUserForVerification($identity); if (!$user) { - return response()->apiError('Unable to verify code.'); + // A proven signup code from requestCode(). It stays live for create(), which uses it up. + $signupCode = $this->verificationCodeMatches([ + 'code' => $code, + 'for' => 'fleetops_create_customer', + 'meta->identity' => $identity, + ]); + if ($signupCode || $this->verificationBypassMatches($identity, $code)) { + return response()->json(['status' => 'new_customer']); + } + + return response()->apiError('Invalid verification code.'); } if ($user->status === 'inactive') { @@ -598,6 +641,12 @@ public function updateMe(UpdateContactRequest $request) $input = $request->only(['name', 'title', 'email', 'phone', 'meta']); if (isset($input['phone'])) { $input['phone'] = static::phone($input['phone']); + if ($input['phone'] !== $customer->phone) { + $refusal = $this->refusePhoneChange($customer, $input['phone'], $request->input('phone_code')); + if ($refusal) { + return $refusal; + } + } } // Photo handling. @@ -753,6 +802,11 @@ public function createOrder(CreateCustomerOrderRequest $request) return response()->apiError('No order config available for this company.', 422); } + $serviceQuote = $this->resolveServiceQuote($request); + if ($serviceQuote instanceof ServiceQuote && ($serviceQuote->company_uuid !== $sessionCompany || $serviceQuote->expired_at?->isPast())) { + return response()->apiError('This fare has expired. Please get a new one.', 422); + } + // Build the Payload (matching the operator OrderController convention). // - `payload` may be an array of {pickup, dropoff, return, waypoints, entities} // - `payload` may be a string public_id referencing an existing Payload @@ -790,7 +844,6 @@ public function createOrder(CreateCustomerOrderRequest $request) // If the customer picked a ServiceQuote up front, consume it now to // lock the pricing onto the order's PurchaseRate (mirrors how // OrderController::create handles `service_quote`). - $serviceQuote = $this->resolveServiceQuote($request); if ($serviceQuote instanceof ServiceQuote) { $order->purchaseServiceQuote($serviceQuote); } @@ -859,6 +912,269 @@ public function places(Request $request) return $this->placeResourceCollection($results); } + /** + * Search this rider's saved places and the geocoder. Other riders' places are never + * returned, and neither are unowned rows, which hold addresses from other riders' trips. + */ + public function searchPlaces(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + $query = Place::where('company_uuid', $this->sessionCompany()) + ->where('owner_uuid', $customer->uuid) + ->whereNull('deleted_at'); + + return $this->placeResourceCollection($this->runPlaceSearch($query, (string) $request->input('query', ''), [ + 'limit' => min((int) $request->input('limit', 10), 50), + 'geo' => true, + 'latitude' => $request->input('latitude', false), + 'longitude' => $request->input('longitude', false), + 'no_query_order' => 'name_desc', + ])); + } + + /** + * Look up an address or coordinates. Nothing is stored. + */ + public function geocode(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + $query = trim((string) $request->input('query', '')); + $latitude = $request->input('latitude'); + $longitude = $request->input('longitude'); + if ($query === '' && (!is_numeric($latitude) || !is_numeric($longitude))) { + return response()->apiError('A query or coordinates are required.', 400); + } + + return $this->placeResourceCollection($this->geocodePlaces($query, $latitude, $longitude)); + } + + /** + * Save a place for the authenticated rider. + */ + public function savePlace(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + $location = $this->savedPlaceLocation($request); + if (!$location || !trim((string) $request->input('name'))) { + return response()->apiError('A name, latitude and longitude are required.', 422); + } + + $place = $this->createPlace(array_merge($this->savedPlaceAttributes($request), [ + 'company_uuid' => $this->sessionCompany(), + 'owner_uuid' => $customer->uuid, + 'owner_type' => get_class($customer), + 'location' => $location, + ])); + + return $this->placeResource($place); + } + + /** + * Update one of the authenticated rider's saved places. + */ + public function updatePlace(string $id, Request $request) + { + $place = $this->ownedPlace($id); + if (!$place) { + return response()->apiError('Place not found.', 404); + } + + $attributes = $this->savedPlaceAttributes($request); + if ($request->hasAny(['latitude', 'longitude'])) { + $location = $this->savedPlaceLocation($request); + if (!$location) { + return response()->apiError('A latitude and longitude are required.', 422); + } + $attributes['location'] = $location; + } + + $place->update($attributes); + + return $this->placeResource($place); + } + + /** + * Delete one of the authenticated rider's saved places. + */ + public function deletePlace(string $id) + { + $place = $this->ownedPlace($id); + if (!$place) { + return response()->apiError('Place not found.', 404); + } + + $place->delete(); + + return response()->json(['status' => 'ok']); + } + + /** + * Send a code to the number a rider wants to change to, so {@see updateMe} can prove + * they hold it. + */ + public function requestPhoneChangeCode(Request $request) + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + if (!$request->filled('phone') || !$customer->user_uuid) { + return response()->apiError('A phone number is required.', 400); + } + + $phone = static::phone($request->input('phone')); + + // Answer the same for a number another account holds, so this can't discover accounts. + // updateMe() refuses the change if it is ever attempted. + if ($this->findActiveUserByIdentity($phone, 'phone')) { + return response()->json(['status' => 'ok']); + } + + $subject = $this->findUserByUuid($customer->user_uuid); + if (!$subject) { + return response()->apiError('Unable to send verification code.'); + } + + try { + $this->generateSmsVerification($subject, 'fleetops_customer_phone_change', [ + 'phone' => $phone, + 'hashed' => true, + 'messageCallback' => fn ($verification) => 'Your ' . config('app.name') . ' verification code is ' . $verification->code, + 'meta' => ['identity' => $phone], + ]); + } catch (SmsBlockedException $e) { + return static::smsBlockedResponse($e); + } catch (\Throwable $e) { + return static::sendFailureResponse($e, 'Unable to send verification code.'); + } + + return response()->json(['status' => 'ok']); + } + + /** + * Request a driver for one of the authenticated rider's orders. + */ + public function dispatchOrder(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if ($order->dispatched) { + return response()->apiError('Order has already been dispatched.', 422); + } + if ($order->status !== 'created') { + return response()->apiError('This order can no longer be dispatched.', 422); + } + if (!$order->hasDriverAssigned && !$order->adhoc) { + return response()->apiError('No driver is available for this order.', 422); + } + + $order->dispatch(); + $order->insertDispatchActivity(); + + return $this->orderResource($order->fresh(static::RIDER_ORDER_RELATIONS)); + } + + /** + * Cancel one of the authenticated rider's orders. + */ + public function cancelOrder(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + if (in_array($order->status, ['completed', 'canceled'], true)) { + return response()->apiError('This order can no longer be canceled.', 422); + } + + $reason = $request->input('reason'); + if (is_string($reason) && trim($reason) !== '') { + $order->cancelWithReason(Str::limit(trim($reason), 1000, '')); + } else { + $order->cancel(); + } + + return $this->orderResource($order->fresh(static::RIDER_ORDER_RELATIONS)); + } + + /** + * The driver and car a rider needs to find their ride. The driver's contact details stay + * out, because riders and drivers don't share phone numbers. + */ + public function orderDriver(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $driver = $order->driverAssigned; + $vehicle = $order->vehicleAssigned ?? $driver?->vehicle; + if (!$driver) { + return response()->json(['driver' => null, 'vehicle' => null]); + } + + return response()->json([ + 'driver' => ['name' => $driver->name, 'photo_url' => $driver->photo_url, 'location' => $driver->location], + 'vehicle' => $vehicle ? [ + 'make' => $vehicle->make, + 'model' => $vehicle->model, + 'color' => $vehicle->color ?? null, + 'plate_number' => $vehicle->plate_number, + ] : null, + ]); + } + + /** + * Live tracking data for one of the authenticated rider's orders. + */ + public function orderTracker(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + try { + return response()->json($order->tracker()->toArray($request->only(['provider', 'fallbacks', 'traffic_enabled']))); + } catch (\Throwable) { + return response()->apiError('Unable to track this order.', 503); + } + } + + /** + * ETA for one of the authenticated rider's orders. + */ + public function orderEta(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + try { + return response()->json($order->tracker()->eta($request->only(['provider', 'fallbacks', 'traffic_enabled']))); + } catch (\Throwable) { + return response()->apiError('Unable to track this order.', 503); + } + } + /** * Register a push-notification device for the authenticated customer's user. */ @@ -892,6 +1208,65 @@ public function registerDevice(Request $request) | Helpers * ============================================================ */ + /** + * Why a rider can't change to this phone number, or null if they can. A number is only + * accepted with a code sent to it, and never if another account holds it. + */ + protected function refusePhoneChange(Contact $customer, string $phone, mixed $code): ?JsonResponse + { + $holder = $this->findActiveUserByIdentity($phone, 'phone'); + $proven = $code && $customer->user_uuid && $this->verificationCodeExists([ + 'subject_uuid' => $customer->user_uuid, + 'code' => $code, + 'for' => 'fleetops_customer_phone_change', + 'meta->identity' => $phone, + ]); + + if (!$proven || ($holder && $holder->uuid !== $customer->user_uuid)) { + return response()->apiError('Changing your phone number needs a valid verification code.', 422); + } + + return null; + } + + protected function ownedOrder(string $id): ?Order + { + $customer = $this->currentCustomer(); + + try { + $order = $this->findOrderOrFail($id); + } catch (\Illuminate\Database\Eloquent\ModelNotFoundException) { + return null; + } + + return $customer && $order->customer_uuid === $customer->uuid ? $order : null; + } + + protected function ownedPlace(string $id): ?Place + { + $customer = $this->currentCustomer(); + $place = $customer ? $this->findPlaceByPublicId($id, (string) $this->sessionCompany()) : null; + + return $place && $place->owner_uuid === $customer->uuid ? $place : null; + } + + protected function savedPlaceAttributes(Request $request): array + { + return $request->only(['name', 'street1', 'street2', 'city', 'province', 'postal_code', 'neighborhood', 'district', 'building', 'country', 'phone', 'meta']); + } + + protected function savedPlaceLocation(Request $request): ?SpatialPoint + { + $latitude = $request->input('latitude'); + $longitude = $request->input('longitude'); + + if (!is_numeric($latitude) || !is_numeric($longitude) || abs($latitude) > 90 || abs($longitude) > 180) { + return null; + } + + return new SpatialPoint((float) $latitude, (float) $longitude); + } + protected function isEmail(?string $identity): bool { return Utils::isEmail($identity); @@ -1033,6 +1408,23 @@ protected function verificationCodeExists(array $attributes): bool return $this->findVerificationCode($attributes) !== null; } + /** + * Whether the submitted code verifies, leaving it live. A wrong guess still counts + * against it. + */ + protected function verificationCodeMatches(array $attributes): bool + { + $code = (string) ($attributes['code'] ?? ''); + + foreach ($this->liveVerificationCodes($attributes) as $verificationCode) { + if ($verificationCode->check($code, static::CODE_CHECK_ATTEMPTS) === VerificationCode::CHECK_VALID) { + return true; + } + } + + return false; + } + /** * The live code the submitted code verified against, used up so it cannot verify * again, or null. `$attributes` carries `code`, `for` and either `subject_uuid` or @@ -1204,6 +1596,21 @@ protected function placeResourceCollection(mixed $results): mixed return PlaceResource::collection($results); } + protected function placeResource(Place $place): mixed + { + return new PlaceResource($place); + } + + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed + { + return PlaceSearch::search($query, $searchQuery, $options); + } + + protected function geocodePlaces(string $query, mixed $latitude, mixed $longitude): mixed + { + return PlaceSearch::geocode($query, $latitude, $longitude); + } + /** * Normalize a phone number to international format (with leading `+`). */ diff --git a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php index 17518b775..8f20b463e 100644 --- a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php +++ b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php @@ -342,7 +342,8 @@ protected function generateServiceQuoteRequestId(): string protected function createPlaceFromMixed(mixed $value): Place { - return Place::createFromMixed($value); + // A preview must not leave a place behind for every fare a rider checks. + return Place::createFromMixed($value, [], !$this->previewOnly); } protected function findPlaceByPublicId(string $publicId): ?Place diff --git a/server/src/Http/Requests/CreateCustomerRequest.php b/server/src/Http/Requests/CreateCustomerRequest.php index 761606858..e019f916e 100644 --- a/server/src/Http/Requests/CreateCustomerRequest.php +++ b/server/src/Http/Requests/CreateCustomerRequest.php @@ -33,7 +33,7 @@ public function rules(): array // non-production testing bypass (fleetops.customers.verification_bypass_code). 'code' => 'required|string', 'name' => 'required|string', - 'password' => 'required|string|min:8', + 'password' => 'nullable|string|min:8', 'email' => [ 'email', 'nullable', Rule::unique('contacts')->where(function ($query) { diff --git a/server/src/Models/ServiceQuote.php b/server/src/Models/ServiceQuote.php index e5b30a9b3..078723d3c 100644 --- a/server/src/Models/ServiceQuote.php +++ b/server/src/Models/ServiceQuote.php @@ -147,16 +147,24 @@ public static function resolveFromRequest(Request|CreateOrderRequest|UpdateOrder } if (Str::isUuid($serviceQuote)) { - $serviceQuote = static::where('uuid', $serviceQuote)->first(); + $serviceQuote = static::forSessionCompany()->where('uuid', $serviceQuote)->first(); } if (Utils::isPublicId($serviceQuote)) { - $serviceQuote = static::where('public_id', $serviceQuote)->first(); + $serviceQuote = static::forSessionCompany()->where('public_id', $serviceQuote)->first(); } return $serviceQuote; } + /** + * A quote from another company is treated as not found. + */ + protected static function forSessionCompany() + { + return session('company') ? static::where('company_uuid', session('company')) : static::query(); + } + public function getPluralName(): string { if (isset($this->pluralName)) { diff --git a/server/src/Support/SocketChannels.php b/server/src/Support/SocketChannels.php index 84c7590c2..d7cd9860a 100644 --- a/server/src/Support/SocketChannels.php +++ b/server/src/Support/SocketChannels.php @@ -110,6 +110,7 @@ public static function register(SocketChannelRegistry $registry): void $registry->register(TrackingChannel::PREFIX, static fn (): bool => false); $registry->registerPrincipalResolver([static::class, 'driverPrincipal']); + $registry->registerPrincipalResolver([static::class, 'customerPrincipal']); } /** @@ -307,6 +308,40 @@ public static function driverPrincipal(Request $request, $user): ?SocketPrincipa ); } + /** + * A customer's token gets the customer principal, so its socket reaches only their own + * records and not the whole company. + */ + public static function customerPrincipal(Request $request, $user): ?SocketPrincipal + { + if (!$user instanceof User || !$user->uuid || !$user->isType('customer')) { + return null; + } + + $companyUuid = session('company') ?: $user->company_uuid; + if (!$companyUuid) { + return null; + } + + $customer = Contact::where('user_uuid', $user->uuid)->where('company_uuid', $companyUuid)->where('type', 'customer')->first(); + if (!$customer) { + return null; + } + + $connection = $customer->getConnectionName(); + $cpid = Company::on($connection)->where('uuid', $companyUuid)->value('public_id'); + + return new SocketPrincipal( + kind: 'customer', + sub: (string) $customer->uuid, + cid: (string) $companyUuid, + cpid: is_string($cpid) && $cpid !== '' ? $cpid : null, + env: $connection === 'sandbox' ? 'test' : 'live', + ids: array_values(array_filter([$customer->uuid, $customer->public_id, $user->uuid])), + adm: false, + ); + } + /** * The customer's orders that are not completed or canceled. */ diff --git a/server/src/routes.php b/server/src/routes.php index 2159f61fa..3cc67ea90 100644 --- a/server/src/routes.php +++ b/server/src/routes.php @@ -103,6 +103,7 @@ function ($router) { $router->post('/', 'CustomerController@create'); $router->post('login', 'CustomerController@login'); $router->post('login-with-sms', 'CustomerController@loginWithPhone')->middleware('throttle:5,1,fleetops-sms'); + $router->post('request-code', 'CustomerController@requestCode')->middleware('throttle:5,1,fleetops-sms'); $router->post('verify-code', 'CustomerController@verifyCode'); $router->post('forgot-password', 'CustomerController@forgotPassword')->middleware('throttle:5,1,fleetops-sms'); $router->post('reset-password', 'CustomerController@resetPassword'); @@ -115,10 +116,21 @@ function ($router) { $router->post('logout', 'CustomerController@logout'); $router->post('logout-all', 'CustomerController@logoutAll'); $router->post('register-device', 'CustomerController@registerDevice'); + $router->post('me/phone-code', 'CustomerController@requestPhoneChangeCode')->middleware('throttle:5,1,fleetops-sms'); + $router->get('geocode', 'CustomerController@geocode'); $router->get('places', 'CustomerController@places'); + $router->get('places/search', 'CustomerController@searchPlaces'); + $router->post('places', 'CustomerController@savePlace'); + $router->put('places/{id}', 'CustomerController@updatePlace'); + $router->delete('places/{id}', 'CustomerController@deletePlace'); $router->get('orders', 'CustomerController@orders'); $router->post('orders', 'CustomerController@createOrder'); $router->get('orders/{id}', 'CustomerController@findOrder'); + $router->post('orders/{id}/dispatch', 'CustomerController@dispatchOrder'); + $router->post('orders/{id}/cancel', 'CustomerController@cancelOrder'); + $router->get('orders/{id}/driver', 'CustomerController@orderDriver'); + $router->get('orders/{id}/tracker', 'CustomerController@orderTracker'); + $router->get('orders/{id}/eta', 'CustomerController@orderEta'); }); }); // vendors routes diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index 00dffea9c..358c915da 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -79,6 +79,20 @@ class FleetOpsApiCustomerControllerProbe extends CustomerController public array $uuidLookups = []; public array $devices = []; + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed + { + $this->placeQueries[] = ['search', $searchQuery, $options]; + + return collect(); + } + + protected function geocodePlaces(string $query, mixed $latitude, mixed $longitude): mixed + { + $this->placeQueries[] = ['geocode', $query, $latitude, $longitude]; + + return collect(); + } + protected function isEmail(?string $identity): bool { return filter_var($identity, FILTER_VALIDATE_EMAIL) !== false; @@ -185,6 +199,13 @@ protected function verificationCodeExists(array $attributes): bool return $this->verificationExists; } + protected function verificationCodeMatches(array $attributes): bool + { + $this->userUpdates[] = ['verificationMatches', $attributes]; + + return $this->verificationExists; + } + protected function findVerificationCode(array $attributes): mixed { $this->userUpdates[] = ['findVerification', $attributes]; @@ -656,6 +677,7 @@ function fleetopsApiCustomerController(): FleetOpsApiCustomerControllerProbe $controller->orderConfig->setRawAttributes(['uuid' => 'config-uuid', 'key' => 'transport'], true); $controller->order = fleetopsApiCustomerOrder(); $controller->serviceQuote = new ServiceQuote(); + $controller->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); $controller->file = (object) ['uuid' => 'public-file-uuid']; return $controller; @@ -863,9 +885,10 @@ function fleetopsApiCustomerJson($response): array $profile = $controller->me(); $updated = $controller->updateMe(new UpdateContactRequest([ - 'name' => 'Jane Updated', - 'phone' => '15550001111', - 'photo' => 'REMOVE', + 'name' => 'Jane Updated', + 'phone' => '15550001111', + 'phone_code' => '123456', + 'photo' => 'REMOVE', ])); $logout = $controller->logout(Request::create('/v1/customers/logout', 'POST', [], [], [], [ 'HTTP_CUSTOMER_TOKEN' => 'token-secret', @@ -1196,3 +1219,154 @@ public function hasDebugModeEnabled() config(['fleetops.customers.verification_bypass_code' => null, 'fleetops.customers.review_accounts' => []]); }); + +function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, array $attributes = []): Order +{ + $order = $controller->order; + $order->setRawAttributes(array_merge($order->getAttributes(), $attributes), true); + + return $order; +} + +test('request code answers the same for known and unknown phone numbers', function () { + $known = fleetopsApiCustomerController(); + $unknown = fleetopsApiCustomerController(); + $unknown->activeUser = null; + + $request = fn () => Request::create('/v1/customers/request-code', 'POST', ['phone' => '+15550001111']); + + expect(fleetopsApiCustomerJson($known->requestCode($request())))->toBe(['status' => 'ok']) + ->and(fleetopsApiCustomerJson($unknown->requestCode($request())))->toBe(['status' => 'ok']) + ->and($known->smsVerifications[0][1] ?? null)->toBe('fleetops_customer_login') + ->and($unknown->smsVerifications[0][1] ?? null)->toBe('fleetops_create_customer'); +}); + +test('request code refuses a missing or email identity', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->requestCode(Request::create('/', 'POST', []))->getStatusCode())->toBe(400) + ->and($controller->requestCode(Request::create('/', 'POST', ['phone' => 'a@b.test']))->getStatusCode())->toBe(400); +}); + +test('verify code tells a new rider apart only after the code is proven', function () { + $controller = fleetopsApiCustomerController(); + $controller->verificationUser = null; + $request = fn () => Request::create('/', 'POST', ['identity' => '+15550001111', 'code' => '123456']); + + expect(fleetopsApiCustomerJson($controller->verifyCode($request())))->toBe(['status' => 'new_customer']); + expect(collect($controller->userUpdates)->pluck(0))->not->toContain('verificationExists'); + + $controller->verificationExists = false; + + expect(fleetopsApiCustomerJson($controller->verifyCode($request())))->toBe(['error' => 'Invalid verification code.']); +}); + +test('a rider cannot change phone without a code for that number', function () { + $controller = fleetopsApiCustomerController(); + $controller->activeUser = null; + $before = $controller->currentCustomer->phone; + + $withoutCode = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222'])); + + $controller->verificationExists = false; + $wrongCode = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222', 'phone_code' => '000000'])); + + expect($withoutCode->getStatusCode())->toBe(422) + ->and($wrongCode->getStatusCode())->toBe(422) + ->and($controller->currentCustomer->phone)->toBe($before); +}); + +test('a rider cannot take a phone number held by another account', function () { + $controller = fleetopsApiCustomerController(); + $controller->activeUser = fleetopsApiCustomerUser(); + $controller->activeUser->uuid = 'someone-else'; + + $response = $controller->updateMe(new UpdateContactRequest(['phone' => '15550002222', 'phone_code' => '123456'])); + + expect($response->getStatusCode())->toBe(422); +}); + +test('a phone change code does not reveal whether a number has an account', function () { + $held = fleetopsApiCustomerController(); + $free = fleetopsApiCustomerController(); + $free->activeUser = null; + $request = fn () => Request::create('/', 'POST', ['phone' => '+15550002222']); + + expect(fleetopsApiCustomerJson($held->requestPhoneChangeCode($request())))->toBe(['status' => 'ok']) + ->and(fleetopsApiCustomerJson($free->requestPhoneChangeCode($request())))->toBe(['status' => 'ok']) + ->and($held->smsVerifications)->toBe([]) + ->and($free->smsVerifications[0][1] ?? null)->toBe('fleetops_customer_phone_change'); +}); + +test('rider order actions treat another rider as not found', function () { + $controller = fleetopsApiCustomerController(); + fleetopsRiderOrderFor($controller, ['customer_uuid' => 'someone-else', 'status' => 'created']); + $request = Request::create('/', 'POST'); + + expect($controller->dispatchOrder('order_1')->getStatusCode())->toBe(404) + ->and($controller->cancelOrder('order_1', $request)->getStatusCode())->toBe(404) + ->and($controller->orderDriver('order_1')->getStatusCode())->toBe(404) + ->and($controller->orderTracker('order_1', $request)->getStatusCode())->toBe(404) + ->and($controller->orderEta('order_1', $request)->getStatusCode())->toBe(404); +}); + +test('a finished order cannot be canceled or dispatched by its rider', function (string $status) { + $controller = fleetopsApiCustomerController(); + fleetopsRiderOrderFor($controller, ['customer_uuid' => $controller->currentCustomer->uuid, 'status' => $status]); + + expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) + ->and($controller->dispatchOrder('order_1')->getStatusCode())->toBe(422); +})->with(['completed', 'canceled']); + +test('rider place routes only touch places the rider owns', function () { + $controller = fleetopsApiCustomerController(); + $controller->place = new Place(); + $controller->place->setRawAttributes(['uuid' => 'p', 'owner_uuid' => 'someone-else'], true); + + expect($controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Mine now']))->getStatusCode())->toBe(404) + ->and($controller->deletePlace('place_1')->getStatusCode())->toBe(404); +}); + +test('saving a place needs a name and real coordinates', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->savePlace(Request::create('/', 'POST', ['latitude' => 1, 'longitude' => 2]))->getStatusCode())->toBe(422) + ->and($controller->savePlace(Request::create('/', 'POST', ['name' => 'Home', 'latitude' => 95, 'longitude' => 2]))->getStatusCode())->toBe(422) + ->and($controller->createdPlaces)->toBe([]); +}); + +test('geocode needs a query or coordinates', function () { + $controller = fleetopsApiCustomerController(); + + expect($controller->geocode(Request::create('/', 'GET'))->getStatusCode())->toBe(400); + $controller->geocode(Request::create('/', 'GET', ['latitude' => 1.28, 'longitude' => 103.85])); + expect($controller->placeQueries[0][0])->toBe('geocode'); +}); + +test('signup password is optional', function () { + $source = file_get_contents(dirname(__DIR__) . '/src/Http/Requests/CreateCustomerRequest.php'); + + expect($source)->toContain("'password' => 'nullable|string|min:8'"); +}); + +test('an expired fare or another company\'s fare is refused when booking', function (array $attributes) { + $controller = fleetopsApiCustomerController(); + $controller->serviceQuote->setRawAttributes($attributes, true); + + $response = $controller->createOrder(new CreateCustomerOrderRequest(['service_quote' => 'quote_1', 'notes' => 'x'])); + + expect($response->getStatusCode())->toBe(422) + ->and($controller->order->purchasedQuotes)->toBe([]); +})->with([ + 'expired' => [['company_uuid' => 'company-uuid', 'expired_at' => Illuminate\Support\Carbon::parse('2020-01-01')]], + 'other company' => [['company_uuid' => 'other-company']], +]); + +test('a customer token gets the narrow customer socket principal', function () { + $source = file_get_contents(dirname(__DIR__) . '/src/Support/SocketChannels.php'); + + expect($source)->toContain("registerPrincipalResolver([static::class, 'customerPrincipal'])") + ->and($source)->toContain("kind: 'customer'") + ->and(Fleetbase\FleetOps\Support\SocketChannels::customerPrincipal(Request::create('/'), null))->toBeNull(); +}); + diff --git a/server/tests/CustomerEndpointTest.php b/server/tests/CustomerEndpointTest.php index 38670211b..2c5697773 100644 --- a/server/tests/CustomerEndpointTest.php +++ b/server/tests/CustomerEndpointTest.php @@ -236,7 +236,7 @@ function fleetopsCustomerEndpointJson(JsonResponse $response): array // (code + for + meta->identity) is strictly stronger than exists:verification_codes. expect($create) ->toContain("'code' => 'required|string'") - ->toContain("'password' => 'required|string|min:8'") + ->toContain("'password' => 'nullable|string|min:8'") ->and($verify)->toContain("'mode' => 'required|in:email,sms'"); }); From 34ae454ee6f717adb1610cdc1ff0ccbc5e868cfb Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 17:44:43 +0800 Subject: [PATCH 04/29] style: format rider access tests --- server/tests/ApiCustomerControllerContractsTest.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index 358c915da..ec97faf76 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -1229,8 +1229,8 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a } test('request code answers the same for known and unknown phone numbers', function () { - $known = fleetopsApiCustomerController(); - $unknown = fleetopsApiCustomerController(); + $known = fleetopsApiCustomerController(); + $unknown = fleetopsApiCustomerController(); $unknown->activeUser = null; $request = fn () => Request::create('/v1/customers/request-code', 'POST', ['phone' => '+15550001111']); @@ -1369,4 +1369,3 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($source)->toContain("kind: 'customer'") ->and(Fleetbase\FleetOps\Support\SocketChannels::customerPrincipal(Request::create('/'), null))->toBeNull(); }); - From 48321a408955a41b0daa1e4ddca35927a077af96 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 18:22:46 +0800 Subject: [PATCH 05/29] ci: allow the unpatched illuminate/mail advisory Composer refuses to install illuminate/mail on Laravel 10 because of CVE-2026-48019, which has no patch before Laravel 12. Ignore this one advisory in PHP CI so the tests can run. Production dependencies don't change. Remove this when the Laravel 12 upgrade lands. --- .github/workflows/server.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index e9699443b..002f52801 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -31,6 +31,11 @@ jobs: - name: Configure Composer Auth for Github run: composer config --global github-oauth.github.com ${{ secrets._GITHUB_AUTH_TOKEN }} + # CVE-2026-48019 in illuminate/mail has no patch for Laravel 10, and Composer refuses to install + # it. CI only: remove this when the Laravel 12 upgrade lands. + - name: Allow the unpatched illuminate/mail advisory + run: composer config --global --json policy.advisories.ignore-id '["PKSA-zwc5-qtrz-zm1n"]' + - name: Validate composer.json and composer.lock run: composer validate From 879d13ccd5107909c164a02bc06bd53adf2b3a34 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 18:29:19 +0800 Subject: [PATCH 06/29] chore(dev): allow symfony/var-dumper 6.4 symfony/http-kernel 6.4, the only version Composer will install for Laravel 10 now, conflicts with var-dumper below 6.3. This is a dev-only dependency, and production already runs 6.4. --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 924dc7d61..a7f527367 100644 --- a/composer.json +++ b/composer.json @@ -44,7 +44,7 @@ "nunomaduro/collision": "^7.0", "pestphp/pest": "^2.33.2", "phpstan/phpstan": "^1.10.38", - "symfony/var-dumper": "^5.4.29" + "symfony/var-dumper": "^5.4.29|^6.4" }, "autoload": { "psr-4": { From 016d07189fac97565b0e6658f5d844978571ed0e Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 18:39:52 +0800 Subject: [PATCH 07/29] test(customers): cover the rider routes and socket principal Cover the rider place, phone change, order and tracking routes, the customer socket principal, and another company's service quote. Update existing tests for the verify-code message and for phone changes needing a code. Check a quote's company after looking it up, so a quote from another company is refused the same way for every lookup, and move the rider place query behind a method so it can be tested. --- .../Controllers/Api/v1/CustomerController.php | 13 +- server/src/Models/ServiceQuote.php | 17 +- .../ApiCustomerControllerContractsTest.php | 234 ++++++++++++++++++ .../Api/CustomerControllerHelperSeamsTest.php | 33 ++- server/tests/Unit/Models/ServiceQuoteTest.php | 17 ++ .../tests/Unit/Support/SocketChannelsTest.php | 33 +++ 6 files changed, 330 insertions(+), 17 deletions(-) diff --git a/server/src/Http/Controllers/Api/v1/CustomerController.php b/server/src/Http/Controllers/Api/v1/CustomerController.php index 0ce732914..fcedd9454 100644 --- a/server/src/Http/Controllers/Api/v1/CustomerController.php +++ b/server/src/Http/Controllers/Api/v1/CustomerController.php @@ -923,11 +923,7 @@ public function searchPlaces(Request $request) return response()->apiError('Not authenticated.', 401); } - $query = Place::where('company_uuid', $this->sessionCompany()) - ->where('owner_uuid', $customer->uuid) - ->whereNull('deleted_at'); - - return $this->placeResourceCollection($this->runPlaceSearch($query, (string) $request->input('query', ''), [ + return $this->placeResourceCollection($this->runPlaceSearch($this->riderPlaceQuery($customer), (string) $request->input('query', ''), [ 'limit' => min((int) $request->input('limit', 10), 50), 'geo' => true, 'latitude' => $request->input('latitude', false), @@ -1601,6 +1597,13 @@ protected function placeResource(Place $place): mixed return new PlaceResource($place); } + protected function riderPlaceQuery(Contact $customer): mixed + { + return Place::where('company_uuid', $this->sessionCompany()) + ->where('owner_uuid', $customer->uuid) + ->whereNull('deleted_at'); + } + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed { return PlaceSearch::search($query, $searchQuery, $options); diff --git a/server/src/Models/ServiceQuote.php b/server/src/Models/ServiceQuote.php index 078723d3c..b29cc8e18 100644 --- a/server/src/Models/ServiceQuote.php +++ b/server/src/Models/ServiceQuote.php @@ -147,22 +147,19 @@ public static function resolveFromRequest(Request|CreateOrderRequest|UpdateOrder } if (Str::isUuid($serviceQuote)) { - $serviceQuote = static::forSessionCompany()->where('uuid', $serviceQuote)->first(); + $serviceQuote = static::where('uuid', $serviceQuote)->first(); } if (Utils::isPublicId($serviceQuote)) { - $serviceQuote = static::forSessionCompany()->where('public_id', $serviceQuote)->first(); + $serviceQuote = static::where('public_id', $serviceQuote)->first(); } - return $serviceQuote; - } + // A quote from another company is treated as not found. + if ($serviceQuote instanceof self && session('company') && $serviceQuote->company_uuid !== session('company')) { + return null; + } - /** - * A quote from another company is treated as not found. - */ - protected static function forSessionCompany() - { - return session('company') ? static::where('company_uuid', session('company')) : static::query(); + return $serviceQuote; } public function getPluralName(): string diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index ec97faf76..b186b9364 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -79,6 +79,11 @@ class FleetOpsApiCustomerControllerProbe extends CustomerController public array $uuidLookups = []; public array $devices = []; + protected function riderPlaceQuery(Contact $customer): mixed + { + return null; + } + protected function runPlaceSearch(mixed $query, string $searchQuery, array $options): mixed { $this->placeQueries[] = ['search', $searchQuery, $options]; @@ -1369,3 +1374,232 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($source)->toContain("kind: 'customer'") ->and(Fleetbase\FleetOps\Support\SocketChannels::customerPrincipal(Request::create('/'), null))->toBeNull(); }); + +class FleetOpsRiderOrderFake extends FleetOpsApiCustomerOrderFake +{ + public array $faked = []; + public array $calls = []; + public mixed $trackerFake = null; + + public function __get($key) + { + return array_key_exists($key, $this->faked) ? $this->faked[$key] : parent::__get($key); + } + + public function __isset($key) + { + return array_key_exists($key, $this->faked) ? isset($this->faked[$key]) : parent::__isset($key); + } + + public function dispatch(bool $save = true): self + { + $this->calls[] = 'dispatch'; + + return $this; + } + + public function insertDispatchActivity(): Order + { + $this->calls[] = 'activity'; + + return $this; + } + + public function cancel() + { + $this->calls[] = 'cancel'; + } + + public function cancelWithReason(?string $reason = null) + { + $this->calls[] = ['reason', $reason]; + } + + public function tracker(): Fleetbase\FleetOps\Support\OrderTracker + { + return $this->trackerFake; + } +} + +class FleetOpsRiderTrackerFake extends Fleetbase\FleetOps\Support\OrderTracker +{ + public function __construct(private bool $fails = false) + { + } + + public function eta(array $options = []): array + { + return $this->answer('eta'); + } + + public function toArray(array $options = []): array + { + return $this->answer('tracker'); + } + + private function answer(string $name): array + { + if ($this->fails) { + throw new RuntimeException('tracking is down'); + } + + return ['answer' => $name]; + } +} + +class FleetOpsRiderPlaceFake extends Place +{ + public array $updates = []; + public bool $deleted = false; + + public function update(array $attributes = [], array $options = []) + { + $this->updates[] = $attributes; + + return true; + } + + public function delete() + { + $this->deleted = true; + + return true; + } +} + +function fleetopsRiderController(array $order = [], array $faked = []): FleetOpsApiCustomerControllerProbe +{ + $controller = fleetopsApiCustomerController(); + $rider = new FleetOpsRiderOrderFake(); + $rider->setRawAttributes(array_merge(['uuid' => 'order-uuid', 'customer_uuid' => $controller->currentCustomer->uuid, 'status' => 'created'], $order), true); + $rider->faked = array_merge(['dispatched' => false, 'hasDriverAssigned' => false, 'adhoc' => true, 'driverAssigned' => null, 'vehicleAssigned' => null], $faked); + $controller->order = $rider; + + return $controller; +} + +test('every rider route answers 401 without a signed-in rider', function () { + $controller = fleetopsApiCustomerController(); + $controller->currentCustomer = null; + $request = Request::create('/', 'GET'); + + expect($controller->searchPlaces($request)->getStatusCode())->toBe(401) + ->and($controller->geocode($request)->getStatusCode())->toBe(401) + ->and($controller->savePlace($request)->getStatusCode())->toBe(401) + ->and($controller->requestPhoneChangeCode($request)->getStatusCode())->toBe(401) + ->and($controller->updatePlace('place_1', $request)->getStatusCode())->toBe(404) + ->and($controller->deletePlace('place_1')->getStatusCode())->toBe(404) + ->and($controller->cancelOrder('order_1', $request)->getStatusCode())->toBe(404); +}); + +test('rider place search only asks for the rider and caps the limit', function () { + $controller = fleetopsApiCustomerController(); + + $controller->searchPlaces(Request::create('/', 'GET', ['query' => 'home', 'limit' => 500, 'latitude' => 1.2, 'longitude' => 103.8])); + + expect($controller->placeQueries[0][0])->toBe('search') + ->and($controller->placeQueries[0][1])->toBe('home') + ->and($controller->placeQueries[0][2])->toMatchArray(['limit' => 50, 'geo' => true, 'latitude' => 1.2, 'longitude' => 103.8]); +}); + +test('a rider saves, edits and deletes their own place', function () { + $controller = fleetopsApiCustomerController(); + $controller->place = new FleetOpsRiderPlaceFake(); + $controller->place->setRawAttributes(['uuid' => 'place-uuid', 'owner_uuid' => $controller->currentCustomer->uuid], true); + + $saved = $controller->savePlace(Request::create('/', 'POST', ['name' => 'Home', 'latitude' => 1.28, 'longitude' => 103.85, 'street1' => '1 Raffles Place', 'owner_uuid' => 'someone-else'])); + $edit = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Work', 'latitude' => 1.3, 'longitude' => 103.9])); + $name = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['name' => 'Office'])); + $bad = $controller->updatePlace('place_1', Request::create('/', 'PUT', ['latitude' => 95, 'longitude' => 103.9])); + $gone = $controller->deletePlace('place_1'); + + $created = collect($controller->createdPlaces)->first(fn ($entry) => isset($entry['name'])); + + expect($saved)->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class) + ->and($created['owner_uuid'])->toBe($controller->currentCustomer->uuid) + ->and($created['location']->getLat())->toBe(1.28) + ->and($edit)->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class) + ->and($controller->place->updates[0]['location']->getLng())->toBe(103.9) + ->and($controller->place->updates[1])->toBe(['name' => 'Office']) + ->and($bad->getStatusCode())->toBe(422) + ->and(fleetopsApiCustomerJson($gone))->toBe(['status' => 'ok']) + ->and($controller->place->deleted)->toBeTrue(); +}); + +test('a phone change code covers missing input, unknown users and send failures', function () { + $request = fn () => Request::create('/', 'POST', ['phone' => '+15550002222']); + + $missing = fleetopsApiCustomerController(); + + $noUser = fleetopsApiCustomerController(); + $noUser->activeUser = null; + $noUser->uuidUser = null; + + $blocked = fleetopsApiCustomerController(); + $blocked->activeUser = null; + $blocked->smsVerificationThrows = SmsBlockedException::limited('company_per_hour', 45); + + $down = fleetopsApiCustomerController(); + $down->activeUser = null; + $down->smsVerificationFails = true; + + expect($missing->requestPhoneChangeCode(Request::create('/', 'POST'))->getStatusCode())->toBe(400) + ->and($noUser->requestPhoneChangeCode($request())->getStatusCode())->toBe(400) + ->and($blocked->requestPhoneChangeCode($request())->getStatusCode())->toBe(429) + ->and($down->requestPhoneChangeCode($request())->getStatusCode())->toBeGreaterThanOrEqual(400); +}); + +test('a rider dispatches their own order only when it can go out', function () { + $ready = fleetopsRiderController(); + $ready->dispatchOrder('order_1'); + + expect($ready->order->calls)->toBe(['dispatch', 'activity']) + ->and(fleetopsRiderController([], ['dispatched' => true])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsRiderController(['status' => 'started'])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsRiderController([], ['adhoc' => false])->dispatchOrder('order_1')->getStatusCode())->toBe(422); +}); + +test('a rider cancels their own order, with or without a reason', function () { + $plain = fleetopsRiderController(); + $plain->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' '])); + + $reason = fleetopsRiderController(); + $reason->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' Changed my mind '])); + + expect($plain->order->calls)->toBe(['cancel']) + ->and($reason->order->calls)->toBe([['reason', 'Changed my mind']]); +}); + +test('a rider sees the driver and car but no contact details', function () { + $driver = (object) ['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here', 'phone' => '+15550009999', 'email' => 'd@example.test', 'vehicle' => null]; + $vehicle = (object) ['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']; + + $none = fleetopsApiCustomerJson(fleetopsRiderController()->orderDriver('order_1')); + $noCar = fleetopsApiCustomerJson(fleetopsRiderController([], ['driverAssigned' => $driver])->orderDriver('order_1')); + $withCar = fleetopsApiCustomerJson(fleetopsRiderController([], ['driverAssigned' => $driver, 'vehicleAssigned' => $vehicle])->orderDriver('order_1')); + + expect($none)->toBe(['driver' => null, 'vehicle' => null]) + ->and($noCar['vehicle'])->toBeNull() + ->and($withCar['driver'])->toBe(['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here']) + ->and($withCar['vehicle'])->toBe(['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']); +}); + +test('rider tracking answers, and says so when tracking is down', function () { + $working = fleetopsRiderController(); + $working->order->trackerFake = new FleetOpsRiderTrackerFake(); + $broken = fleetopsRiderController(); + $broken->order->trackerFake = new FleetOpsRiderTrackerFake(true); + $request = Request::create('/', 'GET'); + + expect(fleetopsApiCustomerJson($working->orderTracker('order_1', $request)))->toBe(['answer' => 'tracker']) + ->and(fleetopsApiCustomerJson($working->orderEta('order_1', $request)))->toBe(['answer' => 'eta']) + ->and($broken->orderTracker('order_1', $request)->getStatusCode())->toBe(503) + ->and($broken->orderEta('order_1', $request)->getStatusCode())->toBe(503); +}); + +test('an order that does not exist is not found for a rider', function () { + $controller = fleetopsApiCustomerController(); + $controller->findOrderFails = true; + + expect($controller->orderDriver('order_missing')->getStatusCode())->toBe(404); +}); diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index d886630d2..b328af014 100644 --- a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php +++ b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php @@ -585,7 +585,7 @@ public function parameters() 'identity' => 'ghost@example.com', 'code' => '111111', ])); - expect($unknown->getData(true)['error'] ?? '')->toContain('Unable to verify'); + expect($unknown->getData(true)['error'] ?? '')->toBe('Invalid verification code.'); // The create-customer intent delegates into the full creation flow $connection->table('verification_codes')->insert(['uuid' => 'vc-del', 'code' => '777777', 'for' => 'fleetops_create_customer', 'meta' => json_encode(['identity' => 'delegate@example.com']), 'status' => 'active']); @@ -711,7 +711,6 @@ public function parameters() $updated = $controller->updateMe(Fleetbase\FleetOps\Http\Requests\UpdateContactRequest::create('/v1/customers/me', 'PUT', [ 'name' => 'Profile Customer Updated', - 'phone' => '+6590001234', 'photo' => 'file_meavatar1', ])); expect($connection->table('contacts')->where('uuid', '88888888-8888-4888-8888-888888888810')->value('name'))->toBe('Profile Customer Updated') @@ -855,3 +854,33 @@ protected function createFileFromBase64(string $contents, string $path): mixed $again = $controller->create(CreateCustomerRequest::create('/v1/customers', 'POST', ['code' => '101010', 'identity' => 'spend@example.com', 'name' => 'Spender', 'password' => 'secret'])); expect($again->getData(true)['error'])->toContain('Invalid verification code'); }); + +test('a signup code can be checked without using it up, and a wrong one is refused', function () { + $connection = fleetopsCustomerHelperBoot(); + $controller = new CustomerController(); + $connection->table('verification_codes')->insert(['uuid' => 'vc-check', 'code' => '246810', 'for' => 'fleetops_create_customer', 'meta' => json_encode(['identity' => 'proof@example.com'])]); + + $wrong = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '000000'])); + $right = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '246810'])); + $again = $controller->verifyCode(Request::create('/v1/customers/verify-code', 'POST', ['identity' => 'proof@example.com', 'code' => '246810'])); + + expect($wrong->getData(true))->toBe(['error' => 'Invalid verification code.']) + ->and($right->getData(true))->toBe(['status' => 'new_customer']) + ->and($again->getData(true))->toBe(['status' => 'new_customer']); +}); + +test('rider place search and geocoding reach the place search service', function () { + fleetopsCustomerHelperBoot(); + $controller = new CustomerController(); + $search = new ReflectionMethod(CustomerController::class, 'runPlaceSearch'); + $geocode = new ReflectionMethod(CustomerController::class, 'geocodePlaces'); + $resource = new ReflectionMethod(CustomerController::class, 'placeResource'); + $owned = new ReflectionMethod(CustomerController::class, 'riderPlaceQuery'); + $customer = new Contact(); + $customer->setRawAttributes(['uuid' => 'rider-1'], true); + + expect($search->invoke($controller, Place::where('company_uuid', 'nobody'), '', ['geo' => false]))->toHaveCount(0) + ->and($owned->invoke($controller, $customer)->getBindings())->toContain('rider-1') + ->and($geocode->invoke($controller, '', null, null))->toHaveCount(0) + ->and($resource->invoke($controller, new Place()))->toBeInstanceOf(Fleetbase\FleetOps\Http\Resources\v1\Place::class); +}); diff --git a/server/tests/Unit/Models/ServiceQuoteTest.php b/server/tests/Unit/Models/ServiceQuoteTest.php index 7814d2edf..4971c0b87 100644 --- a/server/tests/Unit/Models/ServiceQuoteTest.php +++ b/server/tests/Unit/Models/ServiceQuoteTest.php @@ -615,3 +615,20 @@ public function updateMeta($key, $value = null): bool Facade::setFacadeApplication($previousContainer); } }); + +test('service quote from another company resolves as not found', function () { + $quote = new ServiceQuote(); + $quote->setRawAttributes(['uuid' => '11111111-1111-4111-8111-111111111111', 'company_uuid' => 'company-b'], true); + + FleetOpsServiceQuoteUnitResolvableFake::$lookups = []; + FleetOpsServiceQuoteUnitResolvableFake::$records = ['uuid' => ['11111111-1111-4111-8111-111111111111' => $quote], 'public_id' => []]; + $request = fleetopsServiceQuoteUnitRequestWithQuote('11111111-1111-4111-8111-111111111111'); + + session(['company' => 'company-a']); + expect(FleetOpsServiceQuoteUnitResolvableFake::resolveFromRequest($request))->toBeNull(); + + session(['company' => 'company-b']); + expect(FleetOpsServiceQuoteUnitResolvableFake::resolveFromRequest($request))->toBe($quote); + + session(['company' => null]); +}); diff --git a/server/tests/Unit/Support/SocketChannelsTest.php b/server/tests/Unit/Support/SocketChannelsTest.php index 25243e3b9..ee392fbcc 100644 --- a/server/tests/Unit/Support/SocketChannelsTest.php +++ b/server/tests/Unit/Support/SocketChannelsTest.php @@ -379,6 +379,39 @@ function socketChannelsCustomer(): SocketPrincipal expect(SocketChannels::driverPrincipal($request, $homeless))->toBeNull(); }); +test('a customer token gets the customer principal limited to their own records', function () { + socketChannelsBoot(); + $request = Request::create('/v1/socket/token', 'POST'); + $customer = new User(); + $customer->setRawAttributes(['uuid' => 'user-rider-a', 'company_uuid' => 'company-a', 'type' => 'customer'], true); + Fleetbase\FleetOps\Models\Contact::query()->insert(['uuid' => 'contact-rider-a', 'public_id' => 'contact_ridera', 'company_uuid' => 'company-a', 'user_uuid' => 'user-rider-a', 'type' => 'customer']); + + session(['company' => 'company-a']); + $principal = SocketChannels::customerPrincipal($request, $customer); + + expect($principal)->toBeInstanceOf(SocketPrincipal::class) + ->and($principal->kind)->toBe('customer') + ->and($principal->sub)->toBe('contact-rider-a') + ->and($principal->ids)->toBe(['contact-rider-a', 'contact_ridera', 'user-rider-a']) + ->and($principal->cid)->toBe('company-a') + ->and($principal->cpid)->toBe('company_a') + ->and($principal->adm)->toBeFalse(); + + // Another company's rider, an office user and a stranger object: no claim. + session(['company' => 'company-b']); + expect(SocketChannels::customerPrincipal($request, $customer))->toBeNull(); + + session(['company' => 'company-a']); + expect(SocketChannels::customerPrincipal($request, User::where('uuid', 'user-office-a')->first()))->toBeNull() + ->and(SocketChannels::customerPrincipal($request, (object) ['uuid' => 'user-rider-a']))->toBeNull() + ->and(SocketChannels::customerPrincipal($request, null))->toBeNull(); + + session(['company' => null]); + $homeless = new User(); + $homeless->setRawAttributes(['uuid' => 'user-rider-a', 'company_uuid' => null, 'type' => 'customer'], true); + expect(SocketChannels::customerPrincipal($request, $homeless))->toBeNull(); +}); + test('the service provider registers the fleetops channels when the registry is built', function () { socketChannelsBoot(); app()->forgetInstance(SocketChannelRegistry::class); From 6e53c01476c2e76fa3aa9cffbe619e69030be2d9 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 18:50:35 +0800 Subject: [PATCH 08/29] test(customers): expect the optional signup password in request rules --- server/tests/RequestContractsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/tests/RequestContractsTest.php b/server/tests/RequestContractsTest.php index a77d8d20e..12a779d45 100644 --- a/server/tests/RequestContractsTest.php +++ b/server/tests/RequestContractsTest.php @@ -788,7 +788,7 @@ protected function canUpdateDriver(): bool ->and($rules['identity'])->toBe('required|string') ->and($rules['code'])->toBe('required|string') ->and($rules['name'])->toBe('required|string') - ->and($rules['password'])->toBe('required|string|min:8') + ->and($rules['password'])->toBe('nullable|string|min:8') ->and(ruleStrings($rules['email']))->toContain('email', 'nullable', 'unique:contacts') ->and(ruleStrings($rules['phone']))->toContain('nullable', 'string', 'unique:contacts') ->and($rules['meta'])->toBe('nullable|array'); From dad762b8a66e8dec2e02d5efa28d410662ad2f25 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 19:49:44 +0800 Subject: [PATCH 09/29] chore(deps): move to Laravel 12, core-api 2.0 and Pest 3 Bumps the Laravel 12 dependency set and fixes the test fakes the new contracts break: Filesystem fakes, array() stubs, Grammar constructor, cknow/laravel-money currency config, Firebase client errors and loadMissing() needing a connection. --- composer.json | 20 ++++++------- scripts/pest-bootstrap.php | 30 +++++++++++++++++++ server/tests/CommandContractsTest.php | 2 ++ .../CompactResourceSerializationTest.php | 2 +- server/tests/EventContractsTest.php | 2 ++ .../Api/CustomerControllerHelperSeamsTest.php | 15 ++++++++++ .../OrderControllerCapturePhotoTest.php | 15 ++++++++++ server/tests/ModelAccessorContractsTest.php | 2 +- .../tests/ServiceRateRouteValidationTest.php | 2 +- .../TelematicControllerContractsTest.php | 2 ++ .../TrackingNumberTraitContractsTest.php | 2 +- .../Unit/Models/OrderCancelReasonTest.php | 4 +++ .../Models/PlaceCreationAndImportTest.php | 15 ++++++++++ .../MonitoringNotificationsTest.php | 2 +- .../OrderAssignedChannelsTest.php | 2 +- .../OrderChangeNotificationsTest.php | 4 +-- .../OrderDispatchedChannelsTest.php | 2 +- .../Notifications/OrderFailedChannelsTest.php | 2 +- .../Notifications/OrderPingChannelsTest.php | 2 +- .../PurchaseRateObserverAndOrderJobsTest.php | 2 +- .../FuelEfficiencyAndCanceledHandlersTest.php | 2 +- server/tests/UtilsContractsTest.php | 2 +- 22 files changed, 109 insertions(+), 24 deletions(-) diff --git a/composer.json b/composer.json index 924dc7d61..9288d758e 100644 --- a/composer.json +++ b/composer.json @@ -21,30 +21,30 @@ } ], "require": { - "php": "^8.0", + "php": "^8.2", "barryvdh/laravel-dompdf": "^3.1", "brick/geo": "0.7.2", - "cknow/laravel-money": "^7.1", - "fleetbase/core-api": "^1.6.74", + "cknow/laravel-money": "^8.0", + "fleetbase/core-api": "^2.0", "geocoder-php/google-maps-places-provider": "^1.4", "giggsey/libphonenumber-for-php": "^8.13", "league/geotools": "^1.1.0", - "milon/barcode": "^10.0", + "milon/barcode": "^13.0", "php-http/guzzle7-adapter": "^1.0", "php-units-of-measure/php-units-of-measure": "^2.2", "psr/http-factory-implementation": "*", "rlanvin/php-rrule": "^2.6", - "toin0u/geocoder-laravel": "^4.4", + "toin0u/geocoder-laravel": "^13.0", "webit/eval-math": "^1.0", "spatie/icalendar-generator": "^2.8" }, "require-dev": { - "illuminate/encryption": "^9.0|^10.0", + "illuminate/encryption": "^12.69", "friendsofphp/php-cs-fixer": "^3.34.1", - "nunomaduro/collision": "^7.0", - "pestphp/pest": "^2.33.2", - "phpstan/phpstan": "^1.10.38", - "symfony/var-dumper": "^5.4.29" + "nunomaduro/collision": "^8.0", + "pestphp/pest": "^3.0", + "phpstan/phpstan": "^2.0", + "symfony/var-dumper": "^7.0" }, "autoload": { "psr-4": { diff --git a/scripts/pest-bootstrap.php b/scripts/pest-bootstrap.php index 95b00ad3a..fbf9a06a5 100644 --- a/scripts/pest-bootstrap.php +++ b/scripts/pest-bootstrap.php @@ -418,6 +418,36 @@ public static function dispatchNow(...$arguments) { \Fleetbase\TestSupport\Dispa eval('namespace Fleetbase\Ai\Support; class AiRelativeDateResolver { public function __construct($parser = null) {} public function resolveDateTime(string $prompt, ?string $timezone = null): ?\Illuminate\Support\Carbon { if (preg_match("/(\d+)\s+days?\s+from\s+now/i", $prompt, $matches)) { return \Illuminate\Support\Carbon::now($timezone)->addDays((int) $matches[1]); } return null; } public function resolveWindow(string $prompt, ?string $timezone = null): ?array { $timezone = $timezone ?: date_default_timezone_get(); $now = \Illuminate\Support\Carbon::now($timezone); if (str_contains(strtolower($prompt), "last week")) { $start = $now->copy()->subWeek()->startOfWeek(); $end = $now->copy()->subWeek()->endOfWeek(); return ["label" => "last week", "timezone" => $timezone, "start" => $start, "end" => $end]; } if (str_contains(strtolower($prompt), "yesterday")) { $start = $now->copy()->subDay()->startOfDay(); $end = $now->copy()->subDay()->endOfDay(); return ["label" => "yesterday", "timezone" => $timezone, "start" => $start, "end" => $end]; } return null; } }'); } +// cknow/laravel-money 8 finds its ISO currency table through config, which this harness never loads. +if (class_exists(Cknow\Money\Money::class)) { + Cknow\Money\Money::setCurrencies(new Money\Currencies\ISOCurrencies()); +} + +/** + * Laravel 12's loadMissing() always starts a query, even when every relation is set, so a + * model test without a connection needs a resolver to reach that point. + */ +function fleetopsTestConnectionResolver(): void +{ + Illuminate\Database\Eloquent\Model::setConnectionResolver(new class implements Illuminate\Database\ConnectionResolverInterface { + private ?Illuminate\Database\Connection $connection = null; + + public function connection($name = null) + { + return $this->connection ??= new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')); + } + + public function getDefaultConnection() + { + return 'sqlite'; + } + + public function setDefaultConnection($name) + { + } + }); +} + set_error_handler(function (int $severity, string $message): bool { if (str_contains($message, '/pestphp/pest/vendor/autoload.php')) { return true; diff --git a/server/tests/CommandContractsTest.php b/server/tests/CommandContractsTest.php index f6d14ca32..4927df484 100644 --- a/server/tests/CommandContractsTest.php +++ b/server/tests/CommandContractsTest.php @@ -2361,6 +2361,8 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista }); test('assign driver roles command assigns non admin driver users and reports failures', function () { + fleetopsTestConnectionResolver(); + $company = new Company(); $company->setRawAttributes(['uuid' => 'company-uuid', 'name' => 'Acme Logistics'], true); diff --git a/server/tests/CompactResourceSerializationTest.php b/server/tests/CompactResourceSerializationTest.php index 658f68a7b..c015d4335 100644 --- a/server/tests/CompactResourceSerializationTest.php +++ b/server/tests/CompactResourceSerializationTest.php @@ -67,7 +67,7 @@ public function isArray(string $key): bool return is_array($this->input($key)); } - public function array(string $key): array + public function array($key = null, $default = []): array { $value = $this->input($key); diff --git a/server/tests/EventContractsTest.php b/server/tests/EventContractsTest.php index 78c4ccf61..7f109ab19 100644 --- a/server/tests/EventContractsTest.php +++ b/server/tests/EventContractsTest.php @@ -821,6 +821,8 @@ public function getPickupOrCurrentWaypoint(): mixed }); test('geofence entered listener handles arrival branch outcomes', function () { + fleetopsTestConnectionResolver(); + $listener = new HandleGeofenceEntered(); $arrival = new ReflectionMethod(HandleGeofenceEntered::class, 'handleOrderArrival'); $arrival->setAccessible(true); diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index d886630d2..ede6ea322 100644 --- a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php +++ b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php @@ -251,6 +251,21 @@ public function __call($method, $arguments) $contractDisk = new class implements Illuminate\Contracts\Filesystem\Filesystem { public array $writes = []; + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.test/' . ltrim((string) $path, '/'); diff --git a/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php b/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php index 14d5248dc..79c476ee9 100644 --- a/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php +++ b/server/tests/Feature/Http/Internal/OrderControllerCapturePhotoTest.php @@ -161,6 +161,21 @@ public function errors() $disk = new class implements Illuminate\Contracts\Filesystem\Filesystem { public array $writes = []; + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.example.com/' . ltrim((string) $path, '/'); diff --git a/server/tests/ModelAccessorContractsTest.php b/server/tests/ModelAccessorContractsTest.php index 2e034c2ff..a8c9ef9cc 100644 --- a/server/tests/ModelAccessorContractsTest.php +++ b/server/tests/ModelAccessorContractsTest.php @@ -1564,7 +1564,7 @@ public function raw($value): Illuminate\Database\Query\Expression ->and($imported->volume)->toBe('45.5') ->and($imported->metric_unit)->toBe('gal') ->and($imported->status)->toBe('approved') - ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar()))->toContain('POINT'); + ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))))->toContain('POINT'); }); test('fuel provider transaction accessors expose related names and station points', function () { diff --git a/server/tests/ServiceRateRouteValidationTest.php b/server/tests/ServiceRateRouteValidationTest.php index 9b9916076..35c50eef5 100644 --- a/server/tests/ServiceRateRouteValidationTest.php +++ b/server/tests/ServiceRateRouteValidationTest.php @@ -151,7 +151,7 @@ public function where($column, $value) // Exports stream through the excel facade if (!class_exists('Fleetbase\\Http\\Requests\\ExportRequest', false)) { - eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function array($key, $default = []) { return (array) $this->input($key, $default); } }'); + eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function array($key = null, $default = []) { return (array) $this->input($key, $default); } }'); } $excelFake = new class { public array $downloads = []; diff --git a/server/tests/TelematicControllerContractsTest.php b/server/tests/TelematicControllerContractsTest.php index aa0ceef45..4b1f5fb7c 100644 --- a/server/tests/TelematicControllerContractsTest.php +++ b/server/tests/TelematicControllerContractsTest.php @@ -149,6 +149,8 @@ public function getAttribute($key) }); test('internal customer controller serializes portal login payloads', function () { + fleetopsTestConnectionResolver(); + $controller = new FleetOpsCustomerControllerProbe(); $customer = new Contact(); $customer->setRawAttributes([ diff --git a/server/tests/TrackingNumberTraitContractsTest.php b/server/tests/TrackingNumberTraitContractsTest.php index 5d374cecb..02acdf034 100644 --- a/server/tests/TrackingNumberTraitContractsTest.php +++ b/server/tests/TrackingNumberTraitContractsTest.php @@ -42,7 +42,7 @@ public function payload(): void function fleetopsTrackingExpressionValue(Expression $expression): string { - return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar()) : (string) $expression; + return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))) : (string) $expression; } test('tracking number trait handles assignment status location and pickup fallbacks', function () { diff --git a/server/tests/Unit/Models/OrderCancelReasonTest.php b/server/tests/Unit/Models/OrderCancelReasonTest.php index eddd2a606..cc9d04a23 100644 --- a/server/tests/Unit/Models/OrderCancelReasonTest.php +++ b/server/tests/Unit/Models/OrderCancelReasonTest.php @@ -83,6 +83,8 @@ function fleetopsOrderCancelReasonOrder(): array } test('canceling with a reason records it as the canceled details and on the event', function () { + fleetopsTestConnectionResolver(); + [$order, $config] = fleetopsOrderCancelReasonOrder(); $order->cancelWithReason(' Customer moved house '); @@ -97,6 +99,8 @@ function fleetopsOrderCancelReasonOrder(): array }); test('a plain cancel keeps the config activity and sends no reason', function () { + fleetopsTestConnectionResolver(); + [$order, $config] = fleetopsOrderCancelReasonOrder(); $order->cancel(); diff --git a/server/tests/Unit/Models/PlaceCreationAndImportTest.php b/server/tests/Unit/Models/PlaceCreationAndImportTest.php index 7d2df89a0..feae70a71 100644 --- a/server/tests/Unit/Models/PlaceCreationAndImportTest.php +++ b/server/tests/Unit/Models/PlaceCreationAndImportTest.php @@ -62,6 +62,21 @@ public function __call($method, $arguments) Illuminate\Support\Facades\DB::clearResolvedInstance('db'); $disk = new class implements Filesystem { + public function path($path) + { + return $path; + } + + public function putFile($path, $file = null, $options = []) + { + return false; + } + + public function putFileAs($path, $file, $name = null, $options = []) + { + return false; + } + public function url($path) { return 'https://cdn.example.com/' . ltrim((string) $path, '/'); diff --git a/server/tests/Unit/Notifications/MonitoringNotificationsTest.php b/server/tests/Unit/Notifications/MonitoringNotificationsTest.php index dc00d87bc..871a226bf 100644 --- a/server/tests/Unit/Notifications/MonitoringNotificationsTest.php +++ b/server/tests/Unit/Notifications/MonitoringNotificationsTest.php @@ -131,6 +131,6 @@ function fleetopsMonitoringNotifOrder(): Order // Push transports and console urls are unavailable in the harness; the // delegation bodies still execute up to those seams. expect(fn () => $notification->toMail(null))->toThrow(Error::class) - ->and(fn () => $notification->toFcm(null))->toThrow(Exception::class) + ->and(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php b/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php index cb0a481ae..25590c4ac 100644 --- a/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderAssignedChannelsTest.php @@ -48,6 +48,6 @@ function fleetopsOrderAssignedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php b/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php index 7fbd15f48..9389b12ca 100644 --- a/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php +++ b/server/tests/Unit/Notifications/OrderChangeNotificationsTest.php @@ -42,7 +42,7 @@ function fleetopsOrderChangeNotificationOrder(): Order ->and((new OrderChanged(fleetopsOrderChangeNotificationOrder()))->message)->toBe('This order was changed, tap for details.'); // The push builders reach for the FCM and APN clients, which the harness does not configure - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); @@ -54,6 +54,6 @@ function fleetopsOrderChangeNotificationOrder(): Order ->and($notification->via(null))->toBe([FcmChannel::class, ApnChannel::class]) ->and($notification->toArray()['event'])->toBe('order.unassigned_notification'); - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php b/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php index 9446a7af3..00e8809d8 100644 --- a/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderDispatchedChannelsTest.php @@ -76,6 +76,6 @@ function fleetopsOrderDispatchedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderFailedChannelsTest.php b/server/tests/Unit/Notifications/OrderFailedChannelsTest.php index b06272654..cf86d51ef 100644 --- a/server/tests/Unit/Notifications/OrderFailedChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderFailedChannelsTest.php @@ -68,6 +68,6 @@ function fleetopsOrderFailedOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Notifications/OrderPingChannelsTest.php b/server/tests/Unit/Notifications/OrderPingChannelsTest.php index ab57a6520..e5c939603 100644 --- a/server/tests/Unit/Notifications/OrderPingChannelsTest.php +++ b/server/tests/Unit/Notifications/OrderPingChannelsTest.php @@ -64,6 +64,6 @@ function fleetopsOrderPingOrder(): Order // The fcm/apn transport packages are unavailable in the harness; the // delegation bodies still execute, which is the covered contract here. - expect(fn () => $ping->toFcm(null))->toThrow(Exception::class) + expect(fn () => $ping->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $ping->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php b/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php index 3953d2305..22115967e 100644 --- a/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php +++ b/server/tests/Unit/Observers/PurchaseRateObserverAndOrderJobsTest.php @@ -164,6 +164,6 @@ public function __call($method, $arguments) expect(fn () => $withWaypoint->toMail(null))->toThrow(Error::class); // Push transports are unavailable; delegation bodies still execute - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php b/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php index bb48c7a77..af4cf34b2 100644 --- a/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php +++ b/server/tests/Unit/Support/FuelEfficiencyAndCanceledHandlersTest.php @@ -159,6 +159,6 @@ public function sendNow($notifiables, $notification, ?array $channels = null) // Push transports are unavailable in the harness; the delegation bodies // still execute, which is the covered contract here. - expect(fn () => $notification->toFcm(null))->toThrow(Exception::class) + expect(fn () => $notification->toFcm(null))->toThrow(TypeError::class) ->and(fn () => $notification->toApn(null))->toThrow(Error::class); }); diff --git a/server/tests/UtilsContractsTest.php b/server/tests/UtilsContractsTest.php index 660e190c7..94d5e674d 100644 --- a/server/tests/UtilsContractsTest.php +++ b/server/tests/UtilsContractsTest.php @@ -10,7 +10,7 @@ function fleetOpsUtilsExpressionValue(Expression $expression): string { - return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar()) : (string) $expression; + return method_exists($expression, 'getValue') ? $expression->getValue(new Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))) : (string) $expression; } test('utility coordinate validators accept only finite coordinate ranges', function () { From 85721eceaf084469e1f2152b7e5440fb2fc624b9 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Thu, 5 Nov 2026 20:37:27 +0800 Subject: [PATCH 10/29] fix(request): call core-api's inputArray instead of array Laravel 11+ ships a native Request::array(), which wins over core-api's macro of that name and stops it splitting comma-separated values. Needs core-api with inputArray. --- scripts/pest-bootstrap.php | 4 ++-- .../src/Http/Controllers/Api/v1/OrderController.php | 2 +- .../Controllers/Internal/v1/ContactController.php | 4 ++-- .../Controllers/Internal/v1/DeviceController.php | 2 +- .../Controllers/Internal/v1/DriverController.php | 6 +++--- .../Controllers/Internal/v1/EquipmentController.php | 2 +- .../Http/Controllers/Internal/v1/FleetController.php | 6 +++--- .../Internal/v1/FuelProviderConnectionController.php | 4 ++-- .../Controllers/Internal/v1/FuelReportController.php | 4 ++-- .../Internal/v1/InspectionSubmissionController.php | 2 +- .../Http/Controllers/Internal/v1/IssueController.php | 6 +++--- .../Http/Controllers/Internal/v1/LiveController.php | 2 +- .../Internal/v1/MaintenanceController.php | 2 +- .../Internal/v1/MaintenanceScheduleController.php | 2 +- .../Controllers/Internal/v1/MetricsController.php | 2 +- .../Http/Controllers/Internal/v1/OrderController.php | 12 ++++++------ .../Http/Controllers/Internal/v1/PartController.php | 2 +- .../Http/Controllers/Internal/v1/PlaceController.php | 4 ++-- .../Controllers/Internal/v1/SensorController.php | 2 +- .../Internal/v1/ServiceAreaController.php | 4 ++-- .../Internal/v1/ServiceRateController.php | 2 +- .../Controllers/Internal/v1/SettingController.php | 6 +++--- .../Controllers/Internal/v1/TelematicController.php | 4 ++-- .../Controllers/Internal/v1/TrailerController.php | 4 ++-- .../Controllers/Internal/v1/VehicleController.php | 4 ++-- .../Controllers/Internal/v1/VendorController.php | 4 ++-- .../Controllers/Internal/v1/WorkOrderController.php | 2 +- .../Http/Controllers/Internal/v1/ZoneController.php | 2 +- server/tests/CompactResourceSerializationTest.php | 2 +- .../Http/Api/TrailerControllerLifecycleTest.php | 2 +- .../Http/Internal/DriverControllerContractsTest.php | 2 +- .../Http/Internal/IssueControllerContractsTest.php | 2 +- .../Http/Internal/MetricsControllerContractsTest.php | 2 +- .../Internal/OrderConfigControllerContractsTest.php | 4 ++-- .../Http/Internal/OrderControllerContractsTest.php | 2 +- .../Internal/WorkOrderControllerContractsTest.php | 2 +- .../tests/InternalFleetControllerContractsTest.php | 4 ++-- .../InternalImportExportControllerContractsTest.php | 4 ++-- server/tests/OrderFileAttachmentTest.php | 2 +- server/tests/ServiceRateRouteValidationTest.php | 2 +- server/tests/SmallControllerContractsTest.php | 2 +- .../tests/Unit/Http/Resources/FleetResourceTest.php | 4 ++-- 42 files changed, 69 insertions(+), 69 deletions(-) diff --git a/scripts/pest-bootstrap.php b/scripts/pest-bootstrap.php index 95b00ad3a..21b2736b9 100644 --- a/scripts/pest-bootstrap.php +++ b/scripts/pest-bootstrap.php @@ -300,8 +300,8 @@ function now($tz = null): Illuminate\Support\Carbon } if (class_exists('Illuminate\Http\Request') && method_exists('Illuminate\Http\Request', 'macro')) { - if (!method_exists('Illuminate\Http\Request', 'array')) { - Illuminate\Http\Request::macro('array', function (string $key, array $default = []): array { + if (!method_exists('Illuminate\Http\Request', 'inputArray')) { + Illuminate\Http\Request::macro('inputArray', function (string $key, array $default = []): array { $value = $this->input($key, $default); return is_array($value) ? $value : $default; diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index b4e654289..dbc3338a0 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -1255,7 +1255,7 @@ public function updateActivity($id, Request $request) // Get the order config $orderConfig = $order->config(); - $activity = $request->array('activity'); + $activity = $request->inputArray('activity'); if (!Utils::isActivity($activity)) { $activity = new Activity($activity, $order->getConfigFlow()); } diff --git a/server/src/Http/Controllers/Internal/v1/ContactController.php b/server/src/Http/Controllers/Internal/v1/ContactController.php index ecfdf21fd..b72d236bf 100644 --- a/server/src/Http/Controllers/Internal/v1/ContactController.php +++ b/server/src/Http/Controllers/Internal/v1/ContactController.php @@ -77,7 +77,7 @@ public function afterSave(Request $request, Contact $contact) $this->sendCustomerPortalWelcomeEmail($contact); } - $customFieldValues = $request->array('contact.custom_field_values'); + $customFieldValues = $request->inputArray('contact.custom_field_values'); if ($customFieldValues) { $contact->syncCustomFieldValues($customFieldValues); } @@ -175,7 +175,7 @@ public function convertToVendor(Request $request, string $id) public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('contacts-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new ContactExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/DeviceController.php b/server/src/Http/Controllers/Internal/v1/DeviceController.php index ce969fbc2..ccc3f3b87 100644 --- a/server/src/Http/Controllers/Internal/v1/DeviceController.php +++ b/server/src/Http/Controllers/Internal/v1/DeviceController.php @@ -43,7 +43,7 @@ class DeviceController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('devices-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new DeviceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/DriverController.php b/server/src/Http/Controllers/Internal/v1/DriverController.php index f121aeb83..8561c5166 100644 --- a/server/src/Http/Controllers/Internal/v1/DriverController.php +++ b/server/src/Http/Controllers/Internal/v1/DriverController.php @@ -122,7 +122,7 @@ function (&$request, &$input) { }, function ($request, &$driver) { $driver->load(['user']); - $customFieldValues = $request->array('driver.custom_field_values'); + $customFieldValues = $request->inputArray('driver.custom_field_values'); if ($customFieldValues) { $driver->syncCustomFieldValues($customFieldValues); } @@ -191,7 +191,7 @@ function ($request, &$driver) { } $driver->setHidden(['user']); - $customFieldValues = $request->array('driver.custom_field_values'); + $customFieldValues = $request->inputArray('driver.custom_field_values'); if ($customFieldValues) { $driver->syncCustomFieldValues($customFieldValues); } @@ -395,7 +395,7 @@ public function avatars() public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('drivers-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new DriverExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/EquipmentController.php b/server/src/Http/Controllers/Internal/v1/EquipmentController.php index b11c5d410..11ae3e1a0 100644 --- a/server/src/Http/Controllers/Internal/v1/EquipmentController.php +++ b/server/src/Http/Controllers/Internal/v1/EquipmentController.php @@ -27,7 +27,7 @@ class EquipmentController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('equipment-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new EquipmentExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/FleetController.php b/server/src/Http/Controllers/Internal/v1/FleetController.php index e66c1e1fe..adf585e74 100644 --- a/server/src/Http/Controllers/Internal/v1/FleetController.php +++ b/server/src/Http/Controllers/Internal/v1/FleetController.php @@ -32,7 +32,7 @@ class FleetController extends FleetOpsController */ public function afterSave(Request $request, Fleet $fleet) { - $customFieldValues = $request->array('fleet.custom_field_values'); + $customFieldValues = $request->inputArray('fleet.custom_field_values'); if ($customFieldValues) { $fleet->syncCustomFieldValues($customFieldValues); } @@ -47,7 +47,7 @@ public function afterSave(Request $request, Fleet $fleet) public static function onQueryRecord($query, $request): void { if ($request->has('excludeDriverJobs')) { - $excludeJobs = $request->array('excludeDriverJobs'); + $excludeJobs = $request->inputArray('excludeDriverJobs'); $query->with('drivers', function ($query) use ($excludeJobs) { $query->with('jobs', function ($query) use ($excludeJobs) { if (is_array($excludeJobs)) { @@ -97,7 +97,7 @@ function ($q) { public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('fleets-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new FleetExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php b/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php index df99e25e3..c31b2e962 100644 --- a/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php +++ b/server/src/Http/Controllers/Internal/v1/FuelProviderConnectionController.php @@ -59,7 +59,7 @@ public function testCredentials(Request $request, string $provider): JsonRespons $result = $this->fuelProviderService->testCredentials( $provider, - $request->array('credentials'), + $request->inputArray('credentials'), $request->input('environment', 'production') ); @@ -89,7 +89,7 @@ public function sync(Request $request, string $id): JsonResponse $async = $request->boolean('async', true); $from = $request->input('from') ? Carbon::parse($request->input('from'))->startOfDay() : null; $to = $request->input('to') ? Carbon::parse($request->input('to'))->endOfDay() : null; - $options = $request->array('options', []); + $options = $request->inputArray('options', []); $syncRun = $this->fuelProviderService->createSyncRun($connection, $from, $to, $async ? 'queued' : 'running'); if ($async) { diff --git a/server/src/Http/Controllers/Internal/v1/FuelReportController.php b/server/src/Http/Controllers/Internal/v1/FuelReportController.php index c2e8db2bf..ebec4cb41 100644 --- a/server/src/Http/Controllers/Internal/v1/FuelReportController.php +++ b/server/src/Http/Controllers/Internal/v1/FuelReportController.php @@ -27,7 +27,7 @@ class FuelReportController extends FleetOpsController * * Reads the custom field values from the payload the base controller already extracted * rather than from the raw request: Ember Data sends the resource under a camelCase root - * (`fuelReport`), so `$request->array('fuel_report.custom_field_values')` was always empty and no + * (`fuelReport`), so `$request->inputArray('fuel_report.custom_field_values')` was always empty and no * custom field value was ever persisted for this resource. */ public function afterSave(Request $request, FuelReport $fuelReport, array $input = []) @@ -46,7 +46,7 @@ public function afterSave(Request $request, FuelReport $fuelReport, array $input public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('fuel_report-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new FuelReportExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php b/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php index 223c82c75..5836a160c 100644 --- a/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php +++ b/server/src/Http/Controllers/Internal/v1/InspectionSubmissionController.php @@ -78,7 +78,7 @@ protected function syncAnswersFromRequest(Request $request, InspectionSubmission * The first of the given keys that carries a list. * * The console posts a record under its resource name and the app posts it - * flat, so both spellings are read. `Request::array()` arrived in Laravel + * flat, so both spellings are read. `Request::inputArray()` arrived in Laravel * 11 and this runs on 10, where calling it is a BadMethodCallException. * * @return array diff --git a/server/src/Http/Controllers/Internal/v1/IssueController.php b/server/src/Http/Controllers/Internal/v1/IssueController.php index bdd9fb98c..e235beaf4 100644 --- a/server/src/Http/Controllers/Internal/v1/IssueController.php +++ b/server/src/Http/Controllers/Internal/v1/IssueController.php @@ -42,12 +42,12 @@ public function afterSave(Request $request, Issue $issue) } } - $customFieldValues = $request->array('issue.custom_field_values'); + $customFieldValues = $request->inputArray('issue.custom_field_values'); if ($customFieldValues) { $issue->syncCustomFieldValues($customFieldValues); } - $uploads = $request->array('issue.files'); + $uploads = $request->inputArray('issue.files'); if ($uploads) { $this->filesForUploads($uploads)->each(function (File $file) use ($issue) { $file->setKey($issue); @@ -346,7 +346,7 @@ protected function formatChangeDescription(string $field, $from, $to): string public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('issue-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new IssueExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/LiveController.php b/server/src/Http/Controllers/Internal/v1/LiveController.php index 690960baf..0e415ce96 100644 --- a/server/src/Http/Controllers/Internal/v1/LiveController.php +++ b/server/src/Http/Controllers/Internal/v1/LiveController.php @@ -123,7 +123,7 @@ function ($q) { */ public function orders(Request $request) { - $exclude = $request->array('exclude'); + $exclude = $request->inputArray('exclude'); $active = $request->boolean('active'); $unassigned = $request->boolean('unassigned'); diff --git a/server/src/Http/Controllers/Internal/v1/MaintenanceController.php b/server/src/Http/Controllers/Internal/v1/MaintenanceController.php index 49e1ca3e3..122518b0d 100644 --- a/server/src/Http/Controllers/Internal/v1/MaintenanceController.php +++ b/server/src/Http/Controllers/Internal/v1/MaintenanceController.php @@ -42,7 +42,7 @@ class MaintenanceController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('maintenances-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new MaintenanceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php b/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php index 083ef8aad..68a2f7042 100644 --- a/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php +++ b/server/src/Http/Controllers/Internal/v1/MaintenanceScheduleController.php @@ -49,7 +49,7 @@ class MaintenanceScheduleController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('maintenance-schedules-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new MaintenanceScheduleExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/MetricsController.php b/server/src/Http/Controllers/Internal/v1/MetricsController.php index 4d3b374fd..3ae99059b 100644 --- a/server/src/Http/Controllers/Internal/v1/MetricsController.php +++ b/server/src/Http/Controllers/Internal/v1/MetricsController.php @@ -30,7 +30,7 @@ public function all(Request $request) { $start = $request->date('start'); $end = $request->date('end'); - $discover = $request->array('discover', []); + $discover = $request->inputArray('discover', []); try { $data = $this->metricsForCompany($request->user()->company, $start, $end)->with($discover)->get(); diff --git a/server/src/Http/Controllers/Internal/v1/OrderController.php b/server/src/Http/Controllers/Internal/v1/OrderController.php index 2bbe6420d..46061e37e 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderController.php @@ -97,18 +97,18 @@ class OrderController extends FleetOpsController */ public function onAfterUpdate($request, $order) { - $uploads = $request->array('order.files'); + $uploads = $request->inputArray('order.files'); if ($uploads) { $order->attachFiles($uploads); } - $waypoints = $request->array('order.payload.waypoints'); + $waypoints = $request->inputArray('order.payload.waypoints'); if ($waypoints) { $order->loadMissing('payload'); $order->payload->updateWaypoints($waypoints); } - $customFieldValues = $request->array('order.custom_field_values'); + $customFieldValues = $request->inputArray('order.custom_field_values'); if ($customFieldValues) { $order->syncCustomFieldValues($customFieldValues); } @@ -310,7 +310,7 @@ public function editOrderRoute(string $id, Request $request) $pickup = $request->input('pickup'); $dropoff = $request->input('dropoff'); $return = $request->input('return'); - $waypoints = $request->array('waypoints', []); + $waypoints = $request->inputArray('waypoints', []); $hasPickupInput = $request->exists('pickup'); $hasDropoffInput = $request->exists('dropoff'); $hasReturnInput = $request->exists('return'); @@ -957,7 +957,7 @@ public function updateActivity(string $id, Request $request) $proof = $request->input('proof'); $bypassProof = $request->boolean('bypass_proof'); - $activity = $request->array('activity'); + $activity = $request->inputArray('activity'); $activity = new Activity($activity, $order->getConfigFlow()); // Configs with strict transitions only accept a configured child of the current @@ -1932,7 +1932,7 @@ protected function proofsForSubject(Order $order, Order|Waypoint|Entity $subject public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('order-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadOrderExport($selections, $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/PartController.php b/server/src/Http/Controllers/Internal/v1/PartController.php index dd0df7ef9..0de693e35 100644 --- a/server/src/Http/Controllers/Internal/v1/PartController.php +++ b/server/src/Http/Controllers/Internal/v1/PartController.php @@ -27,7 +27,7 @@ class PartController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('parts-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new PartExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/PlaceController.php b/server/src/Http/Controllers/Internal/v1/PlaceController.php index 88b6d0306..071a54f71 100644 --- a/server/src/Http/Controllers/Internal/v1/PlaceController.php +++ b/server/src/Http/Controllers/Internal/v1/PlaceController.php @@ -28,7 +28,7 @@ class PlaceController extends FleetOpsController */ public function afterSave(Request $request, Place $place) { - $customFieldValues = $request->array('place.custom_field_values'); + $customFieldValues = $request->inputArray('place.custom_field_values'); if ($customFieldValues) { $this->syncCustomFieldValues($place, $customFieldValues); } @@ -86,7 +86,7 @@ public function geocode(ExportRequest $request) public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('places-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new PlaceExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/SensorController.php b/server/src/Http/Controllers/Internal/v1/SensorController.php index 8ba62feeb..b9b6b2c5b 100644 --- a/server/src/Http/Controllers/Internal/v1/SensorController.php +++ b/server/src/Http/Controllers/Internal/v1/SensorController.php @@ -25,7 +25,7 @@ class SensorController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('sensors-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new SensorExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php b/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php index 36926e45a..82249ff6c 100644 --- a/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php +++ b/server/src/Http/Controllers/Internal/v1/ServiceAreaController.php @@ -25,7 +25,7 @@ class ServiceAreaController extends FleetOpsController * * Reads the custom field values from the payload the base controller already extracted * rather than from the raw request: Ember Data sends the resource under a camelCase root - * (`serviceArea`), so `$request->array('service_area.custom_field_values')` was always empty and no + * (`serviceArea`), so `$request->inputArray('service_area.custom_field_values')` was always empty and no * custom field value was ever persisted for this resource. */ public function afterSave(Request $request, ServiceArea $serviceArea, array $input = []) @@ -44,7 +44,7 @@ public function afterSave(Request $request, ServiceArea $serviceArea, array $inp public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('service-areas-' . date('Y-m-d-H:i')) . '.' . $format); return static::downloadExport(new ServiceAreaExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ServiceRateController.php b/server/src/Http/Controllers/Internal/v1/ServiceRateController.php index 577bc2316..fe786fb4e 100644 --- a/server/src/Http/Controllers/Internal/v1/ServiceRateController.php +++ b/server/src/Http/Controllers/Internal/v1/ServiceRateController.php @@ -129,7 +129,7 @@ protected function getServicableForWaypoints(Collection $waypoints, \Closure $qu public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('contacts-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new ServiceRateExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/SettingController.php b/server/src/Http/Controllers/Internal/v1/SettingController.php index dad37acd8..c7cc47d25 100644 --- a/server/src/Http/Controllers/Internal/v1/SettingController.php +++ b/server/src/Http/Controllers/Internal/v1/SettingController.php @@ -137,7 +137,7 @@ public function getDriverOnboardSettings($companyId = null) */ public function savedDriverOnboardSettings(Request $request) { - $driverOnboardSettings = $request->array('driverOnboardSettings', []); + $driverOnboardSettings = $request->inputArray('driverOnboardSettings', []); $driverOnboardSettings['companyId'] = session('company'); if (empty($driverOnboardSettings['enableDriverOnboardFromApp'])) { @@ -154,7 +154,7 @@ public function savedDriverOnboardSettings(Request $request) public function saveCustomerEnabledOrderConfigs(Request $request) { - $enabledOrderConfigs = array_values($request->array('enabledOrderConfigs')); + $enabledOrderConfigs = array_values($request->inputArray('enabledOrderConfigs')); $this->configureCompanySetting('fleet-ops.customer-enabled-order-configs', $enabledOrderConfigs); return response()->json($enabledOrderConfigs); @@ -169,7 +169,7 @@ public function getCustomerEnabledOrderConfigs() public function saveCustomerPortalPaymentConfig(Request $request) { - $paymentsConfig = $request->array('paymentsConfig'); + $paymentsConfig = $request->inputArray('paymentsConfig'); $this->configureCompanySetting('fleet-ops.customer-payments-configs', $paymentsConfig); return response()->json($paymentsConfig); diff --git a/server/src/Http/Controllers/Internal/v1/TelematicController.php b/server/src/Http/Controllers/Internal/v1/TelematicController.php index 4f056da5b..93b8ff7f5 100644 --- a/server/src/Http/Controllers/Internal/v1/TelematicController.php +++ b/server/src/Http/Controllers/Internal/v1/TelematicController.php @@ -56,7 +56,7 @@ public function __construct(TelematicService $service, TelematicProviderRegistry public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('telematics-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new TelematicExport($selections), $fileName); @@ -108,7 +108,7 @@ public function testConnection(Request $request, string $id): JsonResponse #[SkipAuthorizationCheck] public function testCredentials(Request $request, string $key): JsonResponse { - $credentials = $request->array('credentials', []); + $credentials = $request->inputArray('credentials', []); $async = $request->input('async', false); try { diff --git a/server/src/Http/Controllers/Internal/v1/TrailerController.php b/server/src/Http/Controllers/Internal/v1/TrailerController.php index 41420ded5..106471679 100644 --- a/server/src/Http/Controllers/Internal/v1/TrailerController.php +++ b/server/src/Http/Controllers/Internal/v1/TrailerController.php @@ -50,7 +50,7 @@ class TrailerController extends FleetOpsController */ public function afterSave(Request $request, Trailer $trailer): void { - $values = $request->array('trailer.custom_field_values'); + $values = $request->inputArray('trailer.custom_field_values'); if ($values) { $trailer->syncCustomFieldValues($values); @@ -313,7 +313,7 @@ public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - return $this->downloadExport(new TrailerExport($request->array('selections')), Str::slug('trailers-' . date('Y-m-d-H:i')) . '.' . $format); + return $this->downloadExport(new TrailerExport($request->inputArray('selections')), Str::slug('trailers-' . date('Y-m-d-H:i')) . '.' . $format); } public function import(ImportRequest $request) diff --git a/server/src/Http/Controllers/Internal/v1/VehicleController.php b/server/src/Http/Controllers/Internal/v1/VehicleController.php index 25712b6cb..7d6f25ede 100644 --- a/server/src/Http/Controllers/Internal/v1/VehicleController.php +++ b/server/src/Http/Controllers/Internal/v1/VehicleController.php @@ -56,7 +56,7 @@ public function afterSave(Request $request, Vehicle $vehicle, array $input = []) $this->syncDriverAssignment($vehicle, $this->driverIdentifierFromRequest($request)); } - $customFieldValues = $request->array('vehicle.custom_field_values'); + $customFieldValues = $request->inputArray('vehicle.custom_field_values'); if ($customFieldValues) { $vehicle->syncCustomFieldValues($customFieldValues); } @@ -472,7 +472,7 @@ public function avatars() public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('vehicles-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new VehicleExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/VendorController.php b/server/src/Http/Controllers/Internal/v1/VendorController.php index 69c100da2..f243d2cfe 100644 --- a/server/src/Http/Controllers/Internal/v1/VendorController.php +++ b/server/src/Http/Controllers/Internal/v1/VendorController.php @@ -44,7 +44,7 @@ class VendorController extends FleetOpsController */ public function afterSave(Request $request, Vendor $vendor) { - $customFieldValues = $request->array('vendor.custom_field_values'); + $customFieldValues = $request->inputArray('vendor.custom_field_values'); if ($customFieldValues) { $vendor->syncCustomFieldValues($customFieldValues); } @@ -94,7 +94,7 @@ public function getAsCustomer($id) public static function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('vendors-' . date('Y-m-d-H:i')) . '.' . $format); return Excel::download(new VendorExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/WorkOrderController.php b/server/src/Http/Controllers/Internal/v1/WorkOrderController.php index 28d37e315..0e0e22e63 100644 --- a/server/src/Http/Controllers/Internal/v1/WorkOrderController.php +++ b/server/src/Http/Controllers/Internal/v1/WorkOrderController.php @@ -41,7 +41,7 @@ class WorkOrderController extends FleetOpsController public function export(ExportRequest $request) { $format = $request->input('format', 'xlsx'); - $selections = $request->array('selections'); + $selections = $request->inputArray('selections'); $fileName = trim(Str::slug('work-orders-' . date('Y-m-d-H:i')) . '.' . $format); return $this->downloadExport(new WorkOrderExport($selections), $fileName); diff --git a/server/src/Http/Controllers/Internal/v1/ZoneController.php b/server/src/Http/Controllers/Internal/v1/ZoneController.php index e790d0a57..2b1515a3b 100644 --- a/server/src/Http/Controllers/Internal/v1/ZoneController.php +++ b/server/src/Http/Controllers/Internal/v1/ZoneController.php @@ -20,7 +20,7 @@ class ZoneController extends FleetOpsController */ public function afterSave(Request $request, Zone $zone) { - $customFieldValues = $request->array('zone.custom_field_values'); + $customFieldValues = $request->inputArray('zone.custom_field_values'); if ($customFieldValues) { $zone->syncCustomFieldValues($customFieldValues); } diff --git a/server/tests/CompactResourceSerializationTest.php b/server/tests/CompactResourceSerializationTest.php index 658f68a7b..b14fa1cb0 100644 --- a/server/tests/CompactResourceSerializationTest.php +++ b/server/tests/CompactResourceSerializationTest.php @@ -67,7 +67,7 @@ public function isArray(string $key): bool return is_array($this->input($key)); } - public function array(string $key): array + public function inputArray(string $key): array { $value = $this->input($key); diff --git a/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php b/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php index 2420ead6d..96b87a378 100644 --- a/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php +++ b/server/tests/Feature/Http/Api/TrailerControllerLifecycleTest.php @@ -90,7 +90,7 @@ protected function importFile(TrailerImport $import, string $path, string $disk) class FleetOpsTrailerExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { return (array) $this->input($key, $default); } diff --git a/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php b/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php index b502938bc..30361c806 100644 --- a/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/DriverControllerContractsTest.php @@ -27,7 +27,7 @@ class FleetOpsInternalDriverExportImportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php b/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php index 55cebc030..677608edc 100644 --- a/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/IssueControllerContractsTest.php @@ -196,7 +196,7 @@ public function setKey($model, $type = null): File class FleetOpsInternalIssueRequestFake extends Request { - public function array($key = null, $default = []): array + public function inputArray($key = null, $default = []): array { $value = data_get($this->all(), $key, $default); diff --git a/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php b/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php index c840ed7cb..033720a91 100644 --- a/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/MetricsControllerContractsTest.php @@ -131,7 +131,7 @@ public function string($key = null, $default = null): Stringable return str((string) ($this->values[$key] ?? $default ?? '')); } - public function array($key = null, $default = []): array + public function inputArray($key = null, $default = []): array { $value = $this->values[$key] ?? $default; diff --git a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php index e1a714436..69bfcbfd4 100644 --- a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php @@ -178,8 +178,8 @@ function fleetopsInternalOrderConfigDbBoot(): SQLiteConnection return $default; }); } - if (!Request::hasMacro('array')) { - Request::macro('array', fn (string $key, $default = []) => (array) $this->input($key, $default)); + if (!Request::hasMacro('inputArray')) { + Request::macro('inputArray', fn (string $key, $default = []) => (array) $this->input($key, $default)); } if (!class_exists('Illuminate\\Validation\\Rule', false)) { eval('namespace Illuminate\\Validation; class Rule { public static function __callStatic($method, $arguments) { return new class { public function __call($method, $arguments) { return $this; } }; } }'); diff --git a/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php index ff183cbe5..30af9c5d2 100644 --- a/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderControllerContractsTest.php @@ -912,7 +912,7 @@ public function input($key = null, $default = null) return data_get($this->payload, $key, $default); } - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php b/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php index e7c450ff8..9cafb6a26 100644 --- a/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/WorkOrderControllerContractsTest.php @@ -17,7 +17,7 @@ class FleetOpsInternalWorkOrderExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/InternalFleetControllerContractsTest.php b/server/tests/InternalFleetControllerContractsTest.php index 847ae4b9a..bd00b1cfa 100644 --- a/server/tests/InternalFleetControllerContractsTest.php +++ b/server/tests/InternalFleetControllerContractsTest.php @@ -23,7 +23,7 @@ class FleetOpsInternalFleetActionRequestFake extends FleetActionRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); @@ -33,7 +33,7 @@ public function array($key = null, $default = []) class FleetOpsInternalFleetExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/InternalImportExportControllerContractsTest.php b/server/tests/InternalImportExportControllerContractsTest.php index db8282592..9aeb01d36 100644 --- a/server/tests/InternalImportExportControllerContractsTest.php +++ b/server/tests/InternalImportExportControllerContractsTest.php @@ -25,7 +25,7 @@ class FleetOpsInternalExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); @@ -37,7 +37,7 @@ class FleetOpsInternalImportRequestFake extends ImportRequest { public array $resolvedFiles = []; - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/OrderFileAttachmentTest.php b/server/tests/OrderFileAttachmentTest.php index c75d10a55..8ef19957d 100644 --- a/server/tests/OrderFileAttachmentTest.php +++ b/server/tests/OrderFileAttachmentTest.php @@ -7,7 +7,7 @@ $formJs = file_get_contents(dirname(dirname(__DIR__)) . '/addon/components/order/form/documents.js'); expect($controller) - ->toContain("\$uploads = \$request->array('order.files')") + ->toContain("\$uploads = \$request->inputArray('order.files')") ->toContain('$order->attachFiles($uploads)') ->and($orderModel) ->toContain('public function attachFiles($uploads): self') diff --git a/server/tests/ServiceRateRouteValidationTest.php b/server/tests/ServiceRateRouteValidationTest.php index 9b9916076..a2a00d216 100644 --- a/server/tests/ServiceRateRouteValidationTest.php +++ b/server/tests/ServiceRateRouteValidationTest.php @@ -151,7 +151,7 @@ public function where($column, $value) // Exports stream through the excel facade if (!class_exists('Fleetbase\\Http\\Requests\\ExportRequest', false)) { - eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function array($key, $default = []) { return (array) $this->input($key, $default); } }'); + eval('namespace Fleetbase\\Http\\Requests; class ExportRequest extends \\Illuminate\\Http\\Request { public function inputArray($key, $default = []) { return (array) $this->input($key, $default); } }'); } $excelFake = new class { public array $downloads = []; diff --git a/server/tests/SmallControllerContractsTest.php b/server/tests/SmallControllerContractsTest.php index a55c96d93..f84a845fd 100644 --- a/server/tests/SmallControllerContractsTest.php +++ b/server/tests/SmallControllerContractsTest.php @@ -26,7 +26,7 @@ class FleetOpsSmallControllerExportRequestFake extends ExportRequest { - public function array($key = null, $default = []) + public function inputArray($key = null, $default = []) { $value = $this->input($key, $default); diff --git a/server/tests/Unit/Http/Resources/FleetResourceTest.php b/server/tests/Unit/Http/Resources/FleetResourceTest.php index cb80ecdf2..90dc5eb05 100644 --- a/server/tests/Unit/Http/Resources/FleetResourceTest.php +++ b/server/tests/Unit/Http/Resources/FleetResourceTest.php @@ -17,8 +17,8 @@ Request::macro('isArray', fn (string $key) => is_array($this->input($key))); } -if (!Request::hasMacro('array')) { - Request::macro('array', fn (string $key, $default = []) => (array) $this->input($key, $default)); +if (!Request::hasMacro('inputArray')) { + Request::macro('inputArray', fn (string $key, $default = []) => (array) $this->input($key, $default)); } function fleetopsFleetResourceBoot(): SQLiteConnection From 4f2353f7e7aea91a9546afbdfcbe4327fc9a68cc Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Wed, 4 Nov 2026 16:42:28 +0800 Subject: [PATCH 11/29] chore(l12): keep fresh-install columns identical without Doctrine Restate nullable on ->change() calls, which Laravel 11+ no longer preserves. Replace unsignedDecimal with decimal()->unsigned(), set DOUBLE(12,2) on routes and DOUBLE(8,2) on the sensors thresholds in SQL since Blueprint::double() and float() drop total and places, and check indexes through TableIndexes. Fresh MySQL schema is unchanged on Laravel 10. --- .../2023_04_27_053456_create_routes_table.php | 11 +++++++++-- ...023_11_03_072503_refactor_issues_table_columns.php | 4 ++-- ...2024_02_18_100209_add_avatar_url_columns_table.php | 4 ++-- ...03_004854_increase_service_quote_amount_column.php | 4 ++-- .../2025_08_28_054926_create_sensors_table.php | 7 +++++++ ...itional_spec_columns_for_assets_vehicles_table.php | 4 ++-- ...dd_performance_indexes_to_fleetops_core_tables.php | 7 ++----- ...001_add_orchestrator_columns_to_vehicles_table.php | 4 ++-- ...004_add_orchestrator_columns_to_payloads_table.php | 4 ++-- ...redundant_capacity_columns_from_payloads_table.php | 4 ++-- ...0002_rename_capacity_columns_on_vehicles_table.php | 2 +- 11 files changed, 33 insertions(+), 22 deletions(-) diff --git a/server/migrations/2023_04_27_053456_create_routes_table.php b/server/migrations/2023_04_27_053456_create_routes_table.php index 0c22f685a..f1f0899db 100644 --- a/server/migrations/2023_04_27_053456_create_routes_table.php +++ b/server/migrations/2023_04_27_053456_create_routes_table.php @@ -19,12 +19,19 @@ public function up() $table->char('company_uuid', 36)->nullable()->index(); $table->char('order_uuid', 36)->nullable()->index(); $table->json('details')->nullable(); - $table->double('total_distance', 12, 2)->nullable(); - $table->double('total_time', 12, 2)->nullable(); + $table->double('total_distance')->nullable(); + $table->double('total_time')->nullable(); $table->softDeletes(); $table->timestamp('created_at')->nullable()->index(); $table->timestamp('updated_at')->nullable(); }); + + // Blueprint::double() only takes total and places before Laravel 11, so set them in SQL. + if (Schema::getConnection()->getDriverName() === 'mysql') { + Schema::getConnection()->statement( + 'ALTER TABLE `routes` MODIFY COLUMN `total_distance` DOUBLE(12,2) NULL, MODIFY COLUMN `total_time` DOUBLE(12,2) NULL' + ); + } } /** diff --git a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php index 3727a3a03..42e4e4886 100644 --- a/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php +++ b/server/migrations/2023_11_03_072503_refactor_issues_table_columns.php @@ -17,7 +17,7 @@ public function up() $table->string('category')->nullable()->after('type'); $table->json('tags')->nullable()->after('priority'); $table->json('meta')->nullable()->after('priority'); - $table->mediumText('report')->change(); + $table->mediumText('report')->nullable()->change(); $table->foreignUuid('reported_by_uuid')->nullable()->after('assigned_to_uuid')->references('uuid')->on('users')->onDelete('cascade'); }); } @@ -33,7 +33,7 @@ public function down() $table->string('longitude')->nullable()->after('location'); $table->string('latitude')->nullable()->after('location'); $table->string('odometer')->nullable()->after('location'); - $table->string('report')->change(); + $table->string('report')->nullable()->change(); $table->dropForeign(['reported_by_uuid']); $table->dropColumn(['reported_by_uuid', 'meta', 'tags', 'category']); }); diff --git a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php index 13bb4c1be..ecc5166fa 100644 --- a/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php +++ b/server/migrations/2024_02_18_100209_add_avatar_url_columns_table.php @@ -14,7 +14,7 @@ public function up() { // Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->mediumText('avatar_url')->change(); + $table->mediumText('avatar_url')->nullable()->change(); }); // Add avatar url column to places @@ -38,7 +38,7 @@ public function down() // @todo this can break migrations if avatar url is over 300 characters to we need to remove this and keep mediumtext // Reverse: Increase size of vehicles avatar url column for signed urls Schema::table('vehicles', function (Blueprint $table) { - $table->string('avatar_url', 300)->change(); + $table->string('avatar_url', 300)->nullable()->change(); }); // Reverse: Add avatar url column to places diff --git a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php index 2b658b3d8..acb915210 100644 --- a/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php +++ b/server/migrations/2025_01_03_004854_increase_service_quote_amount_column.php @@ -11,7 +11,7 @@ public function up(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->bigInteger('amount')->change(); + $table->bigInteger('amount')->nullable()->change(); }); } @@ -21,7 +21,7 @@ public function up(): void public function down(): void { Schema::table('service_quotes', function (Blueprint $table) { - $table->integer('amount')->change(); + $table->integer('amount')->nullable()->change(); }); } }; diff --git a/server/migrations/2025_08_28_054926_create_sensors_table.php b/server/migrations/2025_08_28_054926_create_sensors_table.php index 731ae7158..55f3e7697 100644 --- a/server/migrations/2025_08_28_054926_create_sensors_table.php +++ b/server/migrations/2025_08_28_054926_create_sensors_table.php @@ -48,6 +48,13 @@ public function up(): void $table->index(['company_uuid', 'sensor_type']); }); + + // Blueprint::float() defaulted to total and places before Laravel 11, so set them in SQL. + if (Schema::getConnection()->getDriverName() === 'mysql') { + Schema::getConnection()->statement( + 'ALTER TABLE `sensors` MODIFY COLUMN `min_threshold` DOUBLE(8,2) NULL, MODIFY COLUMN `max_threshold` DOUBLE(8,2) NULL' + ); + } } /** diff --git a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php index 00f072dd9..da5711049 100644 --- a/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php +++ b/server/migrations/2025_09_10_010724_create_additional_spec_columns_for_assets_vehicles_table.php @@ -23,7 +23,7 @@ public function up(): void $table->mediumText('notes')->after('meta')->nullable(); $table->string('usage_type')->after('type')->nullable(); $table->string('measurement_system')->after('type')->nullable(); - $table->json('vin_data')->change(); + $table->json('vin_data')->nullable()->change(); $table->renameColumn('model_data', 'specs'); }); @@ -70,7 +70,7 @@ public function down(): void $table->dropColumn('usage_type'); $table->dropColumn('measurement_system'); $table->dropColumn('ownership_type'); - $table->mediumText('vin_data')->change(); + $table->mediumText('vin_data')->nullable()->change(); $table->renameColumn('specs', 'model_data'); }); } diff --git a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php index 17b129cc5..a1065bdf4 100644 --- a/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php +++ b/server/migrations/2025_12_16_000003_add_performance_indexes_to_fleetops_core_tables.php @@ -1,5 +1,6 @@ getDoctrineSchemaManager(); - $indexes = $doctrineSchemaManager->listTableIndexes($table); - - return isset($indexes[$index]); + return isset(TableIndexes::for($table)[$index]); } catch (Exception $e) { return false; } diff --git a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php index e9555ac8f..e4725974e 100644 --- a/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php +++ b/server/migrations/2026_04_08_000001_add_orchestrator_columns_to_vehicles_table.php @@ -25,8 +25,8 @@ public function up(): void // Skills / capabilities $table->json('skills')->nullable()->after('status'); // Multi-dimensional capacity - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); // Route constraints diff --git a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php index 002226d38..5703f5c7a 100644 --- a/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php +++ b/server/migrations/2026_04_08_000004_add_orchestrator_columns_to_payloads_table.php @@ -20,8 +20,8 @@ public function up(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php index 2b028548a..df1eed0c3 100644 --- a/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php +++ b/server/migrations/2026_04_14_000001_drop_redundant_capacity_columns_from_payloads_table.php @@ -35,8 +35,8 @@ public function up(): void public function down(): void { Schema::table('payloads', function (Blueprint $table) { - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('cod_currency'); - $table->unsignedDecimal('capacity_volume_m3', 10, 3)->nullable()->after('capacity_weight_kg'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('cod_currency'); + $table->decimal('capacity_volume_m3', 10, 3)->unsigned()->nullable()->after('capacity_weight_kg'); $table->unsignedInteger('capacity_pallets')->nullable()->after('capacity_volume_m3'); $table->unsignedInteger('capacity_parcels')->nullable()->after('capacity_pallets'); }); diff --git a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php index 0f5e809d7..e9f65903a 100644 --- a/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php +++ b/server/migrations/2026_04_14_000002_rename_capacity_columns_on_vehicles_table.php @@ -39,7 +39,7 @@ public function down(): void { Schema::table('vehicles', function (Blueprint $table) { // Restore the dropped column - $table->unsignedDecimal('capacity_weight_kg', 10, 2)->nullable()->after('skills'); + $table->decimal('capacity_weight_kg', 10, 2)->unsigned()->nullable()->after('skills'); // Reverse the renames $table->renameColumn('payload_capacity_volume', 'capacity_volume_m3'); From 7d042600aee63cb4d7073d925cd197058a459ef3 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 10:37:46 +0800 Subject: [PATCH 12/29] feat(dispatch): safe accept, timed offers and a ride order config - Accepting an adhoc order is one conditional update, so of two drivers only the first gets it. The driver must work for the order's company and be online, a signed-in driver can only accept for themselves, and a canceled order can't be accepted. - Drivers pinged or offered an order are of the order's company, not on another job, and of the vehicle class booked (`meta.vehicle_class`). - `fleetops:dispatch-adhoc` re-pings again: both ends of its window were moved back 72 hours by one shared Carbon. It no longer re-dispatches, which pinged every driver twice. - An order config with `meta.offers.enabled` offers an order to one driver at a time, nearest first, for `meta.offers.timeout` seconds. Drivers decline with `POST orders/{id}/decline`. With nobody left, the order is canceled as "No driver found". - `fleetops:create-ride-config` adds a strict ride flow: dispatched, started (driver on the way), arrived, in_progress, completed, or no_show. - Strict transitions are enforced on the public update-activity route too. - Fare previews with `availability=1` add each class's seats and how soon its nearest free car could arrive. - Customers can no longer subscribe to a driver's socket channel, whose location events carry the driver's phone number. --- ...11_06_000001_create_order_offers_table.php | 35 ++++ .../src/Console/Commands/CreateRideConfig.php | 44 +++++ .../Console/Commands/DispatchAdhocOrders.php | 62 ++++++- .../Controllers/Api/v1/OrderController.php | 132 +++++++++++++- .../Api/v1/ServiceQuoteController.php | 91 ++++++++-- server/src/Jobs/ExpireOrderOffer.php | 34 ++++ .../src/Listeners/HandleOrderDispatched.php | 38 +++- server/src/Models/Order.php | 16 +- server/src/Models/OrderConfig.php | 17 ++ server/src/Models/OrderOffer.php | 41 +++++ .../src/Providers/FleetOpsServiceProvider.php | 1 + server/src/Support/DriverMatching.php | 82 +++++++++ server/src/Support/FleetOps.php | 75 ++++++++ server/src/Support/OrderOffers.php | 170 ++++++++++++++++++ server/src/Support/SocketChannels.php | 12 +- server/tests/CommandContractsTest.php | 17 ++ .../Api/OrderControllerStartActivityTest.php | 157 ++++++++++++++++ .../OrderDispatchListenerContractsTest.php | 7 +- .../HandleOrderDispatchedConcreteTest.php | 7 +- .../HandleOrderDispatchedHelpersTest.php | 9 +- .../Models/OrderPurchaseAndDriversTest.php | 6 +- .../tests/Unit/Support/SocketChannelsTest.php | 10 +- 22 files changed, 1011 insertions(+), 52 deletions(-) create mode 100644 server/migrations/2026_11_06_000001_create_order_offers_table.php create mode 100644 server/src/Console/Commands/CreateRideConfig.php create mode 100644 server/src/Jobs/ExpireOrderOffer.php create mode 100644 server/src/Models/OrderOffer.php create mode 100644 server/src/Support/DriverMatching.php create mode 100644 server/src/Support/OrderOffers.php diff --git a/server/migrations/2026_11_06_000001_create_order_offers_table.php b/server/migrations/2026_11_06_000001_create_order_offers_table.php new file mode 100644 index 000000000..d4a5bf2d0 --- /dev/null +++ b/server/migrations/2026_11_06_000001_create_order_offers_table.php @@ -0,0 +1,35 @@ +increments('id'); + $table->uuid('uuid')->unique(); + $table->uuid('company_uuid')->nullable()->index(); + $table->uuid('order_uuid')->index(); + $table->uuid('driver_uuid')->index(); + $table->string('status', 16)->default('pending'); + $table->unsignedInteger('distance')->nullable(); + $table->timestamp('expires_at')->nullable()->index(); + $table->timestamp('responded_at')->nullable(); + $table->timestamps(); + $table->softDeletes(); + + $table->index(['order_uuid', 'status']); + }); + } + + public function down(): void + { + Schema::dropIfExists('order_offers'); + } +}; diff --git a/server/src/Console/Commands/CreateRideConfig.php b/server/src/Console/Commands/CreateRideConfig.php new file mode 100644 index 000000000..91baf9b68 --- /dev/null +++ b/server/src/Console/Commands/CreateRideConfig.php @@ -0,0 +1,44 @@ +argument('company'); + $company = Company::where('uuid', $id)->orWhere('public_id', $id)->first(); + if (!$company) { + $this->error('No company found for ' . $id . '.'); + + return self::FAILURE; + } + + $config = FleetOps::createRideConfig($company); + + // What the rider app shows from these settings: see customers/ride-settings. + $rider = array_filter([ + 'emergency_number' => $this->option('emergency-number'), + 'support_phone' => $this->option('support-phone'), + 'support_email' => $this->option('support-email'), + ], fn ($value) => is_string($value) && trim($value) !== ''); + if ($rider) { + $config->update(['meta' => array_replace_recursive((array) $config->meta, ['rider' => $rider])]); + } + $this->info('Ride config ' . $config->public_id . ' is ready for ' . $company->name . '.'); + + return self::SUCCESS; + } +} diff --git a/server/src/Console/Commands/DispatchAdhocOrders.php b/server/src/Console/Commands/DispatchAdhocOrders.php index 31e91f342..2fff37810 100644 --- a/server/src/Console/Commands/DispatchAdhocOrders.php +++ b/server/src/Console/Commands/DispatchAdhocOrders.php @@ -4,8 +4,11 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\FleetOps\Models\OrderOffer; use Fleetbase\FleetOps\Notifications\OrderPing; +use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\NavigatorReview; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Console\Command; @@ -57,6 +60,12 @@ public function handle(): void $this->table(['Order', 'Dispatched At'], $orders->map(fn ($order) => [$order->public_id, $order->dispatched_at])); foreach ($orders as $order) { + // Orders with timed offers go to one driver at a time, so only a stuck offer is moved on here. + if ($this->usesTimedOffers($order)) { + $this->advanceOffers($order); + continue; + } + $pickup = $order->getPickupLocation(); $distance = $order->getAdhocPingDistance(); @@ -70,7 +79,8 @@ public function handle(): void $this->line('Checking order ' . $order->public_id . ' for nearby drivers within ' . $distance . ' meters.'); if ($drivers->count()) { - $order->dispatch(true); + // Dispatching again would fire OrderDispatched, whose listener pings every driver a second time. + $this->markPinged($order); $this->info('Order ' . $order->public_id . ' dispatched successfully to ' . $drivers->count() . ' nearby drivers.'); foreach ($drivers as $driver) { $this->info('Pinging driver ' . $driver->name . ' (' . $driver->public_id . ') ...'); @@ -95,16 +105,16 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i { $sandbox = Utils::castBoolean($this->option('sandbox')); + // Each bound gets its own instance: subtracting from one shared Carbon moved both ends + // back 72 hours, leaving a window that never matched. $cutoffDate = Carbon::now()->subDays($days); - $now = Carbon::now(); + $oldest = Carbon::now()->subHours($expiryHours); + $newest = Carbon::now()->subMinutes($intervalMinutes); return $this->newOrderQuery($sandbox ? 'sandbox' : 'mysql') ->withoutGlobalScopes() ->where(['adhoc' => 1, 'dispatched' => 1, 'started' => 0]) - ->whereBetween('dispatched_at', [ - $now->subHours($expiryHours), // not older than 72 hours - $now->subMinutes($intervalMinutes), - ]) + ->whereBetween('dispatched_at', [$oldest, $newest]) ->where('created_at', '>=', $cutoffDate) ->whereNull('driver_assigned_uuid') ->whereNull('deleted_at') @@ -148,7 +158,45 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista $driverQuery->distanceSphereValue('location', $pickup); } - return $driverQuery->get(); + return $this->matchDrivers($driverQuery, $order)->get(); + } + + /** + * Leave out drivers already on another job and drivers of another vehicle class. + */ + protected function matchDrivers($driverQuery, Order $order) + { + DriverMatching::notBusy($driverQuery); + + return DriverMatching::forVehicleClass($driverQuery, DriverMatching::vehicleClass($order)); + } + + /** + * Restart the order's re-ping interval without dispatching it again. + */ + protected function markPinged(Order $order): void + { + $order->forceFill(['dispatched_at' => Carbon::now()])->saveQuietly(); + } + + protected function usesTimedOffers(Order $order): bool + { + return (bool) $order->config()?->usesTimedOffers(); + } + + /** + * Close an offer whose expiry job was lost, or start offers that never began. + */ + protected function advanceOffers(Order $order): void + { + $pending = OrderOffers::pending($order); + if ($pending && $pending->expires_at?->isPast()) { + OrderOffers::expire($pending); + $this->info('Moved order ' . $order->public_id . ' to the next driver.'); + } elseif (!$pending && !OrderOffer::where('order_uuid', $order->uuid)->exists()) { + OrderOffers::start($order); + $this->info('Started offers for order ' . $order->public_id . '.'); + } } protected function newOrderQuery(string $connection) diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index b4e654289..025614430 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -26,6 +26,7 @@ use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\OrderEdit; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\ResolvesOrderServiceStops; use Fleetbase\FleetOps\Support\TrackingCode; use Fleetbase\FleetOps\Support\Utils; @@ -34,6 +35,7 @@ use Fleetbase\Models\Company; use Fleetbase\Models\File; use Fleetbase\Models\Setting; +use Fleetbase\Models\User; use Fleetbase\Support\Auth; use Fleetbase\Support\TemplateString; use Illuminate\Database\Eloquent\ModelNotFoundException; @@ -1131,9 +1133,16 @@ public function startOrder(string $id, Request $request) return response()->apiError('Order has already started.'); } - // if the order is adhoc and the parameter of `assign` is set with a valid driver id, assign the driver and continue + if ($order->status === 'canceled') { + return response()->apiError('This order was canceled.', 409); + } + + // An adhoc order goes to the first driver who claims it; everyone after is refused. if ($order->adhoc && $assignAdhocDriver && Str::startsWith($assignAdhocDriver, 'driver_')) { - $order->assignDriver($assignAdhocDriver, true); + $refusal = $this->claimAdhocOrder($order, $assignAdhocDriver); + if ($refusal) { + return $refusal; + } } /** @var \Fleetbase\Models\Driver */ @@ -1194,6 +1203,113 @@ public function startOrder(string $id, Request $request) return $this->updateActivity($order, $updateActivityRequest); } + /** + * Claim an adhoc order for a driver of its company who is online. The claim is one + * conditional update, so of two drivers accepting at once only one gets the order. Returns + * the refusal, or null once the driver holds the order. + */ + protected function claimAdhocOrder(Order $order, string $driverId): mixed + { + $driver = $this->findAdhocDriver($driverId); + if (!$driver || !$this->driverServesCompany($driver, $order->company_uuid)) { + return response()->apiError('Driver not found.', 404); + } + + // A driver signed in to the app may only accept for themselves. + $signedIn = $this->signedInDriver($order->company_uuid); + if ($signedIn && $signedIn->uuid !== $driver->uuid) { + return response()->apiError('You can only accept orders for yourself.', 403); + } + + if ($order->driver_assigned_uuid === $driver->uuid) { + return null; + } + + if (!$driver->online) { + return response()->apiError('Go online to accept orders.', 422); + } + + $orderConfig = $order->config(); + if ($orderConfig->usesTimedOffers() && !OrderOffers::accept($order, $driver)) { + return response()->apiError('This order is no longer offered to you.', 409); + } + + $claimed = Order::withoutGlobalScopes() + ->where('uuid', $order->uuid) + ->whereNull('driver_assigned_uuid') + ->where('status', '!=', 'canceled') + ->where(fn ($query) => $query->whereNull('started')->orWhere('started', 0)) + ->update(['driver_assigned_uuid' => $driver->uuid]); + + if (!$claimed) { + return response()->apiError('This order was taken by another driver.', 409); + } + + // The claim saved the driver directly; assigning again runs the order observer for it. + $order->driver_assigned_uuid = null; + $order->assignDriver($driver, true); + + return null; + } + + /** + * Turn down an order offered to the driver, so it goes to the next driver. + */ + public function declineOrder(string $id, Request $request) + { + try { + $order = $this->findOrder($id); + } catch (ModelNotFoundException $exception) { + return response()->apiError('Order resource not found.', 404); + } + + $driver = $this->signedInDriver($order->company_uuid); + $named = $request->input('driver'); + if (!$driver && is_string($named) && Str::startsWith($named, 'driver_')) { + $driver = $this->findAdhocDriver($named); + $driver = $driver && $this->driverServesCompany($driver, $order->company_uuid) ? $driver : null; + } + if (!$driver) { + return response()->apiError('Driver not found.', 404); + } + + if (!OrderOffers::decline($order, $driver)) { + return response()->apiError('This order is not offered to you.', 409); + } + + return response()->json(['status' => 'declined', 'order' => $order->public_id]); + } + + protected function findAdhocDriver(string $publicId): ?Driver + { + return Driver::withoutGlobalScopes()->where('public_id', $publicId)->whereNull('deleted_at')->first(); + } + + /** + * Whether the driver works for the company, directly or through their user. + */ + protected function driverServesCompany(Driver $driver, ?string $companyUuid): bool + { + if ($driver->company_uuid === $companyUuid) { + return true; + } + + return $driver->user_uuid && User::where('uuid', $driver->user_uuid)->value('company_uuid') === $companyUuid; + } + + /** + * The driver profile of the user whose token signed this request, if they drive for the company. + */ + protected function signedInDriver(?string $companyUuid): ?Driver + { + $userUuid = session('user'); + if (!$userUuid) { + return null; + } + + return Driver::withoutGlobalScopes()->where('user_uuid', $userUuid)->where('company_uuid', $companyUuid)->whereNull('deleted_at')->first(); + } + /** * Update an order activity. * @@ -1260,6 +1376,18 @@ public function updateActivity($id, Request $request) $activity = new Activity($activity, $order->getConfigFlow()); } + // Configs with strict transitions only accept a configured child of the current + // activity, and the server's activity definition replaces the one sent. + if ($orderConfig && $orderConfig->hasStrictTransitions() && !($activity->is('dispatched') && $skipDispatch)) { + $targetCode = $activity->get('code'); + $configured = $targetCode ? $orderConfig->getActivityByCode($targetCode) : null; + if (!$configured || !$orderConfig->canTransition($order->status, $targetCode)) { + return response()->apiError('This activity is not a permitted next step for the order.', 422); + } + + $activity = $configured; + } + // if we're going to skip the dispatch get the next activity status and flow and continue if (Utils::isActivity($activity) && $activity->is('dispatched') && $skipDispatch) { $activity = $orderConfig->getStartedActivity(); diff --git a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php index 8f20b463e..5890e945b 100644 --- a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php +++ b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php @@ -4,6 +4,7 @@ use Fleetbase\FleetOps\Http\Requests\QueryServiceQuotesRequest; use Fleetbase\FleetOps\Http\Resources\v1\ServiceQuote as ServiceQuoteResource; +use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Entity; use Fleetbase\FleetOps\Models\IntegratedVendor; use Fleetbase\FleetOps\Models\Payload; @@ -11,8 +12,11 @@ use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\ServiceQuoteItem; use Fleetbase\FleetOps\Models\ServiceRate; +use Fleetbase\FleetOps\Models\Vehicle; +use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; +use Fleetbase\LaravelMysqlSpatial\Types\Point as SpatialPoint; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; @@ -168,22 +172,23 @@ function ($query) use ($request) { */ public function queryFromPreliminary(QueryServiceQuotesRequest $request) { - $facilitator = $request->input('facilitator'); - $scheduledAt = $request->input('scheduled_at'); - $service = $request->input('service', 'all'); // the specific service rate to query - defaults to `all` - $serviceType = $request->input('service_type'); // the specific type of service rate to query - $isCashOnDelivery = $request->has('cod'); - $currency = $this->currencyFromRequest($request); - $totalDistance = $request->input('distance'); - $totalTime = $request->input('time'); - $preliminaryData = $this->preliminaryDataFromRequest($request); - $pickup = $preliminaryData['pickup']; - $dropoff = $preliminaryData['dropoff']; - $return = $preliminaryData['return']; - $waypoints = $preliminaryData['waypoints']; - $entities = $preliminaryData['entities']; - $single = $request->boolean('single'); - $isRouteOptimized = $request->boolean('is_route_optimized', true); + $facilitator = $request->input('facilitator'); + $scheduledAt = $request->input('scheduled_at'); + $service = $request->input('service', 'all'); // the specific service rate to query - defaults to `all` + $serviceType = $request->input('service_type'); // the specific type of service rate to query + $isCashOnDelivery = $request->has('cod'); + $currency = $this->currencyFromRequest($request); + $totalDistance = $request->input('distance'); + $totalTime = $request->input('time'); + $preliminaryData = $this->preliminaryDataFromRequest($request); + $pickup = $preliminaryData['pickup']; + $this->availabilityFrom = $this->availabilityPoint($request, $pickup); + $dropoff = $preliminaryData['dropoff']; + $return = $preliminaryData['return']; + $waypoints = $preliminaryData['waypoints']; + $entities = $preliminaryData['entities']; + $single = $request->boolean('single'); + $isRouteOptimized = $request->boolean('is_route_optimized', true); $requestId = $this->generateServiceQuoteRequestId(); $serviceQuotes = []; @@ -439,9 +444,63 @@ protected function serviceQuoteResource(ServiceQuote $serviceQuote) protected function serviceQuoteResourceCollection(iterable $serviceQuotes) { + if ($this->availabilityFrom) { + foreach ($serviceQuotes as $quote) { + $this->addAvailability($quote, $this->availabilityFrom); + } + } + return ServiceQuoteResource::collection($serviceQuotes); } + /** + * Where a rider asked to be picked up, when they asked how soon a car could come (`availability`). + */ + protected ?SpatialPoint $availabilityFrom = null; + + /** + * The pickup to measure availability from, when the request asked for it with coordinates. + */ + protected function availabilityPoint(Request $request, mixed $pickup): ?SpatialPoint + { + return $request->boolean('availability') && is_array($pickup) && Utils::isCoordinates($pickup) ? Utils::getPointFromMixed($pickup) : null; + } + + /** + * Average speed in metres per second used to turn the nearest car's distance into a pickup ETA. + */ + public const PICKUP_SPEED = 7.0; + + /** + * Add the class's seats and how soon its nearest free car could reach the pickup, in seconds. + * Both are null when the company has no such car; the ETA is a straight-line estimate. + */ + protected function addAvailability(ServiceQuote $quote, SpatialPoint $pickup): void + { + $class = data_get($quote, 'serviceRate.service_type'); + $company = $quote->company_uuid; + + $seats = $class ? Vehicle::where('company_uuid', $company)->whereRaw('LOWER(type) = ?', [strtolower($class)])->max('seating_capacity') : null; + + $drivers = Driver::query() + ->withoutGlobalScopes() + ->where(['status' => 'available', 'online' => 1]) + ->whereNull('deleted_at') + ->whereNotNull('location') + ->distanceSphere('location', $pickup, 15000) + ->distanceSphereValue('location', $pickup) + ->orderBy('distance'); + DriverMatching::inCompany($drivers, $company); + DriverMatching::notBusy($drivers); + DriverMatching::forVehicleClass($drivers, $class); + $nearest = $drivers->first(); + + $quote->setMeta([ + 'seats' => $seats ? (int) $seats : null, + 'pickup_eta' => $nearest ? (int) round(60 + (float) $nearest->distance / self::PICKUP_SPEED) : null, + ]); + } + protected function preliminaryDataFromRequest(Request $request): array { return [ diff --git a/server/src/Jobs/ExpireOrderOffer.php b/server/src/Jobs/ExpireOrderOffer.php new file mode 100644 index 000000000..73b0891a1 --- /dev/null +++ b/server/src/Jobs/ExpireOrderOffer.php @@ -0,0 +1,34 @@ +offerUuid)->first(); + + return $offer ? OrderOffers::expire($offer) : false; + } +} diff --git a/server/src/Listeners/HandleOrderDispatched.php b/server/src/Listeners/HandleOrderDispatched.php index 59d2a826b..a03c02e69 100644 --- a/server/src/Listeners/HandleOrderDispatched.php +++ b/server/src/Listeners/HandleOrderDispatched.php @@ -5,9 +5,12 @@ use Fleetbase\FleetOps\Events\OrderDispatched; use Fleetbase\FleetOps\Events\OrderDispatchFailed; use Fleetbase\FleetOps\Models\Driver; +use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Notifications\OrderDispatched as OrderDispatchedNotification; use Fleetbase\FleetOps\Notifications\OrderPing; +use Fleetbase\FleetOps\Support\DriverMatching; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\Utils; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; @@ -26,7 +29,7 @@ class HandleOrderDispatched implements ShouldQueue */ public function handle(OrderDispatched $event) { - /** @var \Fleetbase\FleetOps\Models\Order $order */ + /** @var Order $order */ $order = $event->getModelRecord(); // set company session @@ -62,6 +65,11 @@ public function handle(OrderDispatched $event) /* if order is adhoc ping drivers within radius of pickup to accept order * */ if ($order->adhoc) { + // A config with timed offers goes to one driver at a time instead of everyone nearby. + if ($this->usesTimedOffers($order)) { + return $this->startOffers($order); + } + $order->load(['company']); $pickup = $order->getPickupLocation(); $distance = $order->getAdhocDistance(); @@ -69,7 +77,7 @@ public function handle(OrderDispatched $event) return; } - $drivers = $this->nearbyAvailableDrivers($pickup, $distance); + $drivers = $this->nearbyAvailableDrivers($pickup, $distance, $order); return $drivers->each(function ($driver) use ($order) { try { @@ -110,9 +118,22 @@ protected function getDispatchActivity($order): mixed return $order->config()?->getDispatchActivity(); } - protected function nearbyAvailableDrivers($pickup, int|float $distance) + protected function usesTimedOffers($order): bool { - return Driver::where(['status' => 'available', 'online' => 1]) + return (bool) $order->config()?->usesTimedOffers(); + } + + protected function startOffers($order): mixed + { + return OrderOffers::start($order); + } + + /** + * Drivers to ping for the order: of its company, not on another job, and of its vehicle class. + */ + protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) + { + $query = Driver::where(['status' => 'available', 'online' => 1]) ->whereHas('company', function ($q) { $q->whereHas('users', function ($q) { $q->whereHas('driver', function ($q) { @@ -129,8 +150,13 @@ protected function nearbyAvailableDrivers($pickup, int|float $distance) ') ->distanceSphere('location', $pickup, $distance) ->distanceSphereValue('location', $pickup) - ->withoutGlobalScopes() - ->get(); + ->withoutGlobalScopes(); + + if ($order) { + DriverMatching::forOrder($query, $order); + } + + return $query->get(); } protected function notifyAdhocDriver(Driver $driver, $order): void diff --git a/server/src/Models/Order.php b/server/src/Models/Order.php index 5d5b90a20..14f628269 100644 --- a/server/src/Models/Order.php +++ b/server/src/Models/Order.php @@ -11,9 +11,11 @@ use Fleetbase\FleetOps\Events\OrderDriverUnassigned; use Fleetbase\FleetOps\Flow\Activity; use Fleetbase\FleetOps\Notifications\OrderUnassigned; +use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\LabelPdf; use Fleetbase\FleetOps\Support\NavigatorReview; use Fleetbase\FleetOps\Support\OrderEditPolicy; +use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\OrderTracker; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\FleetOps\Traits\HasTrackingNumber; @@ -1506,6 +1508,14 @@ public function cancelWithReason(?string $reason = null) $this->status = $canceledActivity->code ?? 'canceled'; $this->updateActivity($canceledActivity); + // The driver is free for other work, and nobody else is offered a canceled order. + if ($this->driver_assigned_uuid) { + Driver::withoutGlobalScopes()->where(['uuid' => $this->driver_assigned_uuid, 'current_job_uuid' => $this->uuid])->update(['current_job_uuid' => null]); + } + if ($orderConfig->usesTimedOffers()) { + OrderOffers::withdraw($this); + } + if ($this->isIntegratedVendorOrder()) { $api = $this->facilitator->api(); @@ -2334,9 +2344,9 @@ public function findClosestDrivers(int $distance = 6000): Collection ') ->distanceSphere('location', $pickup, $distance) ->distanceSphereValue('location', $pickup) - ->withoutGlobalScopes() - ->get(); + ->withoutGlobalScopes(); - return $drivers; + // Only this order's company, and not drivers already on another job. + return DriverMatching::forOrder($drivers, $this)->get(); } } diff --git a/server/src/Models/OrderConfig.php b/server/src/Models/OrderConfig.php index 32d074d30..a7cc181dc 100644 --- a/server/src/Models/OrderConfig.php +++ b/server/src/Models/OrderConfig.php @@ -442,6 +442,23 @@ public function allowsDispatch(): bool return !in_array($dispatch, [false, 'false', 0, '0'], true); } + /** + * Whether orders using this config are offered to one driver at a time (`meta.offers.enabled`) + * rather than pinged to every nearby driver at once. + */ + public function usesTimedOffers(): bool + { + return (bool) data_get($this->meta, 'offers.enabled', false); + } + + /** + * Seconds a driver has to accept an offer (`meta.offers.timeout`), from 10 to 120, default 20. + */ + public function offerTimeout(): int + { + return max(10, min(120, (int) data_get($this->meta, 'offers.timeout', 20))); + } + /** * Determines if activity updates must follow the configured flow graph. */ diff --git a/server/src/Models/OrderOffer.php b/server/src/Models/OrderOffer.php new file mode 100644 index 000000000..094a035e8 --- /dev/null +++ b/server/src/Models/OrderOffer.php @@ -0,0 +1,41 @@ + 'integer', + 'expires_at' => 'datetime', + 'responded_at' => 'datetime', + ]; + + public function order() + { + return $this->belongsTo(Order::class, 'order_uuid', 'uuid')->withoutGlobalScopes(); + } + + public function driver() + { + return $this->belongsTo(Driver::class, 'driver_uuid', 'uuid')->withoutGlobalScopes(); + } +} diff --git a/server/src/Providers/FleetOpsServiceProvider.php b/server/src/Providers/FleetOpsServiceProvider.php index 8633f4730..e037b2723 100644 --- a/server/src/Providers/FleetOpsServiceProvider.php +++ b/server/src/Providers/FleetOpsServiceProvider.php @@ -58,6 +58,7 @@ class FleetOpsServiceProvider extends CoreServiceProvider public $commands = [ \Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, \Fleetbase\FleetOps\Console\Commands\DispatchOrders::class, + \Fleetbase\FleetOps\Console\Commands\CreateRideConfig::class, \Fleetbase\FleetOps\Console\Commands\TrackOrderDistanceAndTime::class, \Fleetbase\FleetOps\Console\Commands\FixDriverCompanies::class, \Fleetbase\FleetOps\Console\Commands\FixCustomerCompanies::class, diff --git a/server/src/Support/DriverMatching.php b/server/src/Support/DriverMatching.php new file mode 100644 index 000000000..421107baa --- /dev/null +++ b/server/src/Support/DriverMatching.php @@ -0,0 +1,82 @@ +company_uuid); + static::notBusy($query); + + return static::forVehicleClass($query, static::vehicleClass($order)); + } + + /** + * Drivers of the company, directly or through their user. + */ + public static function inCompany(Builder $query, ?string $companyUuid): Builder + { + return $query->where(function ($query) use ($companyUuid) { + $query->where($query->getModel()->getTable() . '.company_uuid', $companyUuid) + ->orWhereHas('user', fn ($query) => $query->where('company_uuid', $companyUuid)); + }); + } + + /** + * Drivers with no current job, or whose current job has finished. A job left behind by an + * order that ended without clearing it doesn't keep the driver busy. + */ + public static function notBusy(Builder $query): Builder + { + $drivers = $query->getModel()->getTable(); + + return $query->where(function ($query) use ($drivers) { + $query->whereNull($drivers . '.current_job_uuid') + ->orWhereNotExists(function ($jobs) use ($drivers) { + $jobs->selectRaw('1') + ->from('orders') + ->whereColumn('orders.uuid', $drivers . '.current_job_uuid') + ->whereNull('orders.deleted_at') + ->whereNotIn('orders.status', self::FREE_JOB_STATUSES); + }); + }); + } + + /** + * Drivers whose vehicle is of the class, compared without case. No class matches everyone. + */ + public static function forVehicleClass(Builder $query, ?string $class): Builder + { + if ($class === null || trim($class) === '') { + return $query; + } + + return $query->whereHas('vehicle', fn ($query) => $query->whereRaw('LOWER(type) = ?', [strtolower(trim($class))])); + } + + /** + * The vehicle class booked for the order, if any. + */ + public static function vehicleClass(Order $order): ?string + { + $class = data_get($order->meta, 'vehicle_class'); + + return is_string($class) && trim($class) !== '' ? trim($class) : null; + } +} diff --git a/server/src/Support/FleetOps.php b/server/src/Support/FleetOps.php index a4593dc31..0510a4289 100644 --- a/server/src/Support/FleetOps.php +++ b/server/src/Support/FleetOps.php @@ -139,4 +139,79 @@ private static function transportConfigDefaults(): array ], ]; } + + /** + * Creates or retrieves the ride config for a company: a rider's trip from request to drop-off. + * + * The driver accepting starts the order ("on the way"), then arrives, starts the trip and + * completes it, or records a no-show. Transitions are strict, and the order is offered to + * one driver at a time. + */ + public static function createRideConfig(Company $company): OrderConfig + { + return OrderConfig::firstOrCreate( + [ + 'company_uuid' => $company->uuid, + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + ], + static::rideConfigDefaults() + ); + } + + /** + * The ride flow, keyed by activity code. + */ + public static function rideConfigDefaults(): array + { + $activity = fn (string $code, string $status, string $details, array $next, bool $complete = false) => [ + 'key' => $code, + 'code' => $code, + 'color' => '#1f2937', + 'logic' => [], + 'events' => [], + 'status' => $status, + 'actions' => [], + 'details' => $details, + 'options' => [], + 'complete' => $complete, + 'entities' => [], + 'sequence' => 0, + 'activities' => $next, + 'internalId' => (string) Str::uuid(), + 'pod_method' => 'scan', + 'require_pod' => false, + ]; + + return [ + 'name' => 'Ride', + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + 'description' => 'A rider\'s trip, from request to drop-off', + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + 'tags' => ['ride', 'passenger'], + 'entities' => [], + 'meta' => [ + 'lifecycle' => [ + 'initial' => 'created', + 'completed' => 'completed', + 'canceled' => 'canceled', + 'terminal' => ['no_show'], + 'strict_transitions' => true, + ], + 'offers' => ['enabled' => true, 'timeout' => 20], + ], + 'flow' => [ + 'created' => $activity('created', 'Ride requested', 'The rider requested a ride.', ['dispatched']), + 'dispatched' => $activity('dispatched', 'Finding a driver', 'Looking for a driver nearby.', ['started']), + 'started' => $activity('started', 'Driver on the way', 'The driver accepted and is on the way to the pickup.', ['arrived']), + 'arrived' => $activity('arrived', 'Driver has arrived', 'The driver is waiting at the pickup.', ['in_progress', 'no_show']), + 'in_progress' => $activity('in_progress', 'Trip in progress', 'The rider is on board.', ['completed']), + 'completed' => $activity('completed', 'Trip completed', 'The rider was dropped off.', [], true), + 'no_show' => $activity('no_show', 'Rider didn\'t show', 'The rider didn\'t come to the pickup.', []), + ], + ]; + } } diff --git a/server/src/Support/OrderOffers.php b/server/src/Support/OrderOffers.php new file mode 100644 index 000000000..99ffdd79f --- /dev/null +++ b/server/src/Support/OrderOffers.php @@ -0,0 +1,170 @@ +uuid)->exists()) { + return static::pending($order); + } + + return static::offerNext($order); + } + + /** + * The order's open offer, if any. + */ + public static function pending(Order $order): ?OrderOffer + { + return OrderOffer::where('order_uuid', $order->uuid)->where('status', OrderOffer::PENDING)->latest('id')->first(); + } + + /** + * Accept the driver's open offer. False when it isn't theirs or has run out. + */ + public static function accept(Order $order, Driver $driver): bool + { + return OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->where('expires_at', '>', now()) + ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]) > 0; + } + + /** + * The driver turns the offer down, so the next driver gets it. False when they had no open offer. + */ + public static function decline(Order $order, Driver $driver): bool + { + $declined = OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::DECLINED, 'responded_at' => now()]) > 0; + + if ($declined) { + static::offerNext($order); + } + + return $declined; + } + + /** + * Close an offer that has run out and offer the order to the next driver. + */ + public static function expire(OrderOffer $offer): bool + { + $expired = OrderOffer::where('uuid', $offer->uuid) + ->where('status', OrderOffer::PENDING) + ->where('expires_at', '<=', now()) + ->update(['status' => OrderOffer::EXPIRED, 'responded_at' => now()]) > 0; + + if ($expired && ($order = Order::withoutGlobalScopes()->where('uuid', $offer->order_uuid)->first())) { + static::offerNext($order); + } + + return $expired; + } + + /** + * Close the order's open offer without moving on, for an order that was canceled or assigned. + */ + public static function withdraw(Order $order): int + { + return OrderOffer::where('order_uuid', $order->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::WITHDRAWN, 'responded_at' => now()]); + } + + /** + * Offer the order to the nearest driver who hasn't had it yet. + */ + public static function offerNext(Order $order): ?OrderOffer + { + $order->refresh(); + if ($order->started || $order->driver_assigned_uuid || in_array($order->status, ['completed', 'canceled'], true)) { + return null; + } + + $pickup = $order->getPickupLocation(); + $driver = Utils::isPoint($pickup) ? static::candidates($order, $pickup)->first() : null; + if (!$driver) { + static::noDriverFound($order); + + return null; + } + + $timeout = $order->config()->offerTimeout(); + $offer = OrderOffer::create([ + 'company_uuid' => $order->company_uuid, + 'order_uuid' => $order->uuid, + 'driver_uuid' => $driver->uuid, + 'status' => OrderOffer::PENDING, + 'distance' => isset($driver->distance) ? (int) round((float) $driver->distance) : null, + 'expires_at' => now()->addSeconds($timeout), + ]); + + try { + $driver->notify(new OrderPing($order, $offer->distance)); + } catch (\Throwable $exception) { + Log::warning('Unable to send a ride offer', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + } + + ExpireOrderOffer::dispatch($offer->uuid)->delay(now()->addSeconds($timeout + 1)); + + return $offer; + } + + /** + * Online, free drivers of the order's company and class within the order's radius who + * haven't been offered it, nearest first. + */ + public static function candidates(Order $order, $pickup): Builder + { + $offered = OrderOffer::where('order_uuid', $order->uuid)->pluck('driver_uuid')->all(); + $query = Driver::query() + ->withoutGlobalScopes() + ->where(['status' => 'available', 'online' => 1]) + ->whereNull('deleted_at') + ->whereNotIn('uuid', $offered) + ->whereNotNull('location') + ->whereRaw('ST_Y(location) BETWEEN -90 AND 90 AND ST_X(location) BETWEEN -180 AND 180 AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0)') + ->distanceSphere('location', $pickup, $order->getAdhocPingDistance()) + ->distanceSphereValue('location', $pickup) + ->orderBy('distance'); + + NavigatorReview::excludeFrom($query); + + return DriverMatching::forOrder($query, $order); + } + + /** + * Nobody is left to offer the order to, so cancel it and say why. + */ + public static function noDriverFound(Order $order): void + { + $order->updateMeta('dispatch_outcome', 'no_driver_found'); + $order->cancelWithReason(self::NO_DRIVER_FOUND); + } +} diff --git a/server/src/Support/SocketChannels.php b/server/src/Support/SocketChannels.php index d7cd9860a..c51ffa88d 100644 --- a/server/src/Support/SocketChannels.php +++ b/server/src/Support/SocketChannels.php @@ -213,18 +213,12 @@ public static function narrowOrder(SocketPrincipal $principal, Model $order): bo } /** - * Drivers: a driver only themselves; a customer the driver of one of their active orders. + * Drivers: a driver only themselves. Never a customer, because the driver's location events + * carry their phone number; riders follow the car through their order instead. */ public static function narrowDriver(SocketPrincipal $principal, Model $driver): bool { - if ($principal->kind === 'driver') { - return static::isSelf($principal, $driver->uuid); - } - - return $principal->kind === 'customer' - && static::activeCustomerOrders($principal, $driver->getConnectionName()) - ->where('driver_assigned_uuid', $driver->uuid) - ->exists(); + return $principal->kind === 'driver' && static::isSelf($principal, $driver->uuid); } /** diff --git a/server/tests/CommandContractsTest.php b/server/tests/CommandContractsTest.php index f6d14ca32..592c01998 100644 --- a/server/tests/CommandContractsTest.php +++ b/server/tests/CommandContractsTest.php @@ -355,6 +355,16 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista return $this->drivers; } + protected function usesTimedOffers(Order $order): bool + { + return false; + } + + protected function markPinged(Order $order): void + { + $order->dispatchedForPing = true; + } + public function info($string, $verbosity = null) { $this->messages[] = ['info', $string]; @@ -414,6 +424,13 @@ protected function newDriverQuery() { return $this->driverQuery; } + + protected function matchDrivers($driverQuery, Order $order) + { + $driverQuery->calls[] = ['matchDrivers', $order->company_uuid]; + + return $driverQuery; + } } class FleetOpsDispatchAdhocOrdersBuilderFake diff --git a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php index 5309ffca3..3e29542a8 100644 --- a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php @@ -169,6 +169,7 @@ public function __call($method, $arguments) 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'name', 'plate_number', 'location', 'online'], 'contacts' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'email', 'phone'], 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name', 'email', 'phone'], + 'order_offers' => ['uuid', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { @@ -661,3 +662,159 @@ public function __call($method, $arguments) // The entity receives its own tracking status alongside the order expect($connection->table('tracking_statuses')->where('tracking_number_uuid', 'tn-entity-1')->count())->toBeGreaterThanOrEqual(1); }); + +function fleetopsOrderStartRide(SQLiteConnection $connection, array $order = []): void +{ + $defaults = Fleetbase\FleetOps\Support\FleetOps::rideConfigDefaults(); + $connection->table('order_configs')->insert([ + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + 'flow' => json_encode($defaults['flow']), + 'meta' => json_encode($defaults['meta']), + ]); + fleetopsOrderStartSeedOrder($connection, array_merge(['order_config_uuid' => 'config-ride', 'type' => 'ride', 'adhoc' => 1, 'status' => 'dispatched', 'dispatched' => 1, 'dispatched_at' => '2026-11-06 09:00:00'], $order)); + $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => 1]); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-dispatched', 'company_uuid' => 'company-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED', 'status' => 'Finding a driver']); + // Declining looks for the next driver, nearest first. + $connection->getPdo()->sqliteCreateFunction('st_distance_sphere', fn ($a, $b) => 100.0); + $connection->getPdo()->sqliteCreateFunction('ST_X', fn ($value) => 0.5); + $connection->getPdo()->sqliteCreateFunction('ST_Y', fn ($value) => 0.5); + $connection->table('users')->insert(['uuid' => 'user-2', 'company_uuid' => 'company-2', 'name' => 'Rival']); + $connection->table('drivers')->insert([ + ['uuid' => 'driver-2', 'public_id' => 'driver_two', 'company_uuid' => 'company-1', 'user_uuid' => null, 'online' => 1], + ['uuid' => 'driver-3', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'user_uuid' => 'user-2', 'online' => 1], + ['uuid' => 'driver-4', 'public_id' => 'driver_sleepy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'online' => 0], + ]); +} + +function fleetopsOrderStartOffer(SQLiteConnection $connection, string $driverUuid, string $expiresAt = '2099-01-01 00:00:00'): void +{ + $connection->table('order_offers')->insert(['uuid' => 'offer-' . $driverUuid, 'company_uuid' => 'company-1', 'order_uuid' => 'order-1', 'driver_uuid' => $driverUuid, 'status' => 'pending', 'expires_at' => $expiresAt]); +} + +test('accepting an adhoc ride refuses unknown, foreign, offline and impersonated drivers', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + $controller = new OrderController(); + $accept = fn (string $driver) => $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => $driver])); + + expect($accept('driver_missing')->getStatusCode())->toBe(404) + ->and($accept('driver_rival')->getStatusCode())->toBe(404) + ->and($accept('driver_sleepy')->getStatusCode())->toBe(422); + + // Signed in as Driver One, nobody accepts for someone else. + session(['user' => 'user-1']); + $impersonated = $accept('driver_two'); + session(['user' => null]); + + expect($impersonated->getStatusCode())->toBe(403) + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBeNull(); +}); + +test('a ride with timed offers can only be accepted by the driver it is offered to', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + fleetopsOrderStartOffer($connection, 'driver-1'); + $controller = new OrderController(); + + $notOffered = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_two'])); + $offered = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + + expect($notOffered->getStatusCode())->toBe(409) + ->and($notOffered->getData(true)['error'])->toContain('no longer offered') + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBe('driver-1') + ->and($connection->table('orders')->value('started'))->toBe(1) + ->and($connection->table('order_offers')->where('driver_uuid', 'driver-1')->value('status'))->toBe('accepted'); +}); + +test('of two drivers accepting the same adhoc order only the first gets it', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['meta' => json_encode([])]); + // Someone else claimed it after this request loaded the order. + $connection->table('orders')->update(['driver_assigned_uuid' => 'driver-2']); + + $order = Order::where('uuid', 'order-1')->first(); + $order->driver_assigned_uuid = null; + $order->syncOriginal(); + $refusal = (new class extends OrderController { + public function claim(Order $order, string $driver) + { + return $this->claimAdhocOrder($order, $driver); + } + })->claim($order, 'driver_one'); + + expect($refusal->getStatusCode())->toBe(409) + ->and($refusal->getData(true)['error'])->toContain('taken by another driver') + ->and($connection->table('orders')->value('driver_assigned_uuid'))->toBe('driver-2'); +}); + +test('the driver already holding an adhoc order passes, and a canceled order refuses everyone', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['meta' => json_encode([])]); + $controller = new OrderController(); + + $held = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + expect($connection->table('orders')->value('started'))->toBe(1); + + $connection->table('orders')->update(['started' => 0, 'status' => 'canceled']); + $canceled = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); + + expect($canceled->getStatusCode())->toBe(409) + ->and($canceled->getData(true)['error'])->toContain('canceled'); +}); + +test('a driver declines the ride offered to them, signed in or named', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection); + fleetopsOrderStartOffer($connection, 'driver-1'); + $connection->table('order_offers')->insert(['uuid' => 'offer-2', 'company_uuid' => 'company-1', 'order_uuid' => 'order-1', 'driver_uuid' => 'driver-2', 'status' => 'declined', 'expires_at' => '2099-01-01 00:00:00']); + $controller = new OrderController(); + + $missing = $controller->declineOrder('order_missing', Request::create('/x', 'POST')); + $nobody = $controller->declineOrder('order_start', Request::create('/x', 'POST')); + $rival = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_rival'])); + $named = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_two'])); + + session(['user' => 'user-1']); + $declined = $controller->declineOrder('order_start', Request::create('/x', 'POST', ['driver' => 'driver_two'])); + session(['user' => null]); + + expect($missing->getStatusCode())->toBe(404) + ->and($nobody->getStatusCode())->toBe(404) + ->and($rival->getStatusCode())->toBe(404) + ->and($named->getStatusCode())->toBe(409) + ->and($declined->getData(true))->toBe(['status' => 'declined', 'order' => 'order_start']) + ->and($connection->table('order_offers')->where('uuid', 'offer-driver-1')->value('status'))->toBe('declined') + // Nobody else has a position, so the ride ends as no driver found. + ->and($connection->table('orders')->value('status'))->toBe('canceled'); +}); + +test('a strict ride flow refuses skipped steps and uses the configured activity', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['status' => 'arrived', 'started' => 1, 'driver_assigned_uuid' => 'driver-1']); + $controller = new OrderController(); + + $skipped = $controller->updateActivity('order_start', Request::create('/x', 'POST', ['activity' => ['code' => 'completed']])); + $onBoard = $controller->updateActivity('order_start', Request::create('/x', 'POST', ['activity' => ['code' => 'in_progress', 'status' => 'Anything the client says']])); + + expect($skipped->getStatusCode())->toBe(422) + ->and($connection->table('orders')->value('status'))->toBe('in_progress') + ->and($connection->table('tracking_statuses')->where('code', 'IN_PROGRESS')->value('status'))->toBe('Trip in progress'); +}); + +test('canceling a ride frees its driver and withdraws the open offer', function () { + $connection = fleetopsOrderStartBoot(); + fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); + fleetopsOrderStartOffer($connection, 'driver-2'); + $connection->table('drivers')->where('uuid', 'driver-1')->update(['current_job_uuid' => 'order-1']); + + Order::where('uuid', 'order-1')->first()->cancelWithReason('Rider changed their mind'); + + expect($connection->table('drivers')->where('uuid', 'driver-1')->value('current_job_uuid'))->toBeNull() + ->and($connection->table('order_offers')->value('status'))->toBe('withdrawn') + ->and($connection->table('orders')->value('status'))->toBe('canceled'); +}); diff --git a/server/tests/OrderDispatchListenerContractsTest.php b/server/tests/OrderDispatchListenerContractsTest.php index c8f5f6424..bd05cb988 100644 --- a/server/tests/OrderDispatchListenerContractsTest.php +++ b/server/tests/OrderDispatchListenerContractsTest.php @@ -244,7 +244,12 @@ protected function getDispatchActivity($order): mixed return $order->dispatchActivity; } - protected function nearbyAvailableDrivers($pickup, int|float $distance) + protected function usesTimedOffers($order): bool + { + return false; + } + + protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) { $this->nearbyQueries[] = [(string) $pickup, $distance]; diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php index 49d6a7721..0436f210d 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php @@ -119,7 +119,12 @@ protected function findAssignedDriver($order): ?Driver return $this->assignedDriver; } - protected function nearbyAvailableDrivers($pickup, int|float $distance) + protected function usesTimedOffers($order): bool + { + return false; + } + + protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) { return collect([ new FleetOpsConcreteDriverForDispatch(), diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php index 7e9d8b32c..8a0a2ad0d 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php @@ -92,7 +92,7 @@ public function __call($method, $arguments) 'orders' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'adhoc', 'dispatched', 'dispatched_at', 'payload_uuid', 'meta', 'type'], 'tracking_statuses' => ['uuid', 'company_uuid', 'code', 'tracking_number_uuid', 'status', 'details'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'owner_type', 'status_uuid', 'type'], - 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'meta'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'meta', 'current_job_uuid'], 'companies' => ['uuid', 'public_id', 'name'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'phone', 'email'], @@ -157,6 +157,13 @@ public function __call($method, $arguments) expect($drivers)->toHaveCount(1) ->and($drivers->first()->uuid)->toBe('driver-1'); + // For an order, only its own company's drivers who aren't on another job + $own = Order::where('uuid', 'order-1')->withoutGlobalScopes()->first(); + $other = new Order(); + $other->setRawAttributes(['uuid' => 'order-x', 'company_uuid' => 'company-2'], true); + expect($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000, $own))->toHaveCount(1) + ->and($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000, $other))->toHaveCount(0); + // Offline drivers are excluded $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => '0']); expect($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000))->toHaveCount(0); diff --git a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php index c7afe1b6d..5a754f4fe 100644 --- a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php +++ b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php @@ -59,7 +59,7 @@ public function __call($method, $arguments) 'service_quotes' => ['uuid', 'public_id', 'request_id', 'company_uuid', 'payload_uuid', 'service_rate_uuid', 'amount', 'currency', 'meta', 'expired_at', '_key'], 'transactions' => ['uuid', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'subject_uuid', 'subject_type', 'context_uuid', 'context_type', 'gateway_transaction_id', 'gateway', 'amount', 'currency', 'description', 'type', 'direction', 'status', 'settlement_status', 'voided_at', 'meta', '_key'], 'companies' => ['uuid', 'public_id', 'name', 'currency', 'country'], - 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'status', 'online', 'location'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'status', 'online', 'location', 'current_job_uuid', 'vehicle_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta'], @@ -174,6 +174,10 @@ function fleetopsOrderPurchaseOrder(): Order $connection->table('users')->insert(['uuid' => 'user-1', 'company_uuid' => 'company-1']); $connection->table('company_users')->insert(['uuid' => 'cu-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1']); $connection->table('drivers')->insert(['uuid' => 'driver-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); + // On another company's books, or busy with an order still under way: neither is offered this one. + $connection->table('drivers')->insert(['uuid' => 'driver-other', 'company_uuid' => 'company-2', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); + $connection->table('drivers')->insert(['uuid' => 'driver-busy', 'company_uuid' => 'company-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)', 'current_job_uuid' => 'order-busy']); + $connection->table('orders')->insert(['uuid' => 'order-busy', 'company_uuid' => 'company-1', 'status' => 'started']); $order = fleetopsOrderPurchaseOrder(); $pickup = new Place(); diff --git a/server/tests/Unit/Support/SocketChannelsTest.php b/server/tests/Unit/Support/SocketChannelsTest.php index ee392fbcc..a2c99dda2 100644 --- a/server/tests/Unit/Support/SocketChannelsTest.php +++ b/server/tests/Unit/Support/SocketChannelsTest.php @@ -292,7 +292,7 @@ function socketChannelsCustomer(): SocketPrincipal expect(socketChannelsAllows($walker, 'vehicle.vehicles-a'))->toBeFalse(); }); -test('a customer reaches their own orders and the driver and vehicle of their active orders', function () { +test('a customer reaches their own orders and the vehicle of their active orders, never a driver', function () { socketChannelsBoot(); $customer = socketChannelsCustomer(); @@ -302,10 +302,10 @@ function socketChannelsCustomer(): SocketPrincipal ->and(socketChannelsAllows($customer, 'order.order-a2'))->toBeFalse() ->and(socketChannelsAllows($customer, 'order.orders-b'))->toBeFalse(); - // driver-a1 drives an active order of theirs; driver-a2 only a completed one. - expect(socketChannelsAllows($customer, 'driver.driver-a1'))->toBeTrue() - ->and(socketChannelsAllows($customer, 'driverAssigned.driver_a1'))->toBeTrue() - ->and(socketChannelsAllows($customer, 'driver.driver-a3'))->toBeTrue() + // Not even the driver of an active order of theirs: driver events carry the driver's phone. + expect(socketChannelsAllows($customer, 'driver.driver-a1'))->toBeFalse() + ->and(socketChannelsAllows($customer, 'driverAssigned.driver_a1'))->toBeFalse() + ->and(socketChannelsAllows($customer, 'driver.driver-a3'))->toBeFalse() ->and(socketChannelsAllows($customer, 'driver.driver-a2'))->toBeFalse(); // vehicle-a1 is assigned to an active order; vehicle-a3 is driven by an active order's driver. From f49a296f7eeda8929e20f5f402476e59ca60e4a4 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 10:37:46 +0800 Subject: [PATCH 13/29] feat(customers): ride chat, ratings, sharing, push, final fare and account deletion - Rides: a rider's order on a config with timed offers is adhoc, needs a fare, and takes its vehicle class from the fare. Server-set meta keys can't come from the rider. - Chat: `customers/orders/{id}/messages` reads and sends messages with the ride's driver, as the rider. The channel is a core chat channel that Navigator shows as the order's customer thread. - Ratings: `customers/orders/{id}/rating` rates the driver of a finished ride once. The driver's average is kept on the driver and returned with the ride's driver. - Sharing: `customers/orders/{id}/share` returns a signed tracking link. The tracking page redeems it (`public/track/{number}/share`) for the rider's live view, without a code. - Push: riders get a push to their own devices at each step of a ride and when the car is about to arrive. No Storefront or company notification setting is needed. - Final fare: a completed ride is priced again from its car's positions and the trip time, through the rate the rider booked. The breakdown is kept on the order and bought as the order's price. - A rider can't book while a card trip is unpaid (`meta.paid_at`, set by Ledger). - `customers/ride-settings` returns the operator's emergency number and support contacts, set with `fleetops:create-ride-config`. - `DELETE customers/me` deletes the rider's account, unless they have a ride under way. --- addon/components/tracking-page.js | 10 + .../Controllers/Api/v1/CustomerController.php | 231 +++- .../Controllers/Api/v1/DriverController.php | 4 + .../Controllers/Public/TrackingController.php | 19 + server/src/Notifications/RideUpdate.php | 81 ++ server/src/Observers/OrderObserver.php | 11 + server/src/Support/Rides/DriverRatings.php | 62 + server/src/Support/Rides/FinalFare.php | 143 +++ server/src/Support/Rides/RideChat.php | 115 ++ server/src/Support/Rides/RideUpdates.php | 80 ++ .../Support/TrackingPage/TrackingShare.php | 40 + server/src/routes.php | 8 + .../ApiCustomerControllerContractsTest.php | 66 +- .../Http/Public/TrackingControllerTest.php | 42 +- server/tests/Feature/RidesTest.php | 1017 +++++++++++++++++ 15 files changed, 1914 insertions(+), 15 deletions(-) create mode 100644 server/src/Notifications/RideUpdate.php create mode 100644 server/src/Support/Rides/DriverRatings.php create mode 100644 server/src/Support/Rides/FinalFare.php create mode 100644 server/src/Support/Rides/RideChat.php create mode 100644 server/src/Support/Rides/RideUpdates.php create mode 100644 server/src/Support/TrackingPage/TrackingShare.php create mode 100644 server/tests/Feature/RidesTest.php diff --git a/addon/components/tracking-page.js b/addon/components/tracking-page.js index 6b8f70d75..27ce9acc6 100644 --- a/addon/components/tracking-page.js +++ b/addon/components/tracking-page.js @@ -170,6 +170,16 @@ export default class TrackingPageComponent extends Component { return; } + // A rider's shared link opens their live view on this device first. + const share = this.urlSearchParams.get('share'); + if (this.trackingInput && share) { + try { + yield this.fetch.post(`track/${encodeURIComponent(this.trackingInput)}/share${this.queryString()}`, { token: share }, REQUEST_OPTIONS); + } catch { + // An expired or broken link falls back to the public view. + } + } + if (this.trackingInput) { yield this.lookup.perform(this.trackingInput, { quiet: true }); } else { diff --git a/server/src/Http/Controllers/Api/v1/CustomerController.php b/server/src/Http/Controllers/Api/v1/CustomerController.php index fcedd9454..2c236326c 100644 --- a/server/src/Http/Controllers/Api/v1/CustomerController.php +++ b/server/src/Http/Controllers/Api/v1/CustomerController.php @@ -19,6 +19,11 @@ use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Support\CustomerAuth; use Fleetbase\FleetOps\Support\PlaceSearch; +use Fleetbase\FleetOps\Support\Rides\DriverRatings; +use Fleetbase\FleetOps\Support\Rides\RideChat; +use Fleetbase\FleetOps\Support\TrackingCode; +use Fleetbase\FleetOps\Support\TrackingPage\TrackingShare; +use Fleetbase\FleetOps\Support\TrackingScope; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; use Fleetbase\LaravelMysqlSpatial\Types\Point as SpatialPoint; @@ -28,6 +33,7 @@ use Fleetbase\Models\VerificationCode; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; use Symfony\Component\HttpFoundation\Response; @@ -54,6 +60,11 @@ class CustomerController extends Controller */ protected const RIDER_ORDER_RELATIONS = ['payload', 'payload.pickup', 'payload.dropoff']; + /** + * Order meta the server sets and a rider may not send. + */ + protected const RESERVED_ORDER_META = ['vehicle_class', 'service_name', 'dispatch_outcome', 'fare', 'rating', 'chat_channel', 'paid_at']; + /** * Wrong guesses a single code tolerates before it locks itself (core's check()). */ @@ -691,6 +702,30 @@ public function updateMe(UpdateContactRequest $request) return $this->customerResource($customer->fresh()); } + /** + * Delete the rider's account: sign them out everywhere, delete their saved places and remove + * their name and contact details. Their past trips stay on the operator's books without them. + */ + public function deleteMe() + { + $customer = $this->currentCustomer(); + if (!$customer) { + return response()->apiError('Not authenticated.', 401); + } + + if ($this->hasActiveRide($customer)) { + return response()->apiError('Finish or cancel your ride before deleting your account.', 422); + } + + $user = $customer->user_uuid ? $this->findUserByUuid($customer->user_uuid) : null; + if ($user) { + $this->deleteUserTokens($user); + } + $this->eraseCustomer($customer, $user); + + return response()->json(['status' => 'deleted']); + } + /** * Revoke the Customer-Token used on this request. */ @@ -807,6 +842,22 @@ public function createOrder(CreateCustomerOrderRequest $request) return response()->apiError('This fare has expired. Please get a new one.', 422); } + // A ride is priced and matched by the class the rider picked, so it needs a fare. + $isRide = $orderConfig->usesTimedOffers(); + if ($isRide && !$serviceQuote instanceof ServiceQuote) { + return response()->apiError('Choose a ride option first.', 422); + } + if ($isRide && $this->hasUnpaidRide($customer)) { + return response()->apiError('Pay for your last trip before you book another.', 402); + } + + // Keys the server sets can't come from the rider. + $meta = Arr::except((array) $request->input('meta', []), static::RESERVED_ORDER_META); + if ($isRide) { + $meta['vehicle_class'] = $serviceQuote->serviceRate?->service_type; + $meta['service_name'] = $serviceQuote->serviceRate?->service_name; + } + // Build the Payload (matching the operator OrderController convention). // - `payload` may be an array of {pickup, dropoff, return, waypoints, entities} // - `payload` may be a string public_id referencing an existing Payload @@ -838,7 +889,8 @@ public function createOrder(CreateCustomerOrderRequest $request) 'scheduled_at' => $request->input('scheduled_at'), 'notes' => $request->input('notes'), 'internal_id' => $request->input('internal_id'), - 'meta' => (array) $request->input('meta', []), + 'adhoc' => $isRide, + 'meta' => $meta, ]); // If the customer picked a ServiceQuote up front, consume it now to @@ -1095,7 +1147,7 @@ public function cancelOrder(string $id, Request $request) return response()->apiError('Order not found.', 404); } - if (in_array($order->status, ['completed', 'canceled'], true)) { + if (in_array($order->status, ['completed', 'canceled'], true) || $order->config()->isTerminalActivityCode($order->status)) { return response()->apiError('This order can no longer be canceled.', 422); } @@ -1127,7 +1179,7 @@ public function orderDriver(string $id) } return response()->json([ - 'driver' => ['name' => $driver->name, 'photo_url' => $driver->photo_url, 'location' => $driver->location], + 'driver' => ['name' => $driver->name, 'photo_url' => $driver->photo_url, 'location' => $driver->location, 'rating' => DriverRatings::average($driver)], 'vehicle' => $vehicle ? [ 'make' => $vehicle->make, 'model' => $vehicle->model, @@ -1171,6 +1223,116 @@ public function orderEta(string $id, Request $request) } } + /** + * The chat with the driver of one of the rider's rides, oldest message first. Empty until a + * driver accepts. + */ + public function orderMessages(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $channel = $this->rideChannel($order); + + return response()->json($channel ? RideChat::messages($channel, $this->currentCustomer()->user_uuid)->all() : []); + } + + /** + * Send the driver a message. The rider always writes as themselves. + */ + public function sendOrderMessage(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $text = trim((string) $request->input('text')); + if ($text === '' || mb_strlen($text) > 2000) { + return response()->apiError('Write a message of up to 2000 characters.', 422); + } + if ($this->rideHasEnded($order)) { + return response()->apiError('This ride has ended.', 422); + } + + $channel = $this->rideChannel($order); + if (!$channel) { + return response()->apiError('You can message your driver once they accept.', 422); + } + + $riderUser = $this->currentCustomer()->user_uuid; + $message = RideChat::send($channel, $riderUser, $text); + + return response()->json(RideChat::messages($channel, $riderUser)->firstWhere('id', $message->public_id ?? $message->uuid), 201); + } + + /** + * Rate the driver of a finished ride, once. + */ + public function rateOrder(string $id, Request $request) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $stars = $request->input('stars'); + if (!is_numeric($stars) || (int) $stars != $stars || $stars < 1 || $stars > 5) { + return response()->apiError('Rate from 1 to 5 stars.', 422); + } + if ($order->status !== 'completed' || !$order->driver_assigned_uuid) { + return response()->apiError('Only a finished ride can be rated.', 422); + } + + $comment = $request->input('comment'); + if (!DriverRatings::rate($order, (int) $stars, is_string($comment) ? Str::limit($comment, 1000, '') : null)) { + return response()->apiError('You already rated this ride.', 409); + } + + return response()->json(['status' => 'rated']); + } + + /** + * A link the rider can send to someone they trust to follow the ride live, without a code. + */ + public function shareOrder(string $id) + { + $order = $this->ownedOrder($id); + if (!$order) { + return response()->apiError('Order not found.', 404); + } + + $number = data_get($order, 'trackingNumber.tracking_number'); + if (!$number || $this->rideHasEnded($order)) { + return response()->apiError('This ride can no longer be shared.', 422); + } + + $scope = TrackingScope::forCustomer($order, $this->currentCustomer()); + $expiresAt = now()->addHours(TrackingShare::HOURS); + $url = $this->trackingPageUrl($number, $order->company_uuid); + + return response()->json([ + 'url' => $url . (str_contains($url, '?') ? '&' : '?') . 'share=' . TrackingShare::token($scope->order_uuid, $scope->customer_uuid, $expiresAt), + 'expires_at' => $expiresAt->toISOString(), + ]); + } + + /** + * What the rider app shows from the operator's ride settings: the emergency number and support contacts. + */ + public function rideSettings() + { + $config = OrderConfig::where('company_uuid', $this->sessionCompany())->where('key', 'ride')->first(); + $rider = (array) data_get($config?->meta, 'rider', []); + + return response()->json([ + 'emergency_number' => $rider['emergency_number'] ?? null, + 'support' => ['phone' => $rider['support_phone'] ?? null, 'email' => $rider['support_email'] ?? null], + ]); + } + /** * Register a push-notification device for the authenticated customer's user. */ @@ -1225,6 +1387,69 @@ protected function refusePhoneChange(Contact $customer, string $phone, mixed $co return null; } + protected function trackingPageUrl(string $number, ?string $companyUuid): string + { + return TrackingCode::pageUrl($number, $companyUuid); + } + + protected function rideChannel(Order $order): mixed + { + return RideChat::channel($order); + } + + protected function rideHasEnded(Order $order): bool + { + return in_array($order->status, ['completed', 'canceled'], true) || (bool) $order->config()?->isTerminalActivityCode($order->status); + } + + /** + * Whether one of the rider's recent card trips has a final fare that Ledger hasn't marked + * paid (`meta.paid_at`). Cash is collected by the driver, so it never blocks a booking. + */ + protected function hasUnpaidRide(Contact $customer): bool + { + return Order::withoutGlobalScopes() + ->where('customer_uuid', $customer->uuid) + ->where('type', 'ride') + ->where('status', 'completed') + ->whereNull('deleted_at') + ->latest() + ->limit(20) + ->get(['uuid', 'meta']) + ->contains(fn (Order $order) => data_get($order->meta, 'payment') === 'card' && data_get($order->meta, 'fare.final') && !data_get($order->meta, 'paid_at')); + } + + /** + * Whether the rider has a ride that was sent to drivers and hasn't ended. + */ + protected function hasActiveRide(Contact $customer): bool + { + return Order::withoutGlobalScopes() + ->where('customer_uuid', $customer->uuid) + ->where('dispatched', 1) + ->whereNull('deleted_at') + ->whereNotIn('status', ['completed', 'canceled', 'no_show']) + ->exists(); + } + + /** + * Remove what identifies the rider, then delete their records. A user who is only this + * company's rider goes too; one with other roles or companies keeps their account. + */ + protected function eraseCustomer(Contact $customer, ?User $user): void + { + Place::where('owner_uuid', $customer->uuid)->delete(); + + $customer->forceFill(['name' => 'Deleted rider', 'email' => null, 'phone' => null, 'photo_uuid' => null, 'meta' => []])->saveQuietly(); + $customer->delete(); + + $otherContacts = $user ? Contact::withoutGlobalScopes()->where('user_uuid', $user->uuid)->where('uuid', '!=', $customer->uuid)->exists() : true; + if ($user && $user->type === 'customer' && !$otherContacts) { + $user->forceFill(['name' => 'Deleted rider', 'email' => 'deleted-' . $user->uuid . '@deleted.invalid', 'phone' => null])->saveQuietly(); + $user->delete(); + } + } + protected function ownedOrder(string $id): ?Order { $customer = $this->currentCustomer(); diff --git a/server/src/Http/Controllers/Api/v1/DriverController.php b/server/src/Http/Controllers/Api/v1/DriverController.php index fd006cb2c..364755c90 100644 --- a/server/src/Http/Controllers/Api/v1/DriverController.php +++ b/server/src/Http/Controllers/Api/v1/DriverController.php @@ -28,6 +28,7 @@ use Fleetbase\FleetOps\Support\NavigatorReview; use Fleetbase\FleetOps\Support\OSRM; use Fleetbase\FleetOps\Support\ProfileAccountManager; +use Fleetbase\FleetOps\Support\Rides\RideUpdates; use Fleetbase\FleetOps\Support\TrackingPublisher; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; @@ -394,6 +395,9 @@ public function track(string $id, Request $request) broadcast(new DriverLocationChanged($driver)); app(TrackingPublisher::class)->driverMoved($driver); + // A rider is told once when their car is about to arrive. + RideUpdates::driverMoved($driver, $order instanceof Order ? $order : null); + // ---------------------------------------------------------------- // Geofence intersection detection // diff --git a/server/src/Http/Controllers/Public/TrackingController.php b/server/src/Http/Controllers/Public/TrackingController.php index 758c3436f..1b5325515 100644 --- a/server/src/Http/Controllers/Public/TrackingController.php +++ b/server/src/Http/Controllers/Public/TrackingController.php @@ -10,6 +10,7 @@ use Fleetbase\FleetOps\Support\TrackingPage\TrackingAccess; use Fleetbase\FleetOps\Support\TrackingPage\TrackingRecipient; use Fleetbase\FleetOps\Support\TrackingPage\TrackingResolver; +use Fleetbase\FleetOps\Support\TrackingPage\TrackingShare; use Fleetbase\FleetOps\Support\TrackingPage\TrackingTarget; use Fleetbase\FleetOps\Support\TrackingPage\TrackingView; use Fleetbase\FleetOps\Support\TrackingPublisher; @@ -152,6 +153,24 @@ public function verifyCode(Request $request, string $number): JsonResponse }; } + /** + * Open a link a rider shared: a valid token gives this device the rider's live view, as a + * verified code would. + */ + public function redeemShare(Request $request, string $number): JsonResponse + { + if (!$this->access->allowVerify($request)) { + return $this->json(['error' => 'limited', 'retry_after' => TrackingAccess::LOOKUP_WINDOW], 429); + } + + $target = $this->resolve($request, $number); + if (!$target || !$target->scope) { + return $this->notFound(); + } + + return TrackingShare::valid($request->input('token'), $target->scope) ? $this->verified($request, $target, 'share') : $this->json(['error' => 'invalid'], 422); + } + /** * Sign this device out: of one delivery with `?number=`, otherwise of every one. */ diff --git a/server/src/Notifications/RideUpdate.php b/server/src/Notifications/RideUpdate.php new file mode 100644 index 000000000..61ce103f9 --- /dev/null +++ b/server/src/Notifications/RideUpdate.php @@ -0,0 +1,81 @@ + ['Your driver is on the way', '{driver} accepted your ride.'], + 'arriving' => ['Your driver is almost there', '{driver} is about a minute away.'], + 'arrived' => ['Your driver has arrived', '{driver} is waiting at the pickup point.'], + 'in_progress' => ['Your trip has started', 'Enjoy the ride.'], + 'completed' => ['You have arrived', 'Your trip is complete. See your fare in the app.'], + 'canceled' => ['Your ride was canceled', "You haven't been charged. You can book again."], + 'no_driver_found' => ['No driver found', 'No drivers are free right now. Try again in a few minutes.'], + ]; + + public string $title; + public string $message; + public array $data; + + public function __construct(public Order $order, public string $kind) + { + [$title, $message] = self::MESSAGES[$kind]; + $driver = trim((string) strtok((string) static::driverName($order), ' ')) ?: 'Your driver'; + + $this->title = $title; + $this->message = str_replace('{driver}', $driver, $message); + $this->data = ['id' => $order->public_id, 'type' => 'ride_' . $kind]; + } + + /** + * The driver's name, read without loading their whole record. + */ + public static function driverName(Order $order): ?string + { + if ($order->relationLoaded('driverAssigned')) { + return data_get($order, 'driverAssigned.name'); + } + + $userUuid = $order->driver_assigned_uuid ? Driver::withoutGlobalScopes()->where('uuid', $order->driver_assigned_uuid)->value('user_uuid') : null; + + return $userUuid ? User::where('uuid', $userUuid)->value('name') : null; + } + + public static function knows(string $kind): bool + { + return isset(self::MESSAGES[$kind]); + } + + public function via($notifiable) + { + return [FcmChannel::class, ApnChannel::class]; + } + + public function toFcm($notifiable) + { + return PushNotification::createFcmMessage($this->title, $this->message, $this->data); + } + + public function toApn($notifiable) + { + return PushNotification::createApnMessage($this->title, $this->message, $this->data, 'view_ride'); + } +} diff --git a/server/src/Observers/OrderObserver.php b/server/src/Observers/OrderObserver.php index 45c9261bd..ecf9cc5a4 100644 --- a/server/src/Observers/OrderObserver.php +++ b/server/src/Observers/OrderObserver.php @@ -9,6 +9,8 @@ use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\LiveCacheService; +use Fleetbase\FleetOps\Support\Rides\FinalFare; +use Fleetbase\FleetOps\Support\Rides\RideUpdates; use Fleetbase\FleetOps\Support\TrackingPublisher; use Fleetbase\Support\ApiModelCache; use Illuminate\Support\Facades\Cache; @@ -73,6 +75,15 @@ public function updated(Order $order) // Public tracking channels follow status, assignment and ETA changes. app(TrackingPublisher::class)->orderChanged($order); + + // A rider hears about each step of their ride. This reads the order's changes, so it + // comes before pricing, which saves the order again. + RideUpdates::statusChanged($order); + + // A finished ride is priced from the actual trip. + if ($order->wasChanged('status')) { + FinalFare::settle($order); + } } /** diff --git a/server/src/Support/Rides/DriverRatings.php b/server/src/Support/Rides/DriverRatings.php new file mode 100644 index 000000000..83dff5cab --- /dev/null +++ b/server/src/Support/Rides/DriverRatings.php @@ -0,0 +1,62 @@ +meta, 'rating')) { + return false; + } + + $order->updateMeta('rating', array_filter([ + 'stars' => max(1, min(5, $stars)), + 'comment' => $comment !== null && trim($comment) !== '' ? trim($comment) : null, + 'rated_at' => now()->toISOString(), + ], fn ($value) => $value !== null)); + + $driver = Driver::withoutGlobalScopes()->where('uuid', $order->driver_assigned_uuid)->first(); + if ($driver) { + $driver->forceFill(['meta' => array_merge((array) $driver->meta, ['rating' => static::summary($driver)])])->saveQuietly(); + } + + return true; + } + + /** + * The driver's average stars and how many rides it comes from. + */ + public static function summary(Driver $driver): array + { + $stars = Order::withoutGlobalScopes() + ->where('driver_assigned_uuid', $driver->uuid) + ->whereNull('deleted_at') + ->whereNotNull('meta') + ->pluck('meta') + ->map(fn ($meta) => data_get(is_string($meta) ? json_decode($meta, true) : $meta, 'rating.stars')) + ->filter(fn ($value) => is_numeric($value)); + + return ['average' => $stars->isEmpty() ? null : round($stars->avg(), 2), 'count' => $stars->count()]; + } + + /** + * The driver's average, or null before their first rating. + */ + public static function average(mixed $driver): ?float + { + $average = data_get($driver, 'meta.rating.average'); + + return is_numeric($average) ? (float) $average : null; + } +} diff --git a/server/src/Support/Rides/FinalFare.php b/server/src/Support/Rides/FinalFare.php new file mode 100644 index 000000000..98104ac0d --- /dev/null +++ b/server/src/Support/Rides/FinalFare.php @@ -0,0 +1,143 @@ +status !== 'completed' || data_get($order->meta, 'fare.final')) { + return null; + } + + $rate = data_get($order, 'purchaseRate.serviceQuote.serviceRate'); + if (!$rate instanceof ServiceRate) { + return null; + } + + $startedAt = static::tripStartedAt($order); + [$distance, $source] = static::distance($order, $startedAt); + $duration = max(0, (int) $startedAt->diffInSeconds(Carbon::now(), true)); + $stops = collect([$order->payload?->pickup, $order->payload?->dropoff])->filter()->values(); + [$subTotal, $lines] = $rate->quoteFromPreliminaryData([], $stops, $distance, $duration, false, 2); + $estimate = data_get($order, 'purchaseRate.serviceQuote.amount'); + + $fare = [ + 'final' => true, + 'total' => (int) $subTotal, + 'currency' => $rate->currency, + 'estimate' => is_numeric($estimate) ? (int) $estimate : null, + 'distance_m' => $distance, + 'duration_s' => $duration, + 'distance_source' => $source, + 'lines' => collect($lines)->values()->map(fn ($line, $index) => [ + 'label' => static::label($rate, (string) data_get($line, 'details'), $index), + 'amount' => (int) data_get($line, 'amount', 0), + 'code' => data_get($line, 'code'), + ])->all(), + ]; + + // The fare goes on the order first, so Ledger sees a final fare when the new price arrives. + $order->updateMeta('fare', $fare); + $order->purchaseServiceQuote(static::quote($order, $rate, $fare, $lines)); + + return $fare; + } + + /** + * When the rider got in: the trip's `in_progress` step, else when the driver started. + */ + public static function tripStartedAt(Order $order): Carbon + { + $boarded = $order->tracking_number_uuid + ? TrackingStatus::where('tracking_number_uuid', $order->tracking_number_uuid)->where('code', 'IN_PROGRESS')->oldest()->value('created_at') + : null; + + return Carbon::parse($boarded ?? $order->started_at ?? $order->created_at ?? Carbon::now()); + } + + /** + * Metres the car's recorded positions cover since the trip started, and where the figure + * came from. With too few positions it falls back to the straight line between the stops. + */ + public static function distance(Order $order, Carbon $since): array + { + $points = Position::where('order_uuid', $order->uuid) + ->where('created_at', '>=', $since) + ->orderBy('created_at') + ->orderBy('id') + ->get() + ->map(fn (Position $position) => $position->coordinates) + ->filter(fn ($point) => Utils::isPoint($point)) + ->values(); + + $metres = 0.0; + for ($i = 1; $i < $points->count(); $i++) { + $metres += Utils::vincentyGreatCircleDistance($points[$i - 1], $points[$i]); + } + if ($metres > 0) { + return [(int) round($metres), 'positions']; + } + + $pickup = $order->payload?->pickup?->location; + $dropoff = $order->payload?->dropoff?->location; + + return Utils::isPoint($pickup) && Utils::isPoint($dropoff) ? [(int) round(Utils::vincentyGreatCircleDistance($pickup, $dropoff)), 'straight_line'] : [0, 'none']; + } + + protected static function label(ServiceRate $rate, string $details, int $index): string + { + if ($index === 0) { + return 'Base fare'; + } + + return match ($rate->rate_calculation_method) { + 'per_meter' => 'Distance', + 'algo', 'algorithm' => 'Distance and time', + default => $details !== '' ? $details : 'Fare', + }; + } + + protected static function quote(Order $order, ServiceRate $rate, array $fare, iterable $lines): ServiceQuote + { + $quote = ServiceQuote::create([ + 'request_id' => 'final_' . Str::lower(Str::random(12)), + 'company_uuid' => $order->company_uuid, + 'service_rate_uuid' => $rate->uuid, + 'amount' => $fare['total'], + 'currency' => $fare['currency'], + 'meta' => ['final' => true, 'order' => $order->public_id, 'distance_m' => $fare['distance_m'], 'duration_s' => $fare['duration_s']], + ]); + + foreach ($fare['lines'] as $line) { + ServiceQuoteItem::create([ + 'service_quote_uuid' => $quote->uuid, + 'amount' => $line['amount'], + 'currency' => $fare['currency'], + 'details' => $line['label'], + 'code' => $line['code'], + ]); + } + + return $quote; + } +} diff --git a/server/src/Support/Rides/RideChat.php b/server/src/Support/Rides/RideChat.php new file mode 100644 index 000000000..2c7f84708 --- /dev/null +++ b/server/src/Support/Rides/RideChat.php @@ -0,0 +1,115 @@ +meta, 'chat_channel'); + $channel = $channelUuid ? ChatChannel::where('uuid', $channelUuid)->first() : null; + if (!$channel) { + // Creating the channel adds its creator, the rider, as a participant. + $channel = ChatChannel::create([ + 'company_uuid' => $order->company_uuid, + 'created_by_uuid' => $riderUser, + 'name' => 'Ride ' . $order->public_id, + 'meta' => ['order_public_id' => $order->public_id, 'kind' => 'group'], + ]); + $order->updateMeta('chat_channel', $channel->uuid); + } + + static::participant($channel, $riderUser, 'customer'); + static::participant($channel, $driverUser, 'driver'); + + return $channel; + }); + } + + /** + * Messages oldest first, each marked as the rider's or the driver's. + */ + public static function messages(ChatChannel $channel, string $riderUser): Collection + { + return ChatMessage::where('chat_channel_uuid', $channel->uuid) + ->with('sender') + ->latest() + ->limit(self::MESSAGE_LIMIT) + ->get() + ->reverse() + ->values() + ->map(fn (ChatMessage $message) => [ + 'id' => $message->public_id ?? $message->uuid, + 'from' => data_get($message, 'sender.user_uuid') === $riderUser ? 'rider' : 'driver', + 'text' => (string) $message->content, + 'sent_at' => $message->created_at?->toISOString(), + ]); + } + + /** + * Send a message as the rider, and tell the driver. + */ + public static function send(ChatChannel $channel, string $riderUser, string $text): ChatMessage + { + return static::asUser($riderUser, function () use ($channel, $riderUser, $text) { + $sender = static::participant($channel, $riderUser, 'customer'); + $message = ChatMessage::create([ + 'company_uuid' => $channel->company_uuid, + 'chat_channel_uuid' => $channel->uuid, + 'sender_uuid' => $sender->uuid, + 'content' => $text, + ]); + $message->notifyParticipants(); + + return $message; + }); + } + + /** + * Core's chat logs record who added a participant from the signed-in user, which on a rider + * request is the key's owner rather than the rider, so the rider is signed in for the change. + */ + protected static function asUser(string $userUuid, callable $callback): mixed + { + $previous = session('user'); + session(['user' => $userUuid]); + + try { + return $callback(); + } finally { + session(['user' => $previous]); + } + } + + protected static function participant(ChatChannel $channel, string $userUuid, string $role): ChatParticipant + { + return ChatParticipant::firstOrCreate( + ['chat_channel_uuid' => $channel->uuid, 'user_uuid' => $userUuid], + ['company_uuid' => $channel->company_uuid, 'meta' => ['role' => $role]] + ); + } +} diff --git a/server/src/Support/Rides/RideUpdates.php b/server/src/Support/Rides/RideUpdates.php new file mode 100644 index 000000000..c1467f904 --- /dev/null +++ b/server/src/Support/Rides/RideUpdates.php @@ -0,0 +1,80 @@ +wasChanged('status')) { + return false; + } + + $kind = $order->status === 'canceled' && data_get($order->meta, 'dispatch_outcome') === 'no_driver_found' ? 'no_driver_found' : (string) $order->status; + + return RideUpdate::knows($kind) && static::send($order, $kind); + } + + /** + * The driver of a ride reported a position: tell the rider once when the car is close. + */ + public static function driverMoved(Driver $driver, ?Order $order): bool + { + if (!$order || !static::isRide($order) || $order->status !== 'started') { + return false; + } + + $pickup = $order->getPickupLocation(); + if (!Utils::isPoint($pickup) || !Utils::isPoint($driver->location)) { + return false; + } + + $distance = Utils::vincentyGreatCircleDistance($driver->location, $pickup); + if ($distance > self::ARRIVING_DISTANCE || !Cache::add('fleetops:ride:arriving:' . $order->uuid, 1, now()->addHours(6))) { + return false; + } + + return static::send($order, 'arriving'); + } + + public static function isRide(Order $order): bool + { + return $order->type === 'ride'; + } + + protected static function send(Order $order, string $kind): bool + { + $rider = $order->customer; + if (!$rider || !method_exists($rider, 'notify')) { + return false; + } + + try { + $rider->notify(new RideUpdate($order, $kind)); + } catch (\Throwable $exception) { + Log::warning('Unable to send a ride update', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + + return false; + } + + return true; + } +} diff --git a/server/src/Support/TrackingPage/TrackingShare.php b/server/src/Support/TrackingPage/TrackingShare.php new file mode 100644 index 000000000..6231e24ab --- /dev/null +++ b/server/src/Support/TrackingPage/TrackingShare.php @@ -0,0 +1,40 @@ +addHours(self::HOURS))->getTimestamp(); + + return $expires . '.' . static::sign($orderUuid, $customerUuid, $expires); + } + + public static function valid(mixed $token, ?TrackingScope $scope): bool + { + if (!$scope || !is_string($token) || !preg_match('/^(\d+)\.([a-f0-9]{64})$/', $token, $parts)) { + return false; + } + + $expires = (int) $parts[1]; + + return $expires > Carbon::now()->getTimestamp() + && hash_equals(static::sign((string) $scope->order_uuid, (string) $scope->customer_uuid, $expires), $parts[2]); + } + + protected static function sign(string $orderUuid, string $customerUuid, int $expires): string + { + return hash_hmac('sha256', 'tracking-share|' . $orderUuid . '|' . $customerUuid . '|' . $expires, (string) config('app.key')); + } +} diff --git a/server/src/routes.php b/server/src/routes.php index 3cc67ea90..75839553e 100644 --- a/server/src/routes.php +++ b/server/src/routes.php @@ -35,6 +35,7 @@ function ($router) { $router->get('{number}/proofs/{id}', 'TrackingController@proof'); $router->post('{number}/report', 'TrackingController@report'); $router->get('{number}/socket-token', 'TrackingController@socketToken'); + $router->post('{number}/share', 'TrackingController@redeemShare'); }); $router->prefix('public')->namespace('Public')->middleware([Fleetbase\FleetOps\Http\Middleware\ForceJsonResponse::class, 'throttle:60,1,inspection-public'])->group(function ($router) { @@ -131,6 +132,12 @@ function ($router) { $router->get('orders/{id}/driver', 'CustomerController@orderDriver'); $router->get('orders/{id}/tracker', 'CustomerController@orderTracker'); $router->get('orders/{id}/eta', 'CustomerController@orderEta'); + $router->get('orders/{id}/messages', 'CustomerController@orderMessages'); + $router->post('orders/{id}/messages', 'CustomerController@sendOrderMessage')->middleware('throttle:30,1'); + $router->post('orders/{id}/rating', 'CustomerController@rateOrder'); + $router->post('orders/{id}/share', 'CustomerController@shareOrder'); + $router->get('ride-settings', 'CustomerController@rideSettings'); + $router->delete('me', 'CustomerController@deleteMe'); }); }); // vendors routes @@ -223,6 +230,7 @@ function ($router) { $router->match(['post', 'patch'], '{id}/schedule', 'OrderController@scheduleOrder'); $router->match(['post', 'patch'], '{id}/dispatch', 'OrderController@dispatchOrder'); $router->post('{id}/start', 'OrderController@startOrder'); + $router->post('{id}/decline', 'OrderController@declineOrder'); $router->delete('{id}/cancel', 'OrderController@cancelOrder'); $router->match(['post', 'patch'], '{id}/update-activity', 'OrderController@updateActivity'); $router->post('{id}/complete', 'OrderController@completeOrder'); diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index b186b9364..8ed0b3817 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -331,6 +331,13 @@ protected function resolveOrderConfig(CreateCustomerOrderRequest $request, strin return $this->orderConfig; } + public bool $unpaidRide = false; + + protected function hasUnpaidRide(Contact $customer): bool + { + return $this->unpaidRide; + } + protected function getUuid(array|string $table, array $where, array $options = []): mixed { $this->uuidLookups[] = [$table, $where, $options]; @@ -1415,6 +1422,11 @@ public function cancelWithReason(?string $reason = null) $this->calls[] = ['reason', $reason]; } + public function config(): ?OrderConfig + { + return $this->faked['config'] ?? new OrderConfig(); + } + public function tracker(): Fleetbase\FleetOps\Support\OrderTracker { return $this->trackerFake; @@ -1580,7 +1592,7 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps expect($none)->toBe(['driver' => null, 'vehicle' => null]) ->and($noCar['vehicle'])->toBeNull() - ->and($withCar['driver'])->toBe(['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here']) + ->and($withCar['driver'])->toBe(['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here', 'rating' => null]) ->and($withCar['vehicle'])->toBe(['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']); }); @@ -1603,3 +1615,55 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps expect($controller->orderDriver('order_missing')->getStatusCode())->toBe(404); }); + +test('a ride needs a fare, is adhoc, and its class comes from the fare, not the rider', function () { + $ride = new OrderConfig(['key' => 'ride', 'meta' => ['offers' => ['enabled' => true]]]); + $ride->uuid = 'config-ride'; + $noFare = fleetopsApiCustomerController(); + $noFare->orderConfig = $ride; + $noFare->serviceQuote = null; + $booked = fleetopsApiCustomerController(); + $booked->orderConfig = $ride; + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['service_type' => 'economy', 'service_name' => 'Economy'], true); + $booked->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); + $booked->serviceQuote->setRelation('serviceRate', $rate); + + $refused = $noFare->createOrder(new FleetOpsApiCustomerOrderRequest(['pickup' => ['name' => 'A']])); + $booked->createOrder(new FleetOpsApiCustomerOrderRequest([ + 'service_quote' => 'quote_1', + 'pickup' => ['name' => 'A'], + 'meta' => ['payment' => 'cash', 'vehicle_class' => 'xl', 'fare' => ['total' => 1], 'dispatch_outcome' => 'x'], + ])); + + $owing = fleetopsApiCustomerController(); + $owing->orderConfig = $ride; + $owing->unpaidRide = true; + $owing->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); + $blocked = $owing->createOrder(new FleetOpsApiCustomerOrderRequest(['service_quote' => 'quote_1'])); + + expect($refused->getStatusCode())->toBe(422) + ->and(fleetopsApiCustomerJson($refused))->toBe(['error' => 'Choose a ride option first.']) + ->and($blocked->getStatusCode())->toBe(402) + ->and($owing->createdOrders)->toBe([]) + ->and($booked->createdOrders[0]['adhoc'])->toBeTrue() + ->and($booked->createdOrders[0]['meta'])->toBe(['payment' => 'cash', 'vehicle_class' => 'economy', 'service_name' => 'Economy']); +}); + +test('a ride that ended in a no-show can no longer be canceled', function () { + $controller = fleetopsRiderController(['status' => 'no_show'], ['config' => new OrderConfig(Fleetbase\FleetOps\Support\FleetOps::rideConfigDefaults())]); + + expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) + ->and($controller->order->calls)->toBe([]); +}); + +test('a shared ride links to the public tracking page', function () { + config()->set('fleetbase.console.host', 'https://console.test'); + $url = fleetopsApiCustomerWithEnvironment('production', function () { + $method = new ReflectionMethod(CustomerController::class, 'trackingPageUrl'); + + return $method->invoke(new CustomerController(), 'RIDE1', null); + }); + + expect($url)->toContain('track/RIDE1'); +}); diff --git a/server/tests/Feature/Http/Public/TrackingControllerTest.php b/server/tests/Feature/Http/Public/TrackingControllerTest.php index 623549f09..a002f9c4f 100644 --- a/server/tests/Feature/Http/Public/TrackingControllerTest.php +++ b/server/tests/Feature/Http/Public/TrackingControllerTest.php @@ -2,7 +2,6 @@ use Fleetbase\FleetOps\Http\Controllers\Public\TrackingController; use Fleetbase\FleetOps\Models\Contact; -use Fleetbase\FleetOps\Models\Entity; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Models\Proof; @@ -23,10 +22,10 @@ class TrackingControllerResolverFake extends TrackingResolver { public ?TrackingTarget $target = null; - public ?string $slugCompany = null; - public array $company = []; - public array $admin = []; - public array $resolved = []; + public ?string $slugCompany = null; + public array $company = []; + public array $admin = []; + public array $resolved = []; public function resolve(mixed $input, ?string $slug = null): ?TrackingTarget { @@ -264,7 +263,7 @@ function trackingControllerRequest(array $input = []): Request test('the page config shows a company page or the shared page, and nothing for a page that is off', function () { $controller = trackingController(); - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'companies', ['uuid' => 'co-1', 'name' => 'Northwind Couriers', 'phone' => '+15105550142']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'companies', ['uuid' => 'co-1', 'name' => 'Northwind Couriers', 'phone' => '+15105550142']); expect($controller->config(trackingControllerRequest(['org' => 'northwind']))->getStatusCode())->toBe(404); @@ -299,7 +298,7 @@ function trackingControllerRequest(array $input = []): Request // A tracking number alone: the public view, with the channels a code can use. $controller->fakeAccess->lookup = true; $controller->providers = ['vonage' => ['available' => true]]; - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com', 'phone' => '+15105554821']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com', 'phone' => '+15105554821']); $public = $controller->show(trackingControllerRequest(['org' => 'Northwind']), 'NOR1000000001US')->getData(true); expect($public['level'])->toBe(0) ->and(array_column($public['channels'], 'type'))->toBe(['sms', 'email']) @@ -317,10 +316,10 @@ function trackingControllerRequest(array $input = []): Request $controller->fakeAccess->granted = false; $controller->user = (object) ['uuid' => 'user-1', 'type' => 'customer', 'company_uuid' => 'co-1']; - TrackingPageDatabase::insert(Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-x', 'user_uuid' => 'user-1']); + TrackingPageDatabase::insert(EloquentModel::getConnectionResolver()->connection(), 'contacts', ['uuid' => 'contact-x', 'user_uuid' => 'user-1']); expect($controller->show(trackingControllerRequest(), 'NOR1000000001US')->getData(true)['level'])->toBe(0); - Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection()->table('contacts')->where('uuid', 'contact-1')->update(['user_uuid' => 'user-1']); + EloquentModel::getConnectionResolver()->connection()->table('contacts')->where('uuid', 'contact-1')->update(['user_uuid' => 'user-1']); expect($controller->show(trackingControllerRequest(), 'NOR1000000001US')->getData(true))->toMatchArray(['viewer' => 'account', 'level' => 2, 'expires_at' => null]); $controller->user = (object) ['uuid' => 'user-2', 'type' => 'user', 'company_uuid' => 'co-1']; @@ -335,7 +334,7 @@ function trackingControllerRequest(array $input = []): Request test('codes go out on an available channel, within the limits', function () { $controller = trackingController(); - $db = Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(); + $db = EloquentModel::getConnectionResolver()->connection(); TrackingPageDatabase::insert($db, 'contacts', ['uuid' => 'contact-1', 'email' => 'maya@example.com']); TrackingPageDatabase::insert($db, 'companies', ['uuid' => 'co-1', 'name' => 'Northwind', 'options' => json_encode(['alpha_numeric_sender_id_enabled' => true, 'alpha_numeric_sender_id' => 'NORTHWIND'])]); @@ -473,7 +472,7 @@ function trackingControllerRequest(array $input = []): Request test('a signed-in customer lists their orders with the number that opens their part', function () { $controller = trackingController(); - $db = Illuminate\Database\Eloquent\Model::getConnectionResolver()->connection(); + $db = EloquentModel::getConnectionResolver()->connection(); expect($controller->accountOrders(trackingControllerRequest())->getStatusCode())->toBe(401); @@ -493,3 +492,24 @@ function trackingControllerRequest(array $input = []): Request ['tracking_number' => 'NOR1', 'title' => 'Ceramic lamp', 'status' => 'completed', 'stage' => 'delivered', 'updated_at' => '2026-10-07T10:00:00.000000Z'], ]); }); + +test('a shared ride link opens the rider\'s live view, and a bad one doesn\'t', function () { + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $controller = trackingController(); + $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-1'); + + $controller->fakeAccess->verify = false; + expect($controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1')->getStatusCode())->toBe(429); + + $controller->fakeAccess->verify = true; + expect($controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1')->getStatusCode())->toBe(404); + + $controller->fakeResolver->target = trackingControllerTarget(); + $bad = $controller->redeemShare(trackingControllerRequest(['token' => 'nope']), 'NOR1'); + $opened = $controller->redeemShare(trackingControllerRequest(['token' => $token]), 'NOR1'); + + expect($bad->getData(true))->toBe(['error' => 'invalid']) + ->and($opened->getStatusCode())->toBe(200) + ->and($opened->getData(true)['viewer'])->toBe('verified') + ->and($controller->fakeAccess->grants[0][1])->toBe('share'); +}); diff --git a/server/tests/Feature/RidesTest.php b/server/tests/Feature/RidesTest.php new file mode 100644 index 000000000..dd08b75ff --- /dev/null +++ b/server/tests/Feature/RidesTest.php @@ -0,0 +1,1017 @@ +uuid, $reason]; + + return null; + } +} + +/** A point as MySQL stores it (SRID, then WKB), which the spatial models read back. */ +function rideOffersWkb(float $longitude, float $latitude): string +{ + return pack('V', 0) . pack('C', 1) . pack('V', 1) . pack('e', $longitude) . pack('e', $latitude); +} + +/** [longitude, latitude] of a stored point or of WKT text. */ +function rideOffersPoint(?string $value): array +{ + if ($value !== null && preg_match('/POINT\(\s*([-0-9.]+)\s+([-0-9.]+)\s*\)/i', $value, $m)) { + return [(float) $m[1], (float) $m[2]]; + } + if ($value === null || strlen($value) < 25) { + return [0.0, 0.0]; + } + $xy = unpack('ex/ey', substr($value, 9, 16)); + + return [$xy['x'], $xy['y']]; +} + +function rideOffersBoot(): SQLiteConnection +{ + if (!Illuminate\Support\Str::hasMacro('humanize')) { + Illuminate\Support\Str::macro('humanize', fn ($value, $uppercase = true) => str_replace('_', ' ', Illuminate\Support\Str::snake((string) $value))); + } + + $pdo = new PDO('sqlite::memory:'); + $pdo->sqliteCreateFunction('ST_GeomFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_PointFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_X', fn ($wkt) => rideOffersPoint($wkt)[0]); + $pdo->sqliteCreateFunction('ST_Y', fn ($wkt) => rideOffersPoint($wkt)[1]); + $pdo->sqliteCreateFunction('st_distance_sphere', function ($a, $b) { + [$lng1, $lat1] = rideOffersPoint($a); + [$lng2, $lat2] = rideOffersPoint($b); + $rad = M_PI / 180; + $h = sin(($lat2 - $lat1) * $rad / 2) ** 2 + cos($lat1 * $rad) * cos($lat2 * $rad) * sin(($lng2 - $lng1) * $rad / 2) ** 2; + + return 2 * 6371000 * asin(sqrt($h)); + }); + $pdo->sqliteCreateFunction('LOWER', fn ($value) => $value === null ? null : strtolower((string) $value)); + + $connection = new SQLiteConnection($pdo); + $resolver = new ConnectionResolver(['default' => $connection, 'mysql' => $connection]); + $resolver->setDefaultConnection('mysql'); + EloquentModel::setConnectionResolver($resolver); + if (!EloquentModel::getEventDispatcher()) { + EloquentModel::setEventDispatcher(new Illuminate\Events\Dispatcher()); + } + app()->instance('db', new class($connection) { + public function __construct(public SQLiteConnection $c) + { + } + + public function connection($name = null): SQLiteConnection + { + return $this->c; + } + + public function __call($method, $arguments) + { + return $this->c->{$method}(...$arguments); + } + }); + Illuminate\Support\Facades\DB::clearResolvedInstance('db'); + app()->instance('responsecache', new class { + public function __call($method, $arguments) + { + return null; + } + }); + config()->set('activitylog.enabled', false); + config()->set('activitylog.default_auth_driver', 'web'); + app()->bind(Illuminate\Contracts\Config\Repository::class, fn () => config()); + + app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, new class { + public function send($notifiables, $notification) + { + if (RideOffersRecorder::$notified === ['throw']) { + throw new RuntimeException('push failed'); + } + RideOffersRecorder::$notified[] = [$notifiables->uuid, $notification::class]; + } + + public function sendNow($notifiables, $notification, ?array $channels = null) + { + $this->send($notifiables, $notification); + } + }); + app()->instance('log', new class { + public array $warnings = []; + + public function warning($message, array $context = []) + { + $this->warnings[] = $message; + } + + public function __call($method, $arguments) + { + return null; + } + }); + Illuminate\Support\Facades\Log::clearResolvedInstance('log'); + + $schema = $connection->getSchemaBuilder(); + $tables = [ + 'companies' => ['uuid', 'public_id', 'name', 'options'], + 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'status', 'email', 'phone'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid', 'meta'], + 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'type', 'plate_number', 'seating_capacity', 'vendor_uuid', 'photo_uuid', 'avatar_url', 'name', 'internal_id', 'location', 'online', 'speed', 'heading', 'altitude', 'year', 'make', 'model', 'class', 'color', 'call_sign', 'status', 'specs', 'vin_data', 'telematics', 'meta', 'slug', 'vin', 'trim', 'plate_number_type'], + 'orders' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', 'tags'], + 'order_offers' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], + 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta'], + 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'location', 'meta', 'owner_uuid', 'owner_type'], + 'waypoints' => ['uuid', 'payload_uuid', 'place_uuid', 'order'], + 'entities' => ['uuid', 'payload_uuid', 'name'], + 'tracking_statuses' => ['uuid', 'company_uuid', 'tracking_number_uuid', 'code', 'status'], + 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'status_uuid'], + 'contacts' => ['uuid', '_key', 'public_id', 'company_uuid', 'user_uuid', 'name', 'email', 'phone', 'type', 'photo_uuid', 'meta'], + 'chat_channels' => ['uuid', '_key', 'public_id', 'company_uuid', 'created_by_uuid', 'name', 'slug', 'meta'], + 'chat_participants' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'user_uuid', 'meta'], + 'chat_messages' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'sender_uuid', 'content', 'meta'], + 'chat_attachments' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'chat_message_uuid', 'sender_uuid', 'file_uuid'], + 'chat_logs' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'initiator_uuid', 'event_type', 'content', 'subjects', 'meta', 'status'], + 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name'], + 'files' => ['uuid', 'public_id', 'company_uuid', 'type', 'path', 'disk', 'bucket', 'original_filename', 'content_type', 'file_size', 'meta'], + 'chat_receipts' => ['uuid', 'public_id', 'company_uuid', 'chat_message_uuid', 'participant_uuid', 'read_at'], + 'positions' => ['uuid', '_key', 'public_id', 'company_uuid', 'order_uuid', 'subject_uuid', 'subject_type', 'coordinates', 'heading', 'speed'], + 'service_rates' => ['uuid', 'public_id', 'company_uuid', 'service_name', 'service_type', 'base_fee', 'per_meter_flat_rate_fee', 'per_meter_unit', 'rate_calculation_method', 'algorithm', 'currency', 'has_cod_fee', 'has_peak_hours_fee'], + 'service_quotes' => ['uuid', '_key', 'public_id', 'company_uuid', 'request_id', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at'], + 'service_quote_items' => ['uuid', '_key', 'public_id', 'service_quote_uuid', 'amount', 'currency', 'details', 'code'], + 'purchase_rates' => ['uuid', '_key', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'service_quote_uuid', 'transaction_uuid', 'payload_uuid', 'status', 'meta'], + ]; + foreach ($tables as $table => $columns) { + $schema->create($table, function ($blueprint) use ($columns) { + $blueprint->increments('id'); + foreach ($columns as $column) { + $blueprint->string($column)->nullable(); + } + $blueprint->timestamps(); + $blueprint->timestamp('deleted_at')->nullable(); + }); + } + + session(['company' => 'company-1']); + $connection->table('companies')->insert([['uuid' => 'company-1', 'public_id' => 'company_one', 'name' => 'Acme Cabs'], ['uuid' => 'company-2', 'public_id' => 'company_two', 'name' => 'Other Cabs']]); + $connection->table('order_configs')->insert([ + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + 'flow' => json_encode(FleetOps::rideConfigDefaults()['flow']), + 'meta' => json_encode(['offers' => ['enabled' => true, 'timeout' => 15]]), + ]); + $connection->table('places')->insert(['uuid' => 'place-pickup', 'company_uuid' => 'company-1', 'name' => 'Raffles Place', 'location' => rideOffersWkb(103.8511, 1.2841)]); + $connection->table('payloads')->insert(['uuid' => 'payload-1', 'company_uuid' => 'company-1', 'pickup_uuid' => 'place-pickup']); + $connection->table('vehicles')->insert([ + ['uuid' => 'car-economy', 'company_uuid' => 'company-1', 'type' => 'Economy'], + ['uuid' => 'car-xl', 'company_uuid' => 'company-1', 'type' => 'xl'], + ]); + + RideOffersRecorder::$notified = []; + Fleetbase\TestSupport\DispatchRecorder::$dispatched = []; + RideOffersOrder::$canceled = []; + RideOffersOrder::$pickupPoint = new Point(1.2841, 103.8511); + + return $connection; +} + +/** Drivers around the pickup at Raffles Place, nearest first: Amara 545 m, Chen 1.2 km, Ben (XL) 210 m. */ +function rideOffersSeedDrivers(SQLiteConnection $connection): void +{ + $connection->table('drivers')->insert([ + ['uuid' => 'amara', 'public_id' => 'driver_amara', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2890)], + ['uuid' => 'chen', 'public_id' => 'driver_chen', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2950)], + ['uuid' => 'ben', 'public_id' => 'driver_ben', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-xl', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2860)], + ['uuid' => 'far', 'public_id' => 'driver_far', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.9915, 1.3644)], + ['uuid' => 'offline', 'public_id' => 'driver_offline', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 0, 'location' => rideOffersWkb(103.8511, 1.2845)], + ['uuid' => 'rival', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2842)], + ]); +} + +function rideOffersOrder(SQLiteConnection $connection, array $attributes = []): RideOffersOrder +{ + $connection->table('orders')->insert(array_merge([ + 'uuid' => 'order-1', + 'public_id' => 'order_ride', + 'company_uuid' => 'company-1', + 'order_config_uuid' => 'config-ride', + 'payload_uuid' => 'payload-1', + 'status' => 'dispatched', + 'type' => 'ride', + 'adhoc' => 1, + 'adhoc_distance' => 6000, + 'dispatched' => 1, + 'started' => 0, + 'meta' => json_encode(['vehicle_class' => 'economy']), + ], $attributes)); + + return RideOffersOrder::where('uuid', $attributes['uuid'] ?? 'order-1')->first(); +} + +function rideOffersDriver(string $uuid): Driver +{ + return Driver::withoutGlobalScopes()->where('uuid', $uuid)->first(); +} + +function rideOffersStatuses(SQLiteConnection $connection): array +{ + return $connection->table('order_offers')->orderBy('id')->get(['driver_uuid', 'status'])->map(fn ($row) => [$row->driver_uuid, $row->status])->all(); +} + +test('drivers are matched by company, free from other jobs and of the booked class', function () { + $connection = rideOffersBoot(); + $connection->table('users')->insert(['uuid' => 'user-moved', 'company_uuid' => 'company-1']); + $connection->table('orders')->insert([ + ['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => null], + ['uuid' => 'job-done', 'company_uuid' => 'company-1', 'status' => 'completed', 'deleted_at' => null], + ['uuid' => 'job-gone', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => now()], + ]); + $connection->table('drivers')->insert([ + ['uuid' => 'free', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'via-user', 'company_uuid' => 'company-9', 'user_uuid' => 'user-moved', 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'other-company', 'company_uuid' => 'company-2', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'busy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-live'], + ['uuid' => 'finished', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-done'], + ['uuid' => 'stale', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-gone'], + ['uuid' => 'big-car', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-xl', 'current_job_uuid' => null], + ]); + + $order = new Order(); + $order->setRawAttributes(['company_uuid' => 'company-1', 'meta' => json_encode(['vehicle_class' => ' ECONOMY '])], true); + $matched = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $order)->orderBy('id')->pluck('uuid')->all(); + + $anyClass = new Order(); + $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'meta' => json_encode(['vehicle_class' => ' '])], true); + $everyClass = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $anyClass)->orderBy('id')->pluck('uuid')->all(); + + expect($matched)->toBe(['free', 'via-user', 'finished', 'stale']) + ->and($everyClass)->toBe(['free', 'via-user', 'finished', 'stale', 'big-car']) + ->and(DriverMatching::vehicleClass($anyClass))->toBeNull() + ->and(DriverMatching::vehicleClass($order))->toBe('ECONOMY'); +}); + +test('a ride is offered to the nearest free driver of its class first', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + + Carbon::setTestNow('2026-11-06 09:00:00'); + $offer = OrderOffers::start($order); + Carbon::setTestNow(); + + expect($offer->driver_uuid)->toBe('amara') + ->and($offer->status)->toBe(OrderOffer::PENDING) + ->and($offer->distance)->toBeGreaterThan(500)->toBeLessThan(600) + ->and($offer->expires_at->toDateTimeString())->toBe('2026-11-06 09:00:15') + ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class]]) + ->and(Fleetbase\TestSupport\DispatchRecorder::$dispatched)->toBe([['job' => ExpireOrderOffer::class, 'arguments' => [$offer->uuid]]]) + ->and($offer->order->uuid)->toBe('order-1') + ->and($offer->driver->uuid)->toBe('amara'); + + // Starting again keeps the open offer instead of offering it twice. + expect(OrderOffers::start($order)->uuid)->toBe($offer->uuid) + ->and(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); +}); + +test('declining moves the ride to the next driver, and only the offered driver may accept', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + OrderOffers::start($order); + + expect(OrderOffers::accept($order, rideOffersDriver('chen')))->toBeFalse() + ->and(OrderOffers::decline($order, rideOffersDriver('chen')))->toBeFalse() + ->and(OrderOffers::decline($order, rideOffersDriver('amara')))->toBeTrue() + ->and(OrderOffers::pending($order)->driver_uuid)->toBe('chen') + ->and(OrderOffers::accept($order, rideOffersDriver('amara')))->toBeFalse() + ->and(OrderOffers::accept($order, rideOffersDriver('chen')))->toBeTrue() + ->and(rideOffersStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'accepted']]); +}); + +test('an offer that ran out cannot be accepted and moves on once, however often it expires', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + $offer = OrderOffers::start($order); + + // Not yet expired + expect(OrderOffers::expire($offer))->toBeFalse(); + + Carbon::setTestNow(now()->addSeconds(30)); + $acceptedLate = OrderOffers::accept($order, rideOffersDriver('amara')); + $first = (new ExpireOrderOffer($offer->uuid))->handle(); + $again = (new ExpireOrderOffer($offer->uuid))->handle(); + $missing = (new ExpireOrderOffer('no-such-offer'))->handle(); + Carbon::setTestNow(); + + expect($acceptedLate)->toBeFalse() + ->and($first)->toBeTrue() + ->and($again)->toBeFalse() + ->and($missing)->toBeFalse() + ->and(rideOffersStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]); +}); + +test('when nobody is left the ride is canceled as no driver found', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + OrderOffers::start($order); + OrderOffers::decline($order, rideOffersDriver('amara')); + OrderOffers::decline($order, rideOffersDriver('chen')); + + $meta = json_decode($connection->table('orders')->where('uuid', 'order-1')->value('meta'), true); + + expect(RideOffersOrder::$canceled)->toBe([['order-1', OrderOffers::NO_DRIVER_FOUND]]) + ->and($meta['dispatch_outcome'])->toBe('no_driver_found') + ->and(OrderOffers::pending($order))->toBeNull(); +}); + +test('a ride without a usable pickup finds no driver', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + RideOffersOrder::$pickupPoint = null; + + expect(OrderOffers::start(rideOffersOrder($connection)))->toBeNull() + ->and(RideOffersOrder::$canceled)->toHaveCount(1); +}); + +test('started, assigned or finished rides are not offered again', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + + $started = rideOffersOrder($connection, ['uuid' => 'o-started', 'started' => 1]); + $assigned = rideOffersOrder($connection, ['uuid' => 'o-assigned', 'driver_assigned_uuid' => 'amara']); + $canceled = rideOffersOrder($connection, ['uuid' => 'o-canceled', 'status' => 'canceled']); + + expect(OrderOffers::offerNext($started))->toBeNull() + ->and(OrderOffers::offerNext($assigned))->toBeNull() + ->and(OrderOffers::offerNext($canceled))->toBeNull() + ->and(rideOffersStatuses($connection))->toBe([]) + ->and(RideOffersOrder::$canceled)->toBe([]); +}); + +test('a failed push still leaves the offer open, and withdrawing closes it', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + RideOffersRecorder::$notified = ['throw']; + + $offer = OrderOffers::start($order); + + expect($offer->status)->toBe(OrderOffer::PENDING) + ->and(app('log')->warnings)->toContain('Unable to send a ride offer') + ->and(OrderOffers::withdraw($order))->toBe(1) + ->and(OrderOffers::withdraw($order))->toBe(0) + ->and(rideOffersStatuses($connection))->toBe([['amara', 'withdrawn']]); +}); + +test('offer settings come from the order config and are kept in range', function () { + $config = fn (array $meta) => new OrderConfig(['meta' => $meta]); + + expect($config([])->usesTimedOffers())->toBeFalse() + ->and($config([])->offerTimeout())->toBe(20) + ->and($config(['offers' => ['enabled' => true, 'timeout' => 3]])->usesTimedOffers())->toBeTrue() + ->and($config(['offers' => ['timeout' => 3]])->offerTimeout())->toBe(10) + ->and($config(['offers' => ['timeout' => 900]])->offerTimeout())->toBe(120) + ->and($config(['offers' => ['timeout' => 45]])->offerTimeout())->toBe(45); +}); + +test('the ride config is a strict flow with a no-show ending, offered one driver at a time', function () { + $defaults = FleetOps::rideConfigDefaults(); + $config = new OrderConfig($defaults); + + expect($defaults['key'])->toBe('ride') + ->and(array_keys($defaults['flow']))->toBe(['created', 'dispatched', 'started', 'arrived', 'in_progress', 'completed', 'no_show']) + ->and($config->usesTimedOffers())->toBeTrue() + ->and($config->hasStrictTransitions())->toBeTrue() + ->and($config->canTransition('arrived', 'no_show'))->toBeTrue() + ->and($config->canTransition('arrived', 'completed'))->toBeFalse() + ->and($config->canTransition('in_progress', 'completed'))->toBeTrue() + ->and($config->isTerminalActivityCode('no_show'))->toBeTrue() + ->and($config->getStartedActivity()->get('status'))->toBe('Driver on the way'); +}); + +test('the create ride config command makes the config once per company', function () { + $connection = rideOffersBoot(); + $connection->table('order_configs')->delete(); + + $command = new class extends CreateRideConfig { + public array $lines = []; + public string $id = ''; + public array $opts = []; + + public function option($key = null) + { + return $this->opts[$key] ?? null; + } + + public function argument($key = null) + { + return $this->id; + } + + public function info($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function error($string, $verbosity = null) + { + $this->lines[] = $string; + } + }; + + $command->id = 'company_missing'; + $missing = $command->handle(); + $command->id = 'company_one'; + $made = $command->handle(); + $command->id = 'company-1'; + $command->opts = ['emergency-number' => '995', 'support-phone' => ' ', 'support-email' => 'help@cabs.test']; + $again = $command->handle(); + + expect($missing)->toBe(1) + ->and($made)->toBe(0) + ->and($again)->toBe(0) + ->and($command->lines[0])->toBe('No company found for company_missing.') + ->and($command->lines[1])->toContain('is ready for Acme Cabs.') + ->and($connection->table('order_configs')->where('key', 'ride')->count())->toBe(1) + ->and(json_decode($connection->table('order_configs')->where('key', 'ride')->value('meta'), true)['rider'])->toBe(['emergency_number' => '995', 'support_email' => 'help@cabs.test']); +}); + +test('the dispatch listener hands rides with timed offers to the offers', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $ride = rideOffersOrder($connection); + $transport = new Order(); + $transport->setRawAttributes(['uuid' => 'order-t', 'company_uuid' => 'company-1'], true); + + $listener = new class extends Fleetbase\FleetOps\Listeners\HandleOrderDispatched { + public function call(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + }; + + expect($listener->call('usesTimedOffers', $ride))->toBeTrue() + ->and($listener->call('usesTimedOffers', $transport))->toBeFalse() + ->and($listener->call('startOffers', $ride)->driver_uuid)->toBe('amara'); + + // Handling the dispatch of a ride offers it instead of pinging every driver. + $connection->table('order_offers')->delete(); + $connection->table('orders')->where('uuid', 'order-1')->update(['tracking_number_uuid' => 'tn-1']); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'RIDE1', 'owner_uuid' => 'order-1']); + $listener->handle(new Fleetbase\FleetOps\Events\OrderDispatched(RideOffersOrder::where('uuid', 'order-1')->first())); + expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]) + ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class], ['amara', OrderPing::class]]); +}); + +test('the adhoc command moves stuck offers on and re-pings without dispatching again', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + + $command = new class extends Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders { + public array $lines = []; + + public function info($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + }; + + // No offer yet: the offers start. + $ride = rideOffersOrder($connection); + expect($command->helper('usesTimedOffers', $ride))->toBeTrue(); + $command->helper('advanceOffers', $ride); + expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); + + // An open offer still in time is left alone. + $command->helper('advanceOffers', $ride); + expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); + + // An offer whose expiry job was lost is closed and the next driver gets the ride. + Carbon::setTestNow(now()->addMinute()); + $command->helper('advanceOffers', $ride); + Carbon::setTestNow(); + expect(rideOffersStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]) + ->and($command->lines)->toBe(['Started offers for order order_ride.', 'Moved order order_ride to the next driver.']); + + // An order whose offers all ended is not started again. + $connection->table('order_offers')->update(['status' => 'declined']); + $command->helper('advanceOffers', $ride); + expect($connection->table('order_offers')->count())->toBe(2); + + // A re-ping restarts the interval quietly. + Carbon::setTestNow('2026-11-06 10:00:00'); + $command->helper('markPinged', $ride); + Carbon::setTestNow(); + expect($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); + + // Drivers matched for a re-ping leave out busy ones and other classes. + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'chen')->update(['current_job_uuid' => 'job-live']); + $matched = $command->helper('matchDrivers', Driver::query()->withoutGlobalScopes()->where('online', 1), $ride)->orderBy('id')->pluck('uuid')->all(); + expect($matched)->toBe(['amara', 'far', 'rival']); +}); + +test('fares carry each class\'s seats and how soon its nearest free car could arrive', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $connection->table('vehicles')->where('uuid', 'car-economy')->update(['seating_capacity' => 4]); + $connection->table('vehicles')->insert(['uuid' => 'car-economy-2', 'company_uuid' => 'company-1', 'type' => 'economy', 'seating_capacity' => 5]); + + $controller = new class extends Fleetbase\FleetOps\Http\Controllers\Api\v1\ServiceQuoteController { + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + public function from(?Point $point): void + { + $this->availabilityFrom = $point; + } + }; + $quote = function (string $class) { + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['service_type' => $class], true); + $quote = new Fleetbase\FleetOps\Models\ServiceQuote(); + $quote->setRawAttributes(['company_uuid' => 'company-1'], true); + $quote->setRelation('serviceRate', $rate); + + return $quote; + }; + + $economy = $quote('economy'); + $limo = $quote('limo'); + $controller->from(new Point(1.2841, 103.8511)); + $controller->helper('serviceQuoteResourceCollection', [$economy, $limo]); + + $asked = Illuminate\Http\Request::create('/', 'GET', ['availability' => 1]); + $notAsked = Illuminate\Http\Request::create('/', 'GET'); + + expect($economy->meta)->toBe(['seats' => 5, 'pickup_eta' => 138]) + ->and($limo->meta)->toBe(['seats' => null, 'pickup_eta' => null]) + ->and($controller->helper('availabilityPoint', $asked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeInstanceOf(Point::class) + ->and($controller->helper('availabilityPoint', $asked, 'place_pickup'))->toBeNull() + ->and($controller->helper('availabilityPoint', $notAsked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeNull(); + + // Without a pickup, quotes are returned as they are. + $plain = $quote('economy'); + $controller->from(null); + $controller->helper('serviceQuoteResourceCollection', [$plain]); + expect($plain->meta)->toBeNull(); +}); + +/** A finished ride by rider Sam with driver Chen, from Raffles Place to Bugis. */ +function ridesSeedTrip(SQLiteConnection $connection, array $order = []): RideOffersOrder +{ + rideOffersSeedDrivers($connection); + $connection->table('users')->insert([ + ['uuid' => 'user-sam', 'public_id' => 'user_sam', 'company_uuid' => 'company-1', 'name' => 'Sam Rider', 'type' => 'customer', 'email' => 'sam@rider.test', 'phone' => '+15550190301'], + ['uuid' => 'user-chen', 'public_id' => 'user_chen', 'company_uuid' => 'company-1', 'name' => 'Chen Test', 'type' => 'driver', 'email' => 'chen@cabs.test', 'phone' => '+15550190203'], + ]); + $connection->table('drivers')->where('uuid', 'chen')->update(['user_uuid' => 'user-chen']); + $connection->table('contacts')->insert(['uuid' => 'contact-sam', 'public_id' => 'contact_sam', 'company_uuid' => 'company-1', 'user_uuid' => 'user-sam', 'name' => 'Sam Rider', 'email' => 'sam@rider.test', 'phone' => '+15550190301', 'type' => 'customer']); + $connection->table('places')->insert(['uuid' => 'place-dropoff', 'company_uuid' => 'company-1', 'name' => 'Bugis', 'location' => rideOffersWkb(103.8452, 1.3005)]); + $connection->table('payloads')->where('uuid', 'payload-1')->update(['dropoff_uuid' => 'place-dropoff']); + $connection->table('service_rates')->insert(['uuid' => 'rate-economy', 'company_uuid' => 'company-1', 'service_name' => 'Economy', 'service_type' => 'economy', 'base_fee' => 300, 'rate_calculation_method' => 'algo', 'algorithm' => 'max(200, {distance_km} * 120 + {time_min} * 20)', 'currency' => 'USD']); + $connection->table('service_quotes')->insert(['uuid' => 'quote-booked', 'company_uuid' => 'company-1', 'service_rate_uuid' => 'rate-economy', 'amount' => 533, 'currency' => 'USD']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'RIDE1', 'owner_uuid' => 'order-1']); + $connection->table('purchase_rates')->insert(['uuid' => 'purchase-booked', 'company_uuid' => 'company-1', 'service_quote_uuid' => 'quote-booked', 'payload_uuid' => 'payload-1', 'status' => 'created']); + + return rideOffersOrder($connection, array_merge([ + 'status' => 'completed', + 'started' => 1, + 'started_at' => '2026-11-06 09:00:00', + 'driver_assigned_uuid' => 'chen', + 'customer_uuid' => 'contact-sam', + 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', + 'purchase_rate_uuid' => 'purchase-booked', + 'tracking_number_uuid' => 'tn-1', + ], $order)); +} + +test('the ride chat opens once a driver accepts, with just the rider and driver in it', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + + expect(Fleetbase\FleetOps\Support\Rides\RideChat::channel($order))->toBeNull(); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $order = RideOffersOrder::where('uuid', 'order-1')->first(); + $channel = Fleetbase\FleetOps\Support\Rides\RideChat::channel($order); + $again = Fleetbase\FleetOps\Support\Rides\RideChat::channel(RideOffersOrder::where('uuid', 'order-1')->first()); + + expect($channel->meta)->toBe(['order_public_id' => 'order_ride', 'kind' => 'group']) + ->and($again->uuid)->toBe($channel->uuid) + ->and($connection->table('chat_channels')->count())->toBe(1) + ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']) + ->and(json_decode($connection->table('orders')->value('meta'), true)['chat_channel'])->toBe($channel->uuid); + + $sent = Fleetbase\FleetOps\Support\Rides\RideChat::send($channel, 'user-sam', 'By the lobby'); + $chen = $connection->table('chat_participants')->where('user_uuid', 'user-chen')->value('uuid'); + $connection->table('chat_messages')->insert(['uuid' => 'm-2', 'company_uuid' => 'company-1', 'chat_channel_uuid' => $channel->uuid, 'sender_uuid' => $chen, 'content' => 'Two minutes', 'created_at' => now()->addMinute()]); + + $messages = Fleetbase\FleetOps\Support\Rides\RideChat::messages($channel, 'user-sam'); + expect($messages->map(fn ($message) => [$message['from'], $message['text']])->all())->toBe([['rider', 'By the lobby'], ['driver', 'Two minutes']]) + ->and($messages[0]['id'])->toBe($sent->public_id ?? $sent->uuid); +}); + +test('a rider rates their driver once, and the driver keeps an average', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection); + rideOffersOrder($connection, ['uuid' => 'order-old', 'public_id' => 'order_old', 'status' => 'completed', 'driver_assigned_uuid' => 'chen', 'meta' => json_encode(['rating' => ['stars' => 4]])]); + + $first = Fleetbase\FleetOps\Support\Rides\DriverRatings::rate($order, 9, ' Great '); + $second = Fleetbase\FleetOps\Support\Rides\DriverRatings::rate(RideOffersOrder::where('uuid', 'order-1')->first(), 1); + $driver = rideOffersDriver('chen'); + + expect($first)->toBeTrue() + ->and($second)->toBeFalse() + ->and(json_decode($connection->table('orders')->where('uuid', 'order-1')->value('meta'), true)['rating'])->toMatchArray(['stars' => 5, 'comment' => 'Great']) + ->and($driver->meta['rating'])->toBe(['average' => 4.5, 'count' => 2]) + ->and(Fleetbase\FleetOps\Support\Rides\DriverRatings::average($driver))->toBe(4.5) + ->and(Fleetbase\FleetOps\Support\Rides\DriverRatings::average(rideOffersDriver('amara')))->toBeNull() + ->and(Fleetbase\FleetOps\Support\Rides\DriverRatings::average(null))->toBeNull() + ->and(Fleetbase\FleetOps\Support\Rides\DriverRatings::summary(rideOffersDriver('amara')))->toBe(['average' => null, 'count' => 0]); + + // A ride whose driver record is gone still keeps its rating. + $orphan = rideOffersOrder($connection, ['uuid' => 'order-orphan', 'public_id' => 'order_orphan', 'driver_assigned_uuid' => 'gone']); + expect(Fleetbase\FleetOps\Support\Rides\DriverRatings::rate($orphan, 3))->toBeTrue(); +}); + +test('a share link opens only its rider\'s view of its order, until it expires', function () { + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-1', 'company_uuid' => 'company-1'], true); + $sam = new Fleetbase\FleetOps\Models\Contact(); + $sam->setRawAttributes(['uuid' => 'contact-sam'], true); + $other = new Fleetbase\FleetOps\Models\Contact(); + $other->setRawAttributes(['uuid' => 'contact-other'], true); + + $scope = Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $sam); + $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam'); + $expired = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam', Carbon::now()->subMinute()); + $valid = fn ($token, $scope) => Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::valid($token, $scope); + + expect($valid($token, $scope))->toBeTrue() + ->and($valid($token, Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $other)))->toBeFalse() + ->and($valid($expired, $scope))->toBeFalse() + ->and($valid(substr($token, 0, -1) . (str_ends_with($token, '0') ? '1' : '0'), $scope))->toBeFalse() + ->and($valid('not-a-token', $scope))->toBeFalse() + ->and($valid(['array'], $scope))->toBeFalse() + ->and($valid($token, null))->toBeFalse(); +}); + +test('ride pushes say what happened, by name, to the rider only', function () { + $order = new Order(); + $order->setRawAttributes(['public_id' => 'order_ride'], true); + $driver = new Driver(); + $driver->setRawAttributes(['uuid' => 'chen'], true); + $driver->setRelation('user', null); + $order->setRelation('driverAssigned', new class extends Driver { + public function getNameAttribute() + { + return 'Chen Test'; + } + }); + + $arrived = new Fleetbase\FleetOps\Notifications\RideUpdate($order, 'arrived'); + $nobody = new Fleetbase\FleetOps\Notifications\RideUpdate((new Order())->setRawAttributes(['public_id' => 'order_x'], true), 'started'); + + expect($arrived->title)->toBe('Your driver has arrived') + ->and($arrived->message)->toBe('Chen is waiting at the pickup point.') + ->and($arrived->data)->toBe(['id' => 'order_ride', 'type' => 'ride_arrived']) + ->and($arrived->via(null))->toBe([NotificationChannels\Fcm\FcmChannel::class, NotificationChannels\Apn\ApnChannel::class]) + ->and($nobody->message)->toBe('Your driver accepted your ride.') + ->and(Fleetbase\FleetOps\Notifications\RideUpdate::knows('in_progress'))->toBeTrue() + ->and(Fleetbase\FleetOps\Notifications\RideUpdate::knows('dispatched'))->toBeFalse(); +}); + +test('each step of a ride reaches the rider, and the car about to arrive is told once', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection, ['status' => 'started']); + $updates = Fleetbase\FleetOps\Support\Rides\RideUpdates::class; + Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); + + // Status changes + $order->status = 'arrived'; + $order->save(); + $quiet = RideOffersOrder::where('uuid', 'order-1')->first(); + $notRide = new Order(); + $notRide->setRawAttributes(['type' => 'transport'], true); + expect($updates::statusChanged($order))->toBeTrue() + ->and($updates::statusChanged($quiet))->toBeFalse() + ->and($updates::statusChanged($notRide))->toBeFalse() + ->and(RideOffersRecorder::$notified)->toBe([['contact-sam', Fleetbase\FleetOps\Notifications\RideUpdate::class]]); + + $order->meta = ['dispatch_outcome' => 'no_driver_found']; + $order->status = 'canceled'; + $order->save(); + $updates::statusChanged($order); + $order->status = 'dispatched'; + $order->save(); + expect($updates::statusChanged($order))->toBeFalse() + ->and(RideOffersRecorder::$notified)->toHaveCount(2); + + // Arriving soon: only a started ride, only near the pickup, only once. + $started = RideOffersOrder::where('uuid', 'order-1')->first(); + $started->status = 'started'; + $near = rideOffersDriver('ben'); + $far = rideOffersDriver('chen'); + $nowhere = new Driver(); + expect($updates::driverMoved($near, null))->toBeFalse() + ->and($updates::driverMoved($near, $quiet->setRawAttributes(array_merge($quiet->getAttributes(), ['status' => 'arrived']))))->toBeFalse() + ->and($updates::driverMoved($far, $started))->toBeFalse() + ->and($updates::driverMoved($nowhere, $started))->toBeFalse() + ->and($updates::driverMoved($near, $started))->toBeTrue() + ->and($updates::driverMoved($near, $started))->toBeFalse(); + + // A rider who can't be reached, and a push that fails, don't break anything. + $orphan = rideOffersOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_2', 'status' => 'started', 'customer_uuid' => null]); + $orphan->status = 'arrived'; + $orphan->save(); + RideOffersRecorder::$notified = ['throw']; + $order->status = 'in_progress'; + $order->save(); + expect($updates::statusChanged($orphan))->toBeFalse() + ->and($updates::statusChanged($order))->toBeFalse() + ->and(app('log')->warnings)->toContain('Unable to send a ride update'); +}); + +test('a finished ride is priced from the distance its car covered and the trip time', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); + $connection->table('positions')->insert([ + ['uuid' => 'p0', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2700), 'created_at' => '2026-11-06 09:04:00'], + ['uuid' => 'p1', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2841), 'created_at' => '2026-11-06 09:05:10'], + ['uuid' => 'p2', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2931), 'created_at' => '2026-11-06 09:09:00'], + ['uuid' => 'p3', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8452, 1.3005), 'created_at' => '2026-11-06 09:14:00'], + ]); + + Carbon::setTestNow('2026-11-06 09:15:00'); + $fare = Fleetbase\FleetOps\Support\Rides\FinalFare::settle($order); + Carbon::setTestNow(); + + // About 1.0 km plus 1.05 km over 10 minutes: base 300, then 2.05 × 120 + 10 × 20 = 746 cents. + expect($fare['final'])->toBeTrue() + ->and($fare['distance_source'])->toBe('positions') + ->and($fare['distance_m'])->toBeGreaterThan(2000)->toBeLessThan(2100) + ->and($fare['duration_s'])->toBe(600) + ->and($fare['estimate'])->toBe(533) + ->and($fare['total'])->toBeGreaterThan(740)->toBeLessThan(750) + ->and(array_column($fare['lines'], 'label'))->toBe(['Base fare', 'Distance and time']) + ->and(json_decode($connection->table('orders')->where('uuid', 'order-1')->value('meta'), true)['fare']['total'])->toBe($fare['total']) + ->and($connection->table('service_quotes')->where('uuid', '!=', 'quote-booked')->value('amount'))->toBe((string) $fare['total']) + ->and($connection->table('service_quote_items')->count())->toBe(2) + ->and($connection->table('orders')->value('purchase_rate_uuid'))->not->toBe('purchase-booked'); + + // Priced once. + expect(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(RideOffersOrder::where('uuid', 'order-1')->first()))->toBeNull(); +}); + +test('a ride without positions is priced on the straight line, and other orders are left alone', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection); + $order->started_at = null; + + [$metres, $source] = Fleetbase\FleetOps\Support\Rides\FinalFare::distance($order, Carbon::parse('2026-11-06 09:00:00')); + $connection->table('payloads')->update(['dropoff_uuid' => null]); + [$none, $nothing] = Fleetbase\FleetOps\Support\Rides\FinalFare::distance(RideOffersOrder::where('uuid', 'order-1')->first(), Carbon::now()); + + $started = Fleetbase\FleetOps\Support\Rides\FinalFare::tripStartedAt(RideOffersOrder::where('uuid', 'order-1')->first()); + $unrated = ridesSeedOtherRate($connection); + + expect($source)->toBe('straight_line') + ->and($metres)->toBeGreaterThan(1900)->toBeLessThan(2000) + ->and([$none, $nothing])->toBe([0, 'none']) + ->and($started->toDateTimeString())->toBe('2026-11-06 09:00:00') + ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-live', 'status' => 'started', 'meta' => json_encode([])])))->toBeNull() + ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-transport', 'type' => 'transport', 'status' => 'completed'])))->toBeNull() + ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-unpriced', 'status' => 'completed', 'purchase_rate_uuid' => null])))->toBeNull() + ->and($unrated)->toBe(['Base fare', 'Distance', 'Peak']); +}); + +/** The line labels a finished ride gets on a per-km rate, and on a rate named some other way. */ +function ridesSeedOtherRate(SQLiteConnection $connection): array +{ + $label = new ReflectionMethod(Fleetbase\FleetOps\Support\Rides\FinalFare::class, 'label'); + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['rate_calculation_method' => 'per_meter'], true); + $other = new Fleetbase\FleetOps\Models\ServiceRate(); + $other->setRawAttributes(['rate_calculation_method' => 'fixed_meter'], true); + + return [$label->invoke(null, $rate, 'Base Fee', 0), $label->invoke(null, $rate, 'Service Fee', 1), $label->invoke(null, $other, 'Peak', 2)]; +} + +class RidesCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController +{ + public ?string $customerUuid = 'contact-sam'; + public array $revoked = []; + + protected function currentCustomer(): ?Fleetbase\FleetOps\Models\Contact + { + return $this->customerUuid ? Fleetbase\FleetOps\Models\Contact::where('uuid', $this->customerUuid)->first() : null; + } + + protected function findOrderOrFail(string $id): Order + { + return RideOffersOrder::where('public_id', $id)->firstOrFail(); + } + + protected function deleteUserTokens(Fleetbase\Models\User $user): void + { + $this->revoked[] = $user->uuid; + } + + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + protected function trackingPageUrl(string $number, ?string $companyUuid): string + { + return 'https://console.test/~/track/' . $number . ($companyUuid === 'company-1' ? '' : '?org=other'); + } +} + +function ridesJson($response): array +{ + return $response->getData(true); +} + +test('the rider chats with the driver of their own ride only, as themselves', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + $controller = new RidesCustomerController(); + $send = fn (string $text, string $id = 'order_ride') => $controller->sendOrderMessage($id, Illuminate\Http\Request::create('/', 'POST', ['text' => $text])); + + expect($controller->orderMessages('order_missing')->getStatusCode())->toBe(404) + ->and(ridesJson($controller->orderMessages('order_ride')))->toBe([]) + ->and($send('Hi', 'order_missing')->getStatusCode())->toBe(404) + ->and($send(' ')->getStatusCode())->toBe(422) + ->and($send(str_repeat('x', 2001))->getStatusCode())->toBe(422) + ->and(ridesJson($send('Hi'))['error'])->toContain('once they accept'); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $sent = $send('By the lobby'); + + expect($sent->getStatusCode())->toBe(201) + ->and(ridesJson($sent))->toMatchArray(['from' => 'rider', 'text' => 'By the lobby']) + ->and(array_column(ridesJson($controller->orderMessages('order_ride')), 'text'))->toBe(['By the lobby']); + + $connection->table('orders')->update(['status' => 'completed']); + expect(ridesJson($send('Thanks'))['error'])->toBe('This ride has ended.'); +}); + +test('the rider rates a finished ride once, from 1 to 5 stars', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection, ['status' => 'in_progress']); + $controller = new RidesCustomerController(); + $rate = fn ($stars, string $id = 'order_ride') => $controller->rateOrder($id, Illuminate\Http\Request::create('/', 'POST', ['stars' => $stars, 'comment' => 'Kind'])); + + expect($rate(5, 'order_missing')->getStatusCode())->toBe(404) + ->and($rate(0)->getStatusCode())->toBe(422) + ->and($rate(2.5)->getStatusCode())->toBe(422) + ->and($rate('lots')->getStatusCode())->toBe(422) + ->and(ridesJson($rate(5))['error'])->toBe('Only a finished ride can be rated.'); + + $connection->table('orders')->update(['status' => 'completed']); + expect(ridesJson($rate(4)))->toBe(['status' => 'rated']) + ->and($rate(1)->getStatusCode())->toBe(409); +}); + +test('the rider shares a ride in progress, and reads the operator settings', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection, ['status' => 'started']); + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + config()->set('fleetbase.console.host', 'https://console.test'); + $controller = new RidesCustomerController(); + + $shared = ridesJson($controller->shareOrder('order_ride')); + expect($controller->shareOrder('order_missing')->getStatusCode())->toBe(404) + ->and($shared['url'])->toContain('/~/track/RIDE1') + ->and($shared['url'])->toMatch('/[?&]share=\d+\.[a-f0-9]{64}$/'); + + $connection->table('orders')->update(['tracking_number_uuid' => null]); + expect($controller->shareOrder('order_ride')->getStatusCode())->toBe(422) + ->and(ridesJson($controller->rideSettings()))->toBe(['emergency_number' => null, 'support' => ['phone' => null, 'email' => null]]); + + $connection->table('order_configs')->update(['meta' => json_encode(['rider' => ['emergency_number' => '995', 'support_email' => 'help@cabs.test']])]); + expect(ridesJson($controller->rideSettings()))->toBe(['emergency_number' => '995', 'support' => ['phone' => null, 'email' => 'help@cabs.test']]); +}); + +test('a rider deletes their account, but not in the middle of a ride', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection, ['status' => 'started']); + $connection->table('places')->insert(['uuid' => 'place-home', 'company_uuid' => 'company-1', 'name' => 'Home', 'owner_uuid' => 'contact-sam']); + $controller = new RidesCustomerController(); + + expect(ridesJson($controller->deleteMe())['error'])->toContain('Finish or cancel your ride'); + + $connection->table('orders')->update(['status' => 'completed']); + expect(ridesJson($controller->deleteMe()))->toBe(['status' => 'deleted']) + ->and($controller->revoked)->toBe(['user-sam']) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->first())->toMatchArray(['name' => 'Deleted rider', 'email' => null, 'phone' => null]) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('places')->where('uuid', 'place-home')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->first())->toMatchArray(['name' => 'Deleted rider', 'phone' => null, 'email' => 'deleted-user-sam@deleted.invalid']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('deleted_at'))->toBeNull(); + + $controller->customerUuid = null; + expect($controller->deleteMe()->getStatusCode())->toBe(401); +}); + +test('a rider with another company keeps their user when one account is deleted', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection); + $connection->table('contacts')->insert(['uuid' => 'contact-sam-2', 'company_uuid' => 'company-2', 'user_uuid' => 'user-sam', 'name' => 'Sam Rider', 'type' => 'customer']); + $nobody = new RidesCustomerController(); + $connection->table('contacts')->insert(['uuid' => 'contact-guest', 'company_uuid' => 'company-1', 'name' => 'Guest', 'type' => 'customer']); + $nobody->customerUuid = 'contact-guest'; + + (new RidesCustomerController())->deleteMe(); + $nobody->deleteMe(); + + expect($connection->table('users')->where('uuid', 'user-sam')->value('deleted_at'))->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->value('name'))->toBe('Sam Rider') + ->and($nobody->revoked)->toBe([]) + ->and($connection->table('contacts')->where('uuid', 'contact-guest')->value('deleted_at'))->not->toBeNull(); +}); + +test('an unpaid card trip blocks the next booking, and cash never does', function () { + $connection = rideOffersBoot(); + ridesSeedTrip($connection, ['meta' => json_encode(['payment' => 'card', 'fare' => ['final' => true]])]); + $controller = new RidesCustomerController(); + $sam = Fleetbase\FleetOps\Models\Contact::where('uuid', 'contact-sam')->first(); + + $unpaid = $controller->helper('hasUnpaidRide', $sam); + $connection->table('orders')->update(['meta' => json_encode(['payment' => 'card', 'fare' => ['final' => true], 'paid_at' => '2026-11-06'])]); + $paid = $controller->helper('hasUnpaidRide', $sam); + $connection->table('orders')->update(['meta' => json_encode(['payment' => 'cash', 'fare' => ['final' => true]])]); + $cash = $controller->helper('hasUnpaidRide', $sam); + + expect([$unpaid, $paid, $cash])->toBe([true, false, false]); +}); + +test('when a ride is completed the rider is told and the ride is priced', function () { + $connection = rideOffersBoot(); + $order = ridesSeedTrip($connection, ['status' => 'in_progress']); + Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); + + $order->status = 'completed'; + $order->save(); + (new Fleetbase\FleetOps\Observers\OrderObserver())->updated($order); + + expect(json_decode($connection->table('orders')->value('meta'), true)['fare']['final'])->toBeTrue() + ->and(RideOffersRecorder::$notified)->toBe([['contact-sam', Fleetbase\FleetOps\Notifications\RideUpdate::class]]); +}); From 63fe08e8d6f69c2d8fb1356982abfa5e6348c99e Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 11:16:04 +0800 Subject: [PATCH 14/29] style: php-cs-fixer --- server/tests/ModelAccessorContractsTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/tests/ModelAccessorContractsTest.php b/server/tests/ModelAccessorContractsTest.php index a8c9ef9cc..d0342e215 100644 --- a/server/tests/ModelAccessorContractsTest.php +++ b/server/tests/ModelAccessorContractsTest.php @@ -1564,7 +1564,7 @@ public function raw($value): Illuminate\Database\Query\Expression ->and($imported->volume)->toBe('45.5') ->and($imported->metric_unit)->toBe('gal') ->and($imported->status)->toBe('approved') - ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar(new Illuminate\Database\SQLiteConnection(new PDO('sqlite::memory:')))))->toContain('POINT'); + ->and($imported->location->getValue(new Illuminate\Database\Query\Grammars\Grammar(new SQLiteConnection(new PDO('sqlite::memory:')))))->toContain('POINT'); }); test('fuel provider transaction accessors expose related names and station points', function () { From ae72171bc71d829b795e8819ad5375b029a605fc Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 11:16:13 +0800 Subject: [PATCH 15/29] refactor(dispatch): adhoc dispatch strategies, with one-at-a-time offers by default Timed offers were switched on by an order config meta key and only covered rider orders. Offering is now a dispatch strategy for every adhoc order. - `AdhocDispatchStrategy` contract with `broadcast` (every nearby driver at once) and `sequential` (one at a time, nearest first, with a timeout and "No driver found"). `AdhocDispatch::register()` adds more. - Sequential is the default. An order uses its own `adhoc_strategy`, else its config's, else the company's `fleetops.adhoc_strategy` option. - Both strategies record offers, so decline works for any adhoc order (a broadcast decline stops that driver being offered it again), and on accept everyone else's offer is withdrawn. - `HandleOrderDispatched` and `fleetops:dispatch-adhoc` hand adhoc orders to the strategy. Nearby drivers come from `DriverMatching::nearby()`. - Settings are columns, not meta. Orders get `adhoc_strategy` and `required_vehicle_type`, accepted on the order API and returned in its resource. Order configs get `adhoc_strategy`, `adhoc_offer_timeout`, `customer_orders_adhoc` and `match_vehicle_type`. - The rider route makes orders adhoc and sets their vehicle type from those config columns, instead of from the offers switch. --- ...1_06_000002_add_adhoc_dispatch_columns.php | 41 ++ .../Console/Commands/DispatchAdhocOrders.php | 123 +----- .../src/Contracts/AdhocDispatchStrategy.php | 44 +++ .../Controllers/Api/v1/CustomerController.php | 46 +-- .../Controllers/Api/v1/OrderController.php | 18 +- .../src/Http/Requests/CreateOrderRequest.php | 28 +- .../Requests/Internal/CreateOrderRequest.php | 30 +- server/src/Http/Resources/v1/Order.php | 2 + server/src/Http/Resources/v1/OrderConfig.php | 32 +- server/src/Jobs/ExpireOrderOffer.php | 4 +- .../src/Listeners/HandleOrderDispatched.php | 83 +---- server/src/Models/Order.php | 4 +- server/src/Models/OrderConfig.php | 32 +- .../Support/AdhocDispatch/AdhocDispatch.php | 94 +++++ .../AdhocDispatch/BroadcastStrategy.php | 81 ++++ .../AdhocDispatch/SequentialStrategy.php | 118 ++++++ server/src/Support/DriverMatching.php | 32 +- server/src/Support/FleetOps.php | 14 +- server/src/Support/OrderOffers.php | 156 +++----- .../ApiCustomerControllerContractsTest.php | 9 +- server/tests/CommandContractsTest.php | 128 +++---- .../tests/DriverVehicleStatusDefaultTest.php | 2 +- .../Api/OrderControllerStartActivityTest.php | 21 +- server/tests/Feature/RidesTest.php | 350 +++++++++++------- .../OrderDispatchListenerContractsTest.php | 57 +-- .../HandleOrderDispatchedConcreteTest.php | 32 +- .../HandleOrderDispatchedHelpersTest.php | 26 +- server/tests/Unit/Support/QuerySeamsTest.php | 13 +- 28 files changed, 898 insertions(+), 722 deletions(-) create mode 100644 server/migrations/2026_11_06_000002_add_adhoc_dispatch_columns.php create mode 100644 server/src/Contracts/AdhocDispatchStrategy.php create mode 100644 server/src/Support/AdhocDispatch/AdhocDispatch.php create mode 100644 server/src/Support/AdhocDispatch/BroadcastStrategy.php create mode 100644 server/src/Support/AdhocDispatch/SequentialStrategy.php diff --git a/server/migrations/2026_11_06_000002_add_adhoc_dispatch_columns.php b/server/migrations/2026_11_06_000002_add_adhoc_dispatch_columns.php new file mode 100644 index 000000000..5e05ce54c --- /dev/null +++ b/server/migrations/2026_11_06_000002_add_adhoc_dispatch_columns.php @@ -0,0 +1,41 @@ +string('adhoc_strategy', 32)->nullable()->after('adhoc_distance'); + $table->string('required_vehicle_type')->nullable()->after('adhoc_strategy'); + }); + + Schema::table('order_configs', function (Blueprint $table) { + $table->string('adhoc_strategy', 32)->nullable(); + $table->unsignedSmallInteger('adhoc_offer_timeout')->nullable(); + $table->boolean('customer_orders_adhoc')->default(false); + $table->boolean('match_vehicle_type')->default(false); + }); + } + + public function down(): void + { + Schema::table('orders', function (Blueprint $table) { + $table->dropColumn(['adhoc_strategy', 'required_vehicle_type']); + }); + + Schema::table('order_configs', function (Blueprint $table) { + $table->dropColumn(['adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type']); + }); + } +}; diff --git a/server/src/Console/Commands/DispatchAdhocOrders.php b/server/src/Console/Commands/DispatchAdhocOrders.php index 2fff37810..5d4e9bf3f 100644 --- a/server/src/Console/Commands/DispatchAdhocOrders.php +++ b/server/src/Console/Commands/DispatchAdhocOrders.php @@ -2,15 +2,10 @@ namespace Fleetbase\FleetOps\Console\Commands; -use Fleetbase\FleetOps\Models\Driver; +use Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy; use Fleetbase\FleetOps\Models\Order; -use Fleetbase\FleetOps\Models\OrderOffer; -use Fleetbase\FleetOps\Notifications\OrderPing; -use Fleetbase\FleetOps\Support\DriverMatching; -use Fleetbase\FleetOps\Support\NavigatorReview; -use Fleetbase\FleetOps\Support\OrderOffers; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\Utils; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Console\Command; use Illuminate\Database\Eloquent\Collection; use Illuminate\Support\Carbon; @@ -32,7 +27,7 @@ class DispatchAdhocOrders extends Command * * @var string */ - protected $description = 'Dispatch & ping ad-hoc orders without assigned drivers (within a recent time window)'; + protected $description = 'Offer ad-hoc orders still without a driver again, through each order\'s dispatch strategy (within a recent time window)'; /** * Execute the console command. @@ -60,38 +55,25 @@ public function handle(): void $this->table(['Order', 'Dispatched At'], $orders->map(fn ($order) => [$order->public_id, $order->dispatched_at])); foreach ($orders as $order) { - // Orders with timed offers go to one driver at a time, so only a stuck offer is moved on here. - if ($this->usesTimedOffers($order)) { - $this->advanceOffers($order); - continue; - } - - $pickup = $order->getPickupLocation(); - $distance = $order->getAdhocPingDistance(); - - if (!Utils::isPoint($pickup)) { - $this->error('Invalid pickup location for order ' . $order->public_id); - continue; - } - - $drivers = $this->getNearbyDriversForOrder($order, $pickup, $distance, $testingMode); - - $this->line('Checking order ' . $order->public_id . ' for nearby drivers within ' . $distance . ' meters.'); + $strategy = $this->strategyFor($order); + $offered = $strategy->redispatch($order, $testingMode); - if ($drivers->count()) { - // Dispatching again would fire OrderDispatched, whose listener pings every driver a second time. - $this->markPinged($order); - $this->info('Order ' . $order->public_id . ' dispatched successfully to ' . $drivers->count() . ' nearby drivers.'); - foreach ($drivers as $driver) { - $this->info('Pinging driver ' . $driver->name . ' (' . $driver->public_id . ') ...'); - $driver->notify(new OrderPing($order, $distance)); - } + if ($offered) { + $this->info('Order ' . $order->public_id . ' offered to ' . $offered . ' driver(s) (' . $strategy->name() . ').'); } else { - $this->warn('No available drivers found for order ' . $order->public_id); + $this->line('No new offer for order ' . $order->public_id . ' (' . $strategy->name() . ').'); } } } + /** + * The strategy that offers the order to drivers. + */ + protected function strategyFor(Order $order): AdhocDispatchStrategy + { + return AdhocDispatch::for($order); + } + /** * Retrieve a collection of dispatchable orders created or dispatched within the last N days. * @@ -131,81 +113,8 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i ->get(); } - /** - * Fetch nearby drivers for a given order. - */ - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): Collection - { - $driverQuery = $this->newDriverQuery() - ->where(['online' => 1]) - ->where(function ($q) use ($order) { - $q->where('company_uuid', $order->company_uuid) - ->orWhereHas('user', fn ($q) => $q->where('company_uuid', $order->company_uuid)); - }) - ->whereNull('deleted_at') - ->withoutGlobalScopes(); - - // An app store reviewer's driver is never offered a real order. - NavigatorReview::excludeFrom($driverQuery); - - if (!$testing) { - $driverQuery->whereNotNull('location')->whereRaw(' - ST_Y(location) BETWEEN -90 AND 90 - AND ST_X(location) BETWEEN -180 AND 180 - AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0) - '); - $driverQuery->distanceSphere('location', $pickup, $distance); - $driverQuery->distanceSphereValue('location', $pickup); - } - - return $this->matchDrivers($driverQuery, $order)->get(); - } - - /** - * Leave out drivers already on another job and drivers of another vehicle class. - */ - protected function matchDrivers($driverQuery, Order $order) - { - DriverMatching::notBusy($driverQuery); - - return DriverMatching::forVehicleClass($driverQuery, DriverMatching::vehicleClass($order)); - } - - /** - * Restart the order's re-ping interval without dispatching it again. - */ - protected function markPinged(Order $order): void - { - $order->forceFill(['dispatched_at' => Carbon::now()])->saveQuietly(); - } - - protected function usesTimedOffers(Order $order): bool - { - return (bool) $order->config()?->usesTimedOffers(); - } - - /** - * Close an offer whose expiry job was lost, or start offers that never began. - */ - protected function advanceOffers(Order $order): void - { - $pending = OrderOffers::pending($order); - if ($pending && $pending->expires_at?->isPast()) { - OrderOffers::expire($pending); - $this->info('Moved order ' . $order->public_id . ' to the next driver.'); - } elseif (!$pending && !OrderOffer::where('order_uuid', $order->uuid)->exists()) { - OrderOffers::start($order); - $this->info('Started offers for order ' . $order->public_id . '.'); - } - } - protected function newOrderQuery(string $connection) { return Order::on($connection); } - - protected function newDriverQuery() - { - return Driver::query(); - } } diff --git a/server/src/Contracts/AdhocDispatchStrategy.php b/server/src/Contracts/AdhocDispatchStrategy.php new file mode 100644 index 000000000..6b901239a --- /dev/null +++ b/server/src/Contracts/AdhocDispatchStrategy.php @@ -0,0 +1,44 @@ +apiError('This fare has expired. Please get a new one.', 422); } - // A ride is priced and matched by the class the rider picked, so it needs a fare. - $isRide = $orderConfig->usesTimedOffers(); - if ($isRide && !$serviceQuote instanceof ServiceQuote) { + // A config that matches customer orders by vehicle type needs a fare, which says the type. + $byVehicleType = (bool) $orderConfig->match_vehicle_type; + if ($byVehicleType && !$serviceQuote instanceof ServiceQuote) { return response()->apiError('Choose a ride option first.', 422); } - if ($isRide && $this->hasUnpaidRide($customer)) { + if ($orderConfig->key === 'ride' && $this->hasUnpaidRide($customer)) { return response()->apiError('Pay for your last trip before you book another.', 402); } - // Keys the server sets can't come from the rider. - $meta = Arr::except((array) $request->input('meta', []), static::RESERVED_ORDER_META); - if ($isRide) { - $meta['vehicle_class'] = $serviceQuote->serviceRate?->service_type; - $meta['service_name'] = $serviceQuote->serviceRate?->service_name; + // Keys the server sets can't come from the customer. + $meta = Arr::except((array) $request->input('meta', []), static::RESERVED_ORDER_META); + $vehicleType = null; + if ($byVehicleType) { + $vehicleType = $serviceQuote->serviceRate?->service_type; + $meta['service_name'] = $serviceQuote->serviceRate?->service_name; } // Build the Payload (matching the operator OrderController convention). @@ -879,18 +880,19 @@ public function createOrder(CreateCustomerOrderRequest $request) } $order = $this->createOrderRecord([ - 'company_uuid' => $sessionCompany, - 'customer_uuid' => $customer->uuid, - 'customer_type' => $this->getModelClassName('contact'), - 'payload_uuid' => $payloadUuid, - 'order_config_uuid' => $orderConfig->uuid, - 'type' => $orderConfig->key, - 'status' => 'created', - 'scheduled_at' => $request->input('scheduled_at'), - 'notes' => $request->input('notes'), - 'internal_id' => $request->input('internal_id'), - 'adhoc' => $isRide, - 'meta' => $meta, + 'company_uuid' => $sessionCompany, + 'customer_uuid' => $customer->uuid, + 'customer_type' => $this->getModelClassName('contact'), + 'payload_uuid' => $payloadUuid, + 'order_config_uuid' => $orderConfig->uuid, + 'type' => $orderConfig->key, + 'status' => 'created', + 'scheduled_at' => $request->input('scheduled_at'), + 'notes' => $request->input('notes'), + 'internal_id' => $request->input('internal_id'), + 'adhoc' => (bool) $orderConfig->customer_orders_adhoc, + 'required_vehicle_type' => $vehicleType, + 'meta' => $meta, ]); // If the customer picked a ServiceQuote up front, consume it now to diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index 025614430..93be2e351 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -25,6 +25,7 @@ use Fleetbase\FleetOps\Models\Proof; use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\Waypoint; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\OrderEdit; use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\ResolvesOrderServiceStops; @@ -717,7 +718,7 @@ protected function orderCreateInputFromRequest(Request $request): array { return $request->only([ 'internal_id', 'payload', 'service_quote', 'purchase_rate', - 'adhoc', 'adhoc_distance', 'pod_method', 'pod_required', + 'adhoc', 'adhoc_distance', 'adhoc_strategy', 'required_vehicle_type', 'pod_method', 'pod_required', 'scheduled_at', 'status', 'meta', 'notes', // Orchestrator constraints 'time_window_start', 'time_window_end', @@ -728,7 +729,7 @@ protected function orderCreateInputFromRequest(Request $request): array protected function orderUpdateInputFromRequest(Request $request): array { return $request->only([ - 'internal_id', 'payload', 'adhoc', 'adhoc_distance', + 'internal_id', 'payload', 'adhoc', 'adhoc_distance', 'adhoc_strategy', 'required_vehicle_type', 'pod_method', 'pod_required', 'scheduled_at', 'meta', 'type', 'status', 'notes', // Orchestrator constraints 'time_window_start', 'time_window_end', @@ -1229,8 +1230,9 @@ protected function claimAdhocOrder(Order $order, string $driverId): mixed return response()->apiError('Go online to accept orders.', 422); } - $orderConfig = $order->config(); - if ($orderConfig->usesTimedOffers() && !OrderOffers::accept($order, $driver)) { + // The order's dispatch strategy decides who may accept it, for example only the driver + // with the open offer. + if (!AdhocDispatch::for($order)->accept($order, $driver)) { return response()->apiError('This order is no longer offered to you.', 409); } @@ -1249,11 +1251,15 @@ protected function claimAdhocOrder(Order $order, string $driverId): mixed $order->driver_assigned_uuid = null; $order->assignDriver($driver, true); + // Everyone else's offer is withdrawn. + OrderOffers::claimed($order, $driver); + return null; } /** - * Turn down an order offered to the driver, so it goes to the next driver. + * Turn down an adhoc order. It isn't offered to the driver again, and with one-at-a-time + * offers it goes to the next driver. */ public function declineOrder(string $id, Request $request) { @@ -1273,7 +1279,7 @@ public function declineOrder(string $id, Request $request) return response()->apiError('Driver not found.', 404); } - if (!OrderOffers::decline($order, $driver)) { + if (!$order->adhoc || $order->driver_assigned_uuid || !AdhocDispatch::for($order)->decline($order, $driver)) { return response()->apiError('This order is not offered to you.', 409); } diff --git a/server/src/Http/Requests/CreateOrderRequest.php b/server/src/Http/Requests/CreateOrderRequest.php index e110627db..de9aa839c 100644 --- a/server/src/Http/Requests/CreateOrderRequest.php +++ b/server/src/Http/Requests/CreateOrderRequest.php @@ -26,19 +26,21 @@ public function rules(): array $podMethods = is_array($podMethods) ? implode(',', $podMethods) : (string) $podMethods; $validations = [ - 'adhoc' => ['nullable', 'boolean'], - 'dispatch' => ['nullable', 'boolean'], - 'adhoc_distance' => ['nullable', 'numeric'], - 'pod_required' => ['nullable', 'boolean'], - 'pod_method' => ['nullable', 'in:' . $podMethods], - 'scheduled_at' => ['nullable', 'date'], - 'driver' => ['nullable', 'exists:drivers,public_id'], - 'service_quote' => ['nullable', 'exists:service_quotes,public_id'], - 'purchase_rate' => ['nullable', 'exists:purchase_rates,public_id'], - 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['public_id', 'provider'])], - 'customer' => ['nullable', new CustomerIdOrDetails(['vendors', 'contacts'], 'public_id')], - 'status' => ['nullable', 'string'], - 'type' => ['string'], + 'adhoc' => ['nullable', 'boolean'], + 'dispatch' => ['nullable', 'boolean'], + 'adhoc_distance' => ['nullable', 'numeric'], + 'adhoc_strategy' => ['nullable', 'string', 'in:' . implode(',', \Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch::names())], + 'required_vehicle_type' => ['nullable', 'string', 'max:191'], + 'pod_required' => ['nullable', 'boolean'], + 'pod_method' => ['nullable', 'in:' . $podMethods], + 'scheduled_at' => ['nullable', 'date'], + 'driver' => ['nullable', 'exists:drivers,public_id'], + 'service_quote' => ['nullable', 'exists:service_quotes,public_id'], + 'purchase_rate' => ['nullable', 'exists:purchase_rates,public_id'], + 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['public_id', 'provider'])], + 'customer' => ['nullable', new CustomerIdOrDetails(['vendors', 'contacts'], 'public_id')], + 'status' => ['nullable', 'string'], + 'type' => ['string'], ]; // Conditionally require 'pod_method' if 'pod_required' is truthy diff --git a/server/src/Http/Requests/Internal/CreateOrderRequest.php b/server/src/Http/Requests/Internal/CreateOrderRequest.php index 7b5466857..c3f142067 100644 --- a/server/src/Http/Requests/Internal/CreateOrderRequest.php +++ b/server/src/Http/Requests/Internal/CreateOrderRequest.php @@ -26,20 +26,22 @@ public function rules(): array $podMethods = is_array($podMethods) ? implode(',', $podMethods) : (string) $podMethods; $validations = [ - 'order_config_uuid' => ['required'], - 'adhoc' => ['nullable', 'boolean'], - 'dispatch' => ['nullable', 'boolean'], - 'adhoc_distance' => ['nullable', 'numeric'], - 'pod_required' => ['nullable', 'boolean'], - 'pod_method' => ['nullable', 'in:' . $podMethods], - 'scheduled_at' => ['nullable', 'date'], - 'driver' => ['nullable', 'exists:drivers,uuid'], - 'service_quote' => ['nullable', 'exists:service_quotes,uuid'], - 'purchase_rate' => ['nullable', 'exists:purchase_rates,uuid'], - 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['uuid', 'provider'])], - 'customer' => ['nullable', new ExistsInAny(['vendors', 'contacts'], 'uuid')], - 'status' => ['nullable', 'string'], - 'type' => ['string'], + 'order_config_uuid' => ['required'], + 'adhoc' => ['nullable', 'boolean'], + 'dispatch' => ['nullable', 'boolean'], + 'adhoc_distance' => ['nullable', 'numeric'], + 'adhoc_strategy' => ['nullable', 'string', 'in:' . implode(',', \Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch::names())], + 'required_vehicle_type' => ['nullable', 'string', 'max:191'], + 'pod_required' => ['nullable', 'boolean'], + 'pod_method' => ['nullable', 'in:' . $podMethods], + 'scheduled_at' => ['nullable', 'date'], + 'driver' => ['nullable', 'exists:drivers,uuid'], + 'service_quote' => ['nullable', 'exists:service_quotes,uuid'], + 'purchase_rate' => ['nullable', 'exists:purchase_rates,uuid'], + 'facilitator' => ['nullable', new ExistsInAny(['vendors', 'contacts', 'integrated_vendors'], ['uuid', 'provider'])], + 'customer' => ['nullable', new ExistsInAny(['vendors', 'contacts'], 'uuid')], + 'status' => ['nullable', 'string'], + 'type' => ['string'], ]; // Conditionally require 'pod_method' if 'pod_required' is truthy diff --git a/server/src/Http/Resources/v1/Order.php b/server/src/Http/Resources/v1/Order.php index 6ed174612..d9bc4ff7d 100644 --- a/server/src/Http/Resources/v1/Order.php +++ b/server/src/Http/Resources/v1/Order.php @@ -88,6 +88,8 @@ public function toArray($request): array 'started' => (bool) data_get($this, 'started', false), 'adhoc' => (bool) data_get($this, 'adhoc', false), 'adhoc_distance' => (int) $this->getAdhocDistance(), + 'adhoc_strategy' => $this->adhoc_strategy, + 'required_vehicle_type' => $this->required_vehicle_type, 'distance' => (int) $this->distance, 'time' => (int) $this->time, 'transaction_amount' => $this->transaction_amount, diff --git a/server/src/Http/Resources/v1/OrderConfig.php b/server/src/Http/Resources/v1/OrderConfig.php index 7b52fa2e9..99c8d54c4 100644 --- a/server/src/Http/Resources/v1/OrderConfig.php +++ b/server/src/Http/Resources/v1/OrderConfig.php @@ -23,20 +23,24 @@ class OrderConfig extends FleetbaseResource public function toArray($request): array { return [ - 'id' => $this->when(Http::isInternalRequest(), $this->id, $this->public_id), - 'uuid' => $this->when(Http::isInternalRequest(), $this->uuid), - 'public_id' => $this->when(Http::isInternalRequest(), $this->public_id), - 'company_uuid' => $this->when(Http::isInternalRequest(), $this->company_uuid), - 'key' => $this->key, - 'name' => $this->name, - 'namespace' => $this->namespace, - 'description' => $this->description, - 'tags' => $this->tags, - 'status' => $this->status, - 'version' => $this->version, - 'flow' => $this->projectFlow(), - 'created_at' => $this->created_at, - 'updated_at' => $this->updated_at, + 'id' => $this->when(Http::isInternalRequest(), $this->id, $this->public_id), + 'uuid' => $this->when(Http::isInternalRequest(), $this->uuid), + 'public_id' => $this->when(Http::isInternalRequest(), $this->public_id), + 'company_uuid' => $this->when(Http::isInternalRequest(), $this->company_uuid), + 'key' => $this->key, + 'name' => $this->name, + 'namespace' => $this->namespace, + 'description' => $this->description, + 'tags' => $this->tags, + 'status' => $this->status, + 'version' => $this->version, + 'flow' => $this->projectFlow(), + 'adhoc_strategy' => $this->adhoc_strategy, + 'adhoc_offer_timeout' => $this->adhoc_offer_timeout, + 'customer_orders_adhoc' => (bool) $this->customer_orders_adhoc, + 'match_vehicle_type' => (bool) $this->match_vehicle_type, + 'created_at' => $this->created_at, + 'updated_at' => $this->updated_at, ]; } diff --git a/server/src/Jobs/ExpireOrderOffer.php b/server/src/Jobs/ExpireOrderOffer.php index 73b0891a1..2af7d423f 100644 --- a/server/src/Jobs/ExpireOrderOffer.php +++ b/server/src/Jobs/ExpireOrderOffer.php @@ -3,7 +3,7 @@ namespace Fleetbase\FleetOps\Jobs; use Fleetbase\FleetOps\Models\OrderOffer; -use Fleetbase\FleetOps\Support\OrderOffers; +use Fleetbase\FleetOps\Support\AdhocDispatch\SequentialStrategy; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; @@ -29,6 +29,6 @@ public function handle(): bool { $offer = OrderOffer::where('uuid', $this->offerUuid)->first(); - return $offer ? OrderOffers::expire($offer) : false; + return $offer ? app(SequentialStrategy::class)->expire($offer) : false; } } diff --git a/server/src/Listeners/HandleOrderDispatched.php b/server/src/Listeners/HandleOrderDispatched.php index a03c02e69..cb4747ac0 100644 --- a/server/src/Listeners/HandleOrderDispatched.php +++ b/server/src/Listeners/HandleOrderDispatched.php @@ -5,13 +5,9 @@ use Fleetbase\FleetOps\Events\OrderDispatched; use Fleetbase\FleetOps\Events\OrderDispatchFailed; use Fleetbase\FleetOps\Models\Driver; -use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Notifications\OrderDispatched as OrderDispatchedNotification; -use Fleetbase\FleetOps\Notifications\OrderPing; -use Fleetbase\FleetOps\Support\DriverMatching; -use Fleetbase\FleetOps\Support\OrderOffers; -use Fleetbase\FleetOps\Support\Utils; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Support\Carbon; @@ -63,29 +59,9 @@ public function handle(OrderDispatched $event) $order->save(); $order->flushAttributesCache(); - /* if order is adhoc ping drivers within radius of pickup to accept order * */ + // An adhoc order is offered to drivers by its dispatch strategy. if ($order->adhoc) { - // A config with timed offers goes to one driver at a time instead of everyone nearby. - if ($this->usesTimedOffers($order)) { - return $this->startOffers($order); - } - - $order->load(['company']); - $pickup = $order->getPickupLocation(); - $distance = $order->getAdhocDistance(); - if (!Utils::isPoint($pickup)) { - return; - } - - $drivers = $this->nearbyAvailableDrivers($pickup, $distance, $order); - - return $drivers->each(function ($driver) use ($order) { - try { - $this->notifyAdhocDriver($driver, $order); - } catch (\Exception $exception) { - // failed to notify driver for order dispatch for reason uknown -- exit silently - } - }); + return $this->dispatchAdhoc($order); } /** @var \Fleetbase\Models\Driver */ @@ -103,6 +79,13 @@ public function handle(OrderDispatched $event) } } + protected function dispatchAdhoc($order): mixed + { + AdhocDispatch::for($order)->dispatch($order); + + return null; + } + protected function dispatchFailed($order, string $reason): mixed { return event(new OrderDispatchFailed($order, $reason)); @@ -118,52 +101,6 @@ protected function getDispatchActivity($order): mixed return $order->config()?->getDispatchActivity(); } - protected function usesTimedOffers($order): bool - { - return (bool) $order->config()?->usesTimedOffers(); - } - - protected function startOffers($order): mixed - { - return OrderOffers::start($order); - } - - /** - * Drivers to ping for the order: of its company, not on another job, and of its vehicle class. - */ - protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) - { - $query = Driver::where(['status' => 'available', 'online' => 1]) - ->whereHas('company', function ($q) { - $q->whereHas('users', function ($q) { - $q->whereHas('driver', function ($q) { - $q->where(['status' => 'available', 'online' => 1]); - $q->whereNull('deleted_at'); - }); - }); - }) - ->whereNull('deleted_at') - ->whereNotNull('location')->whereRaw(' - ST_Y(location) BETWEEN -90 AND 90 - AND ST_X(location) BETWEEN -180 AND 180 - AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0) - ') - ->distanceSphere('location', $pickup, $distance) - ->distanceSphereValue('location', $pickup) - ->withoutGlobalScopes(); - - if ($order) { - DriverMatching::forOrder($query, $order); - } - - return $query->get(); - } - - protected function notifyAdhocDriver(Driver $driver, $order): void - { - $driver->notify(new OrderPing($order, $driver->distance)); - } - protected function findAssignedDriver($order): ?Driver { return Driver::where('uuid', $order->driver_assigned_uuid)->withoutGlobalScopes()->first(); diff --git a/server/src/Models/Order.php b/server/src/Models/Order.php index 14f628269..52e44df8f 100644 --- a/server/src/Models/Order.php +++ b/server/src/Models/Order.php @@ -116,6 +116,8 @@ class Order extends Model 'dispatched', 'adhoc', 'adhoc_distance', + 'adhoc_strategy', + 'required_vehicle_type', 'started', 'started_at', 'pod_method', @@ -1512,7 +1514,7 @@ public function cancelWithReason(?string $reason = null) if ($this->driver_assigned_uuid) { Driver::withoutGlobalScopes()->where(['uuid' => $this->driver_assigned_uuid, 'current_job_uuid' => $this->uuid])->update(['current_job_uuid' => null]); } - if ($orderConfig->usesTimedOffers()) { + if ($this->adhoc) { OrderOffers::withdraw($this); } diff --git a/server/src/Models/OrderConfig.php b/server/src/Models/OrderConfig.php index a7cc181dc..18c222f44 100644 --- a/server/src/Models/OrderConfig.php +++ b/server/src/Models/OrderConfig.php @@ -68,6 +68,10 @@ class OrderConfig extends Model 'flow', 'entities', 'meta', + 'adhoc_strategy', + 'adhoc_offer_timeout', + 'customer_orders_adhoc', + 'match_vehicle_type', ]; /** @@ -76,10 +80,13 @@ class OrderConfig extends Model * @var array */ protected $casts = [ - 'tags' => Json::class, - 'flow' => Json::class, - 'entities' => OrderConfigEntities::class, - 'meta' => Json::class, + 'tags' => Json::class, + 'flow' => Json::class, + 'entities' => OrderConfigEntities::class, + 'meta' => Json::class, + 'adhoc_offer_timeout' => 'integer', + 'customer_orders_adhoc' => 'boolean', + 'match_vehicle_type' => 'boolean', ]; /** @@ -442,23 +449,6 @@ public function allowsDispatch(): bool return !in_array($dispatch, [false, 'false', 0, '0'], true); } - /** - * Whether orders using this config are offered to one driver at a time (`meta.offers.enabled`) - * rather than pinged to every nearby driver at once. - */ - public function usesTimedOffers(): bool - { - return (bool) data_get($this->meta, 'offers.enabled', false); - } - - /** - * Seconds a driver has to accept an offer (`meta.offers.timeout`), from 10 to 120, default 20. - */ - public function offerTimeout(): int - { - return max(10, min(120, (int) data_get($this->meta, 'offers.timeout', 20))); - } - /** * Determines if activity updates must follow the configured flow graph. */ diff --git a/server/src/Support/AdhocDispatch/AdhocDispatch.php b/server/src/Support/AdhocDispatch/AdhocDispatch.php new file mode 100644 index 000000000..daafb2332 --- /dev/null +++ b/server/src/Support/AdhocDispatch/AdhocDispatch.php @@ -0,0 +1,94 @@ +> + */ + protected static array $strategies = [ + self::BROADCAST => BroadcastStrategy::class, + self::SEQUENTIAL => SequentialStrategy::class, + ]; + + /** + * Add a strategy, or replace one, under its name. + * + * @param class-string $class + */ + public static function register(string $name, string $class): void + { + if (!is_subclass_of($class, AdhocDispatchStrategy::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . AdhocDispatchStrategy::class . '.'); + } + + static::$strategies[$name] = $class; + } + + /** + * Every registered strategy name. + */ + public static function names(): array + { + return array_keys(static::$strategies); + } + + public static function has(?string $name): bool + { + return is_string($name) && isset(static::$strategies[$name]); + } + + /** + * The strategy name for the order: its own, its config's, its company's, or the default. + * A name that isn't registered is skipped. + */ + public static function nameFor(Order $order): string + { + $candidates = [ + $order->adhoc_strategy, + $order->config()?->adhoc_strategy, + data_get($order, 'company.options.fleetops.adhoc_strategy'), + ]; + + foreach ($candidates as $name) { + if (static::has($name)) { + return $name; + } + } + + return self::DEFAULT; + } + + public static function for(Order $order): AdhocDispatchStrategy + { + return app(static::$strategies[static::nameFor($order)]); + } + + /** + * Seconds a driver has to accept a one-at-a-time offer: the config's, the company's, or the default. + */ + public static function offerTimeout(Order $order): int + { + $timeout = $order->config()?->adhoc_offer_timeout ?? data_get($order, 'company.options.fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; + + return max(self::MIN_OFFER_TIMEOUT, min(self::MAX_OFFER_TIMEOUT, (int) $timeout)); + } +} diff --git a/server/src/Support/AdhocDispatch/BroadcastStrategy.php b/server/src/Support/AdhocDispatch/BroadcastStrategy.php new file mode 100644 index 000000000..dd3c5f626 --- /dev/null +++ b/server/src/Support/AdhocDispatch/BroadcastStrategy.php @@ -0,0 +1,81 @@ +offer($order); + } + + public function redispatch(Order $order, bool $testing = false): int + { + $offered = $this->offer($order, $testing)->count(); + if ($offered) { + // Restart the re-offer interval without dispatching again, which would offer it twice. + $order->forceFill(['dispatched_at' => Carbon::now()])->saveQuietly(); + } + + return $offered; + } + + public function accept(Order $order, Driver $driver): bool + { + return true; + } + + public function decline(Order $order, Driver $driver): bool + { + OrderOffers::recordDecline($order, $driver); + + return true; + } + + /** + * Offer the order to every nearby driver who hasn't declined it. Returns those drivers. + */ + protected function offer(Order $order, bool $testing = false): Collection + { + $pickup = $order->getPickupLocation(); + if (!Utils::isPoint($pickup)) { + return collect(); + } + + $drivers = DriverMatching::nearby($order, $pickup, $testing)->whereNotIn('uuid', OrderOffers::declinedDrivers($order))->get(); + foreach ($drivers as $driver) { + OrderOffers::record($order, $driver); + $this->ping($order, $driver); + } + + return $drivers; + } + + protected function ping(Order $order, Driver $driver): void + { + try { + $driver->notify(new OrderPing($order, $driver->distance ?? null)); + } catch (\Throwable) { + // One driver's failed push doesn't stop the others being offered the order. + } + } +} diff --git a/server/src/Support/AdhocDispatch/SequentialStrategy.php b/server/src/Support/AdhocDispatch/SequentialStrategy.php new file mode 100644 index 000000000..be00e9931 --- /dev/null +++ b/server/src/Support/AdhocDispatch/SequentialStrategy.php @@ -0,0 +1,118 @@ +uuid)->exists()) { + $this->offerNext($order); + } + } + + /** + * Move on from an offer whose expiry job was lost, or start offers that never began. + */ + public function redispatch(Order $order, bool $testing = false): int + { + $pending = OrderOffers::pending($order); + if ($pending && $pending->expires_at?->isPast()) { + return $this->expire($pending) ? 1 : 0; + } + + if (!$pending && !OrderOffer::where('order_uuid', $order->uuid)->exists()) { + return $this->offerNext($order) ? 1 : 0; + } + + return 0; + } + + public function accept(Order $order, Driver $driver): bool + { + return OrderOffers::acceptPending($order, $driver); + } + + public function decline(Order $order, Driver $driver): bool + { + if (!OrderOffers::declinePending($order, $driver)) { + return false; + } + + $this->offerNext($order); + + return true; + } + + /** + * Close an offer that has run out and offer the order to the next driver. + */ + public function expire(OrderOffer $offer): bool + { + $expired = OrderOffer::where('uuid', $offer->uuid) + ->where('status', OrderOffer::PENDING) + ->where('expires_at', '<=', now()) + ->update(['status' => OrderOffer::EXPIRED, 'responded_at' => now()]) > 0; + + if ($expired && ($order = Order::withoutGlobalScopes()->where('uuid', $offer->order_uuid)->first())) { + $this->offerNext($order); + } + + return $expired; + } + + /** + * Offer the order to the nearest driver who hasn't had it yet. + */ + public function offerNext(Order $order): ?OrderOffer + { + $order->refresh(); + if ($order->started || $order->driver_assigned_uuid || in_array($order->status, ['completed', 'canceled'], true)) { + return null; + } + + $pickup = $order->getPickupLocation(); + $driver = Utils::isPoint($pickup) + ? DriverMatching::nearby($order, $pickup)->whereNotIn('uuid', OrderOffers::offeredDrivers($order))->orderBy('distance')->first() + : null; + if (!$driver) { + OrderOffers::noDriverFound($order); + + return null; + } + + $timeout = AdhocDispatch::offerTimeout($order); + $offer = OrderOffers::record($order, $driver, now()->addSeconds($timeout)); + + try { + $driver->notify(new OrderPing($order, $offer->distance)); + } catch (\Throwable $exception) { + Log::warning('Unable to send an order offer', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + } + + ExpireOrderOffer::dispatch($offer->uuid)->delay(now()->addSeconds($timeout + 1)); + + return $offer; + } +} diff --git a/server/src/Support/DriverMatching.php b/server/src/Support/DriverMatching.php index 421107baa..e9b3b0625 100644 --- a/server/src/Support/DriverMatching.php +++ b/server/src/Support/DriverMatching.php @@ -2,12 +2,14 @@ namespace Fleetbase\FleetOps\Support; +use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\Eloquent\Builder; /** * Filters shared by every query that finds drivers for an order: the order's own company, - * drivers not already on a job, and the vehicle class a rider booked. + * drivers not already on a job, and the vehicle type the order needs. */ class DriverMatching { @@ -16,6 +18,30 @@ class DriverMatching */ public const FREE_JOB_STATUSES = ['completed', 'canceled', 'no_show']; + /** + * Available, online drivers who could take the order, with their `distance` from the pickup in + * metres. Within the order's ping radius, unless testing, which skips the position checks. + */ + public static function nearby(Order $order, Point $pickup, bool $testing = false): Builder + { + $query = Driver::query() + ->withoutGlobalScopes() + ->where(['status' => 'available', 'online' => 1]) + ->whereNull('deleted_at'); + + if (!$testing) { + $query->whereNotNull('location') + ->whereRaw('ST_Y(location) BETWEEN -90 AND 90 AND ST_X(location) BETWEEN -180 AND 180 AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0)') + ->distanceSphere('location', $pickup, $order->getAdhocPingDistance()) + ->distanceSphereValue('location', $pickup); + } + + // An app store reviewer's driver is never offered a real order. + NavigatorReview::excludeFrom($query); + + return static::forOrder($query, $order); + } + /** * Apply every filter for the order. */ @@ -71,11 +97,11 @@ public static function forVehicleClass(Builder $query, ?string $class): Builder } /** - * The vehicle class booked for the order, if any. + * The vehicle type the order needs, if any (`required_vehicle_type`). */ public static function vehicleClass(Order $order): ?string { - $class = data_get($order->meta, 'vehicle_class'); + $class = $order->required_vehicle_type; return is_string($class) && trim($class) !== '' ? trim($class) : null; } diff --git a/server/src/Support/FleetOps.php b/server/src/Support/FleetOps.php index 0510a4289..ff870697f 100644 --- a/server/src/Support/FleetOps.php +++ b/server/src/Support/FleetOps.php @@ -144,8 +144,8 @@ private static function transportConfigDefaults(): array * Creates or retrieves the ride config for a company: a rider's trip from request to drop-off. * * The driver accepting starts the order ("on the way"), then arrives, starts the trip and - * completes it, or records a no-show. Transitions are strict, and the order is offered to - * one driver at a time. + * completes it, or records a no-show. Transitions are strict. Riders' orders are adhoc, + * priced and matched by vehicle class, and offered to one driver at a time. */ public static function createRideConfig(Company $company): OrderConfig { @@ -192,8 +192,13 @@ public static function rideConfigDefaults(): array 'status' => 'private', 'version' => '0.0.1', 'tags' => ['ride', 'passenger'], - 'entities' => [], - 'meta' => [ + // Riders' orders go to nearby drivers of the class they booked, one driver at a time. + 'customer_orders_adhoc' => true, + 'match_vehicle_type' => true, + 'adhoc_strategy' => 'sequential', + 'adhoc_offer_timeout' => 20, + 'entities' => [], + 'meta' => [ 'lifecycle' => [ 'initial' => 'created', 'completed' => 'completed', @@ -201,7 +206,6 @@ public static function rideConfigDefaults(): array 'terminal' => ['no_show'], 'strict_transitions' => true, ], - 'offers' => ['enabled' => true, 'timeout' => 20], ], 'flow' => [ 'created' => $activity('created', 'Ride requested', 'The rider requested a ride.', ['dispatched']), diff --git a/server/src/Support/OrderOffers.php b/server/src/Support/OrderOffers.php index 99ffdd79f..9917ebe39 100644 --- a/server/src/Support/OrderOffers.php +++ b/server/src/Support/OrderOffers.php @@ -2,39 +2,39 @@ namespace Fleetbase\FleetOps\Support; -use Fleetbase\FleetOps\Jobs\ExpireOrderOffer; use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\OrderOffer; -use Fleetbase\FleetOps\Notifications\OrderPing; -use Illuminate\Database\Eloquent\Builder; -use Illuminate\Support\Facades\Log; +use Illuminate\Support\Carbon; /** - * Timed offers: one driver at a time, nearest first. An offer moves on when the driver - * declines or it runs out, and the order is canceled with "No driver found" when nobody is left. + * The record of who an adhoc order was offered to and how each driver answered, shared by every + * adhoc dispatch strategy. * - * Every change of an offer's status is a conditional update, so of two callers closing the - * same offer (a decline racing its timeout, say) only one moves the order on. + * Every change of an offer's status is a conditional update, so of two callers closing the same + * offer (a decline racing its timeout, say) only one of them changes it. */ class OrderOffers { public const NO_DRIVER_FOUND = 'No driver found'; /** - * Offer a newly dispatched order to its first driver. + * Offer the order to the driver, or keep the offer they already have open. */ - public static function start(Order $order): ?OrderOffer + public static function record(Order $order, Driver $driver, ?Carbon $expiresAt = null): OrderOffer { - if (OrderOffer::where('order_uuid', $order->uuid)->exists()) { - return static::pending($order); - } - - return static::offerNext($order); + return OrderOffer::firstOrCreate( + ['order_uuid' => $order->uuid, 'driver_uuid' => $driver->uuid, 'status' => OrderOffer::PENDING], + [ + 'company_uuid' => $order->company_uuid, + 'distance' => isset($driver->distance) ? (int) round((float) $driver->distance) : null, + 'expires_at' => $expiresAt, + ] + ); } /** - * The order's open offer, if any. + * The order's newest open offer, if any. */ public static function pending(Order $order): ?OrderOffer { @@ -42,121 +42,81 @@ public static function pending(Order $order): ?OrderOffer } /** - * Accept the driver's open offer. False when it isn't theirs or has run out. + * Drivers the order was offered to, whatever they answered. */ - public static function accept(Order $order, Driver $driver): bool + public static function offeredDrivers(Order $order): array { - return OrderOffer::where('order_uuid', $order->uuid) - ->where('driver_uuid', $driver->uuid) - ->where('status', OrderOffer::PENDING) - ->where('expires_at', '>', now()) - ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]) > 0; + return OrderOffer::where('order_uuid', $order->uuid)->pluck('driver_uuid')->all(); } /** - * The driver turns the offer down, so the next driver gets it. False when they had no open offer. + * Drivers who turned the order down. */ - public static function decline(Order $order, Driver $driver): bool + public static function declinedDrivers(Order $order): array { - $declined = OrderOffer::where('order_uuid', $order->uuid) - ->where('driver_uuid', $driver->uuid) - ->where('status', OrderOffer::PENDING) - ->update(['status' => OrderOffer::DECLINED, 'responded_at' => now()]) > 0; - - if ($declined) { - static::offerNext($order); - } - - return $declined; + return OrderOffer::where('order_uuid', $order->uuid)->where('status', OrderOffer::DECLINED)->pluck('driver_uuid')->all(); } /** - * Close an offer that has run out and offer the order to the next driver. + * Accept the driver's open offer, if it hasn't run out. False when they have none. */ - public static function expire(OrderOffer $offer): bool + public static function acceptPending(Order $order, Driver $driver): bool { - $expired = OrderOffer::where('uuid', $offer->uuid) + return OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) ->where('status', OrderOffer::PENDING) - ->where('expires_at', '<=', now()) - ->update(['status' => OrderOffer::EXPIRED, 'responded_at' => now()]) > 0; - - if ($expired && ($order = Order::withoutGlobalScopes()->where('uuid', $offer->order_uuid)->first())) { - static::offerNext($order); - } - - return $expired; + ->where(fn ($query) => $query->whereNull('expires_at')->orWhere('expires_at', '>', now())) + ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]) > 0; } /** - * Close the order's open offer without moving on, for an order that was canceled or assigned. + * Turn down the driver's open offer. False when they have none. */ - public static function withdraw(Order $order): int + public static function declinePending(Order $order, Driver $driver): bool { return OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) ->where('status', OrderOffer::PENDING) - ->update(['status' => OrderOffer::WITHDRAWN, 'responded_at' => now()]); + ->update(['status' => OrderOffer::DECLINED, 'responded_at' => now()]) > 0; } /** - * Offer the order to the nearest driver who hasn't had it yet. + * Record that the driver doesn't want the order, offered to them or not, so it isn't offered to them again. */ - public static function offerNext(Order $order): ?OrderOffer + public static function recordDecline(Order $order, Driver $driver): void { - $order->refresh(); - if ($order->started || $order->driver_assigned_uuid || in_array($order->status, ['completed', 'canceled'], true)) { - return null; - } - - $pickup = $order->getPickupLocation(); - $driver = Utils::isPoint($pickup) ? static::candidates($order, $pickup)->first() : null; - if (!$driver) { - static::noDriverFound($order); - - return null; + if (!static::declinePending($order, $driver) && !in_array($driver->uuid, static::declinedDrivers($order), true)) { + OrderOffer::create([ + 'company_uuid' => $order->company_uuid, + 'order_uuid' => $order->uuid, + 'driver_uuid' => $driver->uuid, + 'status' => OrderOffer::DECLINED, + 'responded_at' => now(), + ]); } - - $timeout = $order->config()->offerTimeout(); - $offer = OrderOffer::create([ - 'company_uuid' => $order->company_uuid, - 'order_uuid' => $order->uuid, - 'driver_uuid' => $driver->uuid, - 'status' => OrderOffer::PENDING, - 'distance' => isset($driver->distance) ? (int) round((float) $driver->distance) : null, - 'expires_at' => now()->addSeconds($timeout), - ]); - - try { - $driver->notify(new OrderPing($order, $offer->distance)); - } catch (\Throwable $exception) { - Log::warning('Unable to send a ride offer', ['order' => $order->public_id, 'error' => $exception->getMessage()]); - } - - ExpireOrderOffer::dispatch($offer->uuid)->delay(now()->addSeconds($timeout + 1)); - - return $offer; } /** - * Online, free drivers of the order's company and class within the order's radius who - * haven't been offered it, nearest first. + * The driver got the order: their offer is accepted and everyone else's is withdrawn. */ - public static function candidates(Order $order, $pickup): Builder + public static function claimed(Order $order, Driver $driver): void { - $offered = OrderOffer::where('order_uuid', $order->uuid)->pluck('driver_uuid')->all(); - $query = Driver::query() - ->withoutGlobalScopes() - ->where(['status' => 'available', 'online' => 1]) - ->whereNull('deleted_at') - ->whereNotIn('uuid', $offered) - ->whereNotNull('location') - ->whereRaw('ST_Y(location) BETWEEN -90 AND 90 AND ST_X(location) BETWEEN -180 AND 180 AND NOT (ST_X(location) = 0 AND ST_Y(location) = 0)') - ->distanceSphere('location', $pickup, $order->getAdhocPingDistance()) - ->distanceSphereValue('location', $pickup) - ->orderBy('distance'); + OrderOffer::where('order_uuid', $order->uuid) + ->where('driver_uuid', $driver->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::ACCEPTED, 'responded_at' => now()]); - NavigatorReview::excludeFrom($query); + static::withdraw($order); + } - return DriverMatching::forOrder($query, $order); + /** + * Close the order's open offers, for an order that was taken or canceled. + */ + public static function withdraw(Order $order): int + { + return OrderOffer::where('order_uuid', $order->uuid) + ->where('status', OrderOffer::PENDING) + ->update(['status' => OrderOffer::WITHDRAWN, 'responded_at' => now()]); } /** diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index 8ed0b3817..db7c34ea8 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -1616,8 +1616,8 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps expect($controller->orderDriver('order_missing')->getStatusCode())->toBe(404); }); -test('a ride needs a fare, is adhoc, and its class comes from the fare, not the rider', function () { - $ride = new OrderConfig(['key' => 'ride', 'meta' => ['offers' => ['enabled' => true]]]); +test('a ride needs a fare, is adhoc, and its vehicle type comes from the fare, not the rider', function () { + $ride = new OrderConfig(['key' => 'ride', 'customer_orders_adhoc' => true, 'match_vehicle_type' => true]); $ride->uuid = 'config-ride'; $noFare = fleetopsApiCustomerController(); $noFare->orderConfig = $ride; @@ -1633,7 +1633,7 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps $booked->createOrder(new FleetOpsApiCustomerOrderRequest([ 'service_quote' => 'quote_1', 'pickup' => ['name' => 'A'], - 'meta' => ['payment' => 'cash', 'vehicle_class' => 'xl', 'fare' => ['total' => 1], 'dispatch_outcome' => 'x'], + 'meta' => ['payment' => 'cash', 'service_name' => 'Limo', 'fare' => ['total' => 1], 'dispatch_outcome' => 'x'], ])); $owing = fleetopsApiCustomerController(); @@ -1647,7 +1647,8 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($blocked->getStatusCode())->toBe(402) ->and($owing->createdOrders)->toBe([]) ->and($booked->createdOrders[0]['adhoc'])->toBeTrue() - ->and($booked->createdOrders[0]['meta'])->toBe(['payment' => 'cash', 'vehicle_class' => 'economy', 'service_name' => 'Economy']); + ->and($booked->createdOrders[0]['required_vehicle_type'])->toBe('economy') + ->and($booked->createdOrders[0]['meta'])->toBe(['payment' => 'cash', 'service_name' => 'Economy']); }); test('a ride that ended in a no-show can no longer be canceled', function () { diff --git a/server/tests/CommandContractsTest.php b/server/tests/CommandContractsTest.php index 592c01998..d4c98eea4 100644 --- a/server/tests/CommandContractsTest.php +++ b/server/tests/CommandContractsTest.php @@ -348,21 +348,11 @@ public function getDispatchableOrders(int $days = 2, int $intervalMinutes = 4, i return $this->orders; } - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): EloquentCollection - { - $this->messages[] = ['getNearbyDriversForOrder', $order->public_id, $distance, $testing]; - - return $this->drivers; - } - - protected function usesTimedOffers(Order $order): bool - { - return false; - } + public ?FleetOpsAdhocStrategyFake $strategy = null; - protected function markPinged(Order $order): void + protected function strategyFor(Order $order): Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy { - $order->dispatchedForPing = true; + return $this->strategy ??= new FleetOpsAdhocStrategyFake(); } public function info($string, $verbosity = null) @@ -399,13 +389,11 @@ public function warn($string, $verbosity = null) class FleetOpsDispatchAdhocOrdersQueryProbe extends DispatchAdhocOrders { public FleetOpsDispatchAdhocOrdersBuilderFake $orderQuery; - public FleetOpsDispatchAdhocOrdersBuilderFake $driverQuery; public function __construct(private array $testOptions) { parent::__construct(); $this->orderQuery = new FleetOpsDispatchAdhocOrdersBuilderFake(); - $this->driverQuery = new FleetOpsDispatchAdhocOrdersBuilderFake(); } public function option($key = null) @@ -419,17 +407,38 @@ protected function newOrderQuery(string $connection) return $this->orderQuery; } +} + +/** A dispatch strategy that offers each order to as many drivers as the test says. */ +class FleetOpsAdhocStrategyFake implements Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy +{ + public array $offered = []; + public array $redispatched = []; + + public function name(): string + { + return 'fake'; + } + + public function dispatch(Order $order): void + { + } - protected function newDriverQuery() + public function redispatch(Order $order, bool $testing = false): int { - return $this->driverQuery; + $this->redispatched[] = [$order->public_id, $testing]; + + return $this->offered[$order->public_id] ?? 0; } - protected function matchDrivers($driverQuery, Order $order) + public function accept(Order $order, Driver $driver): bool { - $driverQuery->calls[] = ['matchDrivers', $order->company_uuid]; + return true; + } - return $driverQuery; + public function decline(Order $order, Driver $driver): bool + { + return true; } } @@ -2027,62 +2036,34 @@ public function getDropoffOrLastWaypoint(): object ->and($command->messages)->toContain(['info', 'No dispatchable orders found in the given timeframe.']); }); -test('dispatch adhoc command handles invalid pickups empty drivers and successful pings', function () { +test('dispatch adhoc command offers each order again through its strategy', function () { Carbon::setTestNow(Carbon::parse('2026-05-06 07:08:09')); - $invalidOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $invalidOrder->public_id = 'order_invalid'; - $invalidOrder->dispatched_at = '2026-05-06 06:00:00'; - $invalidOrder->pickupLocation = null; + $quiet = new FleetOpsDispatchAdhocOrdersOrderFake(); + $quiet->public_id = 'order_quiet'; + $quiet->dispatched_at = '2026-05-06 06:00:00'; + $busy = new FleetOpsDispatchAdhocOrdersOrderFake(); + $busy->public_id = 'order_busy'; + $busy->dispatched_at = '2026-05-06 06:10:00'; - $emptyDriverOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $emptyDriverOrder->public_id = 'order_empty'; - $emptyDriverOrder->dispatched_at = '2026-05-06 06:05:00'; - $emptyDriverOrder->pickupLocation = new Point(1.3, 103.8); - $emptyDriverOrder->adhocDistance = 1200; - - $pingOrder = new FleetOpsDispatchAdhocOrdersOrderFake(); - $pingOrder->public_id = 'order_ping'; - $pingOrder->dispatched_at = '2026-05-06 06:10:00'; - $pingOrder->pickupLocation = new Point(1.31, 103.81); - $pingOrder->adhocDistance = 2400; - - $driver = new FleetOpsDispatchAdhocOrdersDriverFake(); - $driver->public_id = 'driver_public'; - $driver->name = 'Jane Driver'; - - $command = new class(['sandbox' => true, 'testing' => true, 'days' => 3], $pingOrder, $driver) extends FleetOpsDispatchAdhocOrdersCommandFake { - public function __construct(array $options, private Order $pingOrder, private Driver $driver) - { - parent::__construct($options); - } - - public function getNearbyDriversForOrder(Order $order, Point $pickup, int $distance, bool $testing = false): EloquentCollection - { - parent::getNearbyDriversForOrder($order, $pickup, $distance, $testing); - - return $order === $this->pingOrder ? new EloquentCollection([$this->driver]) : new EloquentCollection(); - } - }; - $command->orders = new EloquentCollection([$invalidOrder, $emptyDriverOrder, $pingOrder]); + $command = new FleetOpsDispatchAdhocOrdersCommandFake(['sandbox' => true, 'testing' => true, 'days' => 3]); + $command->orders = new EloquentCollection([$quiet, $busy]); + $command->strategy = new FleetOpsAdhocStrategyFake(); + $command->strategy->offered = ['order_busy' => 2]; $command->handle(); expect($command->messages)->toContain(['info', 'Running in sandbox mode.']) - ->and($command->messages)->toContain(['alert', '3 orders found for ad-hoc dispatch. Current Time: 2026-05-06 07:08:09']) - ->and($command->messages)->toContain(['error', 'Invalid pickup location for order order_invalid']) - ->and($command->messages)->toContain(['warn', 'No available drivers found for order order_empty']) - ->and($command->messages)->toContain(['line', 'Checking order order_ping for nearby drivers within 2400 meters.']) - ->and($command->messages)->toContain(['info', 'Order order_ping dispatched successfully to 1 nearby drivers.']) - ->and($command->messages)->toContain(['info', 'Pinging driver Jane Driver (driver_public) ...']) - ->and($pingOrder->dispatchedForPing)->toBeTrue() - ->and($driver->notifications)->toBe([OrderPing::class]) + ->and($command->messages)->toContain(['alert', '2 orders found for ad-hoc dispatch. Current Time: 2026-05-06 07:08:09']) + ->and($command->messages)->toContain(['line', 'No new offer for order order_quiet (fake).']) + ->and($command->messages)->toContain(['info', 'Order order_busy offered to 2 driver(s) (fake).']) + ->and($command->strategy->redispatched)->toBe([['order_quiet', true], ['order_busy', true]]) ->and($command->tables)->toHaveCount(1); Carbon::setTestNow(); }); -test('dispatch adhoc command builds dispatchable order and nearby driver queries', function () { +test('dispatch adhoc command builds the dispatchable order query', function () { Carbon::setTestNow(Carbon::parse('2026-05-06 07:08:09')); $command = new FleetOpsDispatchAdhocOrdersQueryProbe([ @@ -2099,25 +2080,6 @@ public function getNearbyDriversForOrder(Order $order, Point $pickup, int $dista ->and($command->orderQuery->calls)->toContain(['whereHas', 'payload']) ->and($command->orderQuery->calls)->toContain(['with', ['company', 'payload']]); - $order = new Order(); - $order->setRawAttributes(['company_uuid' => 'company-uuid']); - $point = new Point(1.3, 103.8); - - expect($command->getNearbyDriversForOrder($order, $point, 500, true))->toBe($command->driverQuery->results) - ->and($command->driverQuery->calls)->toContain(['where', [['online' => 1]]]) - ->and($command->driverQuery->calls)->toContain(['whereNull', 'deleted_at']) - ->and($command->driverQuery->calls)->not->toContain(['whereNotNull', 'location']); - - $command = new FleetOpsDispatchAdhocOrdersQueryProbe([ - 'sandbox' => false, - ]); - - $command->getNearbyDriversForOrder($order, $point, 750, false); - - expect($command->driverQuery->calls)->toContain(['whereNotNull', 'location']) - ->and($command->driverQuery->calls)->toContain(['distanceSphere', 'location', $point, 750]) - ->and($command->driverQuery->calls)->toContain(['distanceSphereValue', 'location', $point]); - Carbon::setTestNow(); }); diff --git a/server/tests/DriverVehicleStatusDefaultTest.php b/server/tests/DriverVehicleStatusDefaultTest.php index 8cec78254..3ca0c1551 100644 --- a/server/tests/DriverVehicleStatusDefaultTest.php +++ b/server/tests/DriverVehicleStatusDefaultTest.php @@ -44,7 +44,7 @@ }); test('dispatch driver availability queries use available status', function () { - $listener = file_get_contents(dirname(__DIR__) . '/src/Listeners/HandleOrderDispatched.php'); + $listener = file_get_contents(dirname(__DIR__) . '/src/Support/DriverMatching.php'); $order = file_get_contents(dirname(__DIR__) . '/src/Models/Order.php'); expect($listener) diff --git a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php index 3e29542a8..d4c35749c 100644 --- a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php @@ -150,13 +150,13 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); app()->instance('db.schema', $schema); $tables = [ - 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'payload_uuid', 'order_config_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'dispatched', 'dispatched_at', 'started', 'started_at', 'scheduled_at', 'meta', 'distance', 'time', 'pod_required', 'pod_method', 'orchestrator_priority', 'adhoc_distance', 'notes', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'vehicle_assigned_uuid', 'route_uuid', 'purchase_rate_uuid', 'transaction_uuid', 'time_window_start', 'time_window_end', 'required_skills', '_key'], + 'orders' => ['uuid', 'public_id', 'internal_id', 'adhoc_strategy', 'required_vehicle_type', 'company_uuid', 'payload_uuid', 'order_config_uuid', 'tracking_number_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'dispatched', 'dispatched_at', 'started', 'started_at', 'scheduled_at', 'meta', 'distance', 'time', 'pod_required', 'pod_method', 'orchestrator_priority', 'adhoc_distance', 'notes', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'vehicle_assigned_uuid', 'route_uuid', 'purchase_rate_uuid', 'transaction_uuid', 'time_window_start', 'time_window_end', 'required_skills', '_key'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'return_uuid', 'current_waypoint_uuid', 'pickup_tracking_number_uuid', 'dropoff_tracking_number_uuid', 'meta', 'type', 'payment_method', 'cod_amount', 'cod_currency', '_key'], 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'street1', 'city', 'country', 'location', 'meta', 'street2', 'province', 'postal_code', 'phone', 'type', 'owner_uuid', 'owner_type', '_key', '_import_id'], 'waypoints' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'place_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'order', 'type', '_key', '_import_id'], 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'status', 'type', 'email', 'phone', 'password', 'slug', 'username', 'meta', '_key'], - 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'region', 'location', 'status_uuid', 'owner_uuid', 'owner_type', 'qr_code', 'barcode', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'proof_uuid', 'status', 'details', 'location', 'code', 'complete', '_key'], 'entities' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'destination_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'name', 'type', 'meta', 'internal_id', 'qr_code', 'barcode', 'photo_uuid', '_key', '_import_id'], @@ -667,12 +667,13 @@ function fleetopsOrderStartRide(SQLiteConnection $connection, array $order = []) { $defaults = Fleetbase\FleetOps\Support\FleetOps::rideConfigDefaults(); $connection->table('order_configs')->insert([ - 'uuid' => 'config-ride', - 'company_uuid' => 'company-1', - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - 'flow' => json_encode($defaults['flow']), - 'meta' => json_encode($defaults['meta']), + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + 'flow' => json_encode($defaults['flow']), + 'meta' => json_encode($defaults['meta']), + 'adhoc_strategy' => $defaults['adhoc_strategy'], ]); fleetopsOrderStartSeedOrder($connection, array_merge(['order_config_uuid' => 'config-ride', 'type' => 'ride', 'adhoc' => 1, 'status' => 'dispatched', 'dispatched' => 1, 'dispatched_at' => '2026-11-06 09:00:00'], $order)); $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => 1]); @@ -732,7 +733,7 @@ function fleetopsOrderStartOffer(SQLiteConnection $connection, string $driverUui test('of two drivers accepting the same adhoc order only the first gets it', function () { $connection = fleetopsOrderStartBoot(); fleetopsOrderStartRide($connection); - $connection->table('order_configs')->where('uuid', 'config-ride')->update(['meta' => json_encode([])]); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['adhoc_strategy' => 'broadcast']); // Someone else claimed it after this request loaded the order. $connection->table('orders')->update(['driver_assigned_uuid' => 'driver-2']); @@ -754,7 +755,7 @@ public function claim(Order $order, string $driver) test('the driver already holding an adhoc order passes, and a canceled order refuses everyone', function () { $connection = fleetopsOrderStartBoot(); fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); - $connection->table('order_configs')->where('uuid', 'config-ride')->update(['meta' => json_encode([])]); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['adhoc_strategy' => 'broadcast']); $controller = new OrderController(); $held = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); diff --git a/server/tests/Feature/RidesTest.php b/server/tests/Feature/RidesTest.php index dd08b75ff..8a2b737be 100644 --- a/server/tests/Feature/RidesTest.php +++ b/server/tests/Feature/RidesTest.php @@ -5,8 +5,10 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\OrderConfig; -use Fleetbase\FleetOps\Models\OrderOffer; use Fleetbase\FleetOps\Notifications\OrderPing; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; +use Fleetbase\FleetOps\Support\AdhocDispatch\BroadcastStrategy; +use Fleetbase\FleetOps\Support\AdhocDispatch\SequentialStrategy; use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\FleetOps; use Fleetbase\FleetOps\Support\OrderOffers; @@ -158,8 +160,8 @@ public function __call($method, $arguments) 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'status', 'email', 'phone'], 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid', 'meta'], 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'type', 'plate_number', 'seating_capacity', 'vendor_uuid', 'photo_uuid', 'avatar_url', 'name', 'internal_id', 'location', 'online', 'speed', 'heading', 'altitude', 'year', 'make', 'model', 'class', 'color', 'call_sign', 'status', 'specs', 'vin_data', 'telematics', 'meta', 'slug', 'vin', 'trim', 'plate_number_type'], - 'orders' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], - 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', 'tags'], + 'orders' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'required_vehicle_type', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', 'tags'], 'order_offers' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta'], 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'location', 'meta', 'owner_uuid', 'owner_type'], @@ -196,12 +198,13 @@ public function __call($method, $arguments) session(['company' => 'company-1']); $connection->table('companies')->insert([['uuid' => 'company-1', 'public_id' => 'company_one', 'name' => 'Acme Cabs'], ['uuid' => 'company-2', 'public_id' => 'company_two', 'name' => 'Other Cabs']]); $connection->table('order_configs')->insert([ - 'uuid' => 'config-ride', - 'company_uuid' => 'company-1', - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - 'flow' => json_encode(FleetOps::rideConfigDefaults()['flow']), - 'meta' => json_encode(['offers' => ['enabled' => true, 'timeout' => 15]]), + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'ride', + 'namespace' => 'system:order-config:ride', + 'flow' => json_encode(FleetOps::rideConfigDefaults()['flow']), + 'adhoc_strategy' => 'sequential', + 'adhoc_offer_timeout' => 15, ]); $connection->table('places')->insert(['uuid' => 'place-pickup', 'company_uuid' => 'company-1', 'name' => 'Raffles Place', 'location' => rideOffersWkb(103.8511, 1.2841)]); $connection->table('payloads')->insert(['uuid' => 'payload-1', 'company_uuid' => 'company-1', 'pickup_uuid' => 'place-pickup']); @@ -234,18 +237,18 @@ function rideOffersSeedDrivers(SQLiteConnection $connection): void function rideOffersOrder(SQLiteConnection $connection, array $attributes = []): RideOffersOrder { $connection->table('orders')->insert(array_merge([ - 'uuid' => 'order-1', - 'public_id' => 'order_ride', - 'company_uuid' => 'company-1', - 'order_config_uuid' => 'config-ride', - 'payload_uuid' => 'payload-1', - 'status' => 'dispatched', - 'type' => 'ride', - 'adhoc' => 1, - 'adhoc_distance' => 6000, - 'dispatched' => 1, - 'started' => 0, - 'meta' => json_encode(['vehicle_class' => 'economy']), + 'uuid' => 'order-1', + 'public_id' => 'order_ride', + 'company_uuid' => 'company-1', + 'order_config_uuid' => 'config-ride', + 'payload_uuid' => 'payload-1', + 'status' => 'dispatched', + 'type' => 'ride', + 'adhoc' => 1, + 'adhoc_distance' => 6000, + 'dispatched' => 1, + 'started' => 0, + 'required_vehicle_type' => 'economy', ], $attributes)); return RideOffersOrder::where('uuid', $attributes['uuid'] ?? 'order-1')->first(); @@ -261,7 +264,7 @@ function rideOffersStatuses(SQLiteConnection $connection): array return $connection->table('order_offers')->orderBy('id')->get(['driver_uuid', 'status'])->map(fn ($row) => [$row->driver_uuid, $row->status])->all(); } -test('drivers are matched by company, free from other jobs and of the booked class', function () { +test('drivers are matched by company, free from other jobs and of the vehicle type the order needs', function () { $connection = rideOffersBoot(); $connection->table('users')->insert(['uuid' => 'user-moved', 'company_uuid' => 'company-1']); $connection->table('orders')->insert([ @@ -280,11 +283,11 @@ function rideOffersStatuses(SQLiteConnection $connection): array ]); $order = new Order(); - $order->setRawAttributes(['company_uuid' => 'company-1', 'meta' => json_encode(['vehicle_class' => ' ECONOMY '])], true); + $order->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' ECONOMY '], true); $matched = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $order)->orderBy('id')->pluck('uuid')->all(); $anyClass = new Order(); - $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'meta' => json_encode(['vehicle_class' => ' '])], true); + $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' '], true); $everyClass = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $anyClass)->orderBy('id')->pluck('uuid')->all(); expect($matched)->toBe(['free', 'via-user', 'finished', 'stale']) @@ -293,17 +296,23 @@ function rideOffersStatuses(SQLiteConnection $connection): array ->and(DriverMatching::vehicleClass($order))->toBe('ECONOMY'); }); -test('a ride is offered to the nearest free driver of its class first', function () { +function sequential(): SequentialStrategy +{ + return new SequentialStrategy(); +} + +test('one at a time: the order goes to the nearest free driver of its type first', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); $order = rideOffersOrder($connection); Carbon::setTestNow('2026-11-06 09:00:00'); - $offer = OrderOffers::start($order); + sequential()->dispatch($order); Carbon::setTestNow(); + $offer = OrderOffers::pending($order); - expect($offer->driver_uuid)->toBe('amara') - ->and($offer->status)->toBe(OrderOffer::PENDING) + expect(sequential()->name())->toBe('sequential') + ->and($offer->driver_uuid)->toBe('amara') ->and($offer->distance)->toBeGreaterThan(500)->toBeLessThan(600) ->and($offer->expires_at->toDateTimeString())->toBe('2026-11-06 09:00:15') ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class]]) @@ -311,37 +320,37 @@ function rideOffersStatuses(SQLiteConnection $connection): array ->and($offer->order->uuid)->toBe('order-1') ->and($offer->driver->uuid)->toBe('amara'); - // Starting again keeps the open offer instead of offering it twice. - expect(OrderOffers::start($order)->uuid)->toBe($offer->uuid) - ->and(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); + // Dispatching again keeps the open offer instead of offering it twice. + sequential()->dispatch($order); + expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); }); -test('declining moves the ride to the next driver, and only the offered driver may accept', function () { +test('one at a time: declining moves the order on, and only the offered driver may accept', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); $order = rideOffersOrder($connection); - OrderOffers::start($order); + sequential()->dispatch($order); - expect(OrderOffers::accept($order, rideOffersDriver('chen')))->toBeFalse() - ->and(OrderOffers::decline($order, rideOffersDriver('chen')))->toBeFalse() - ->and(OrderOffers::decline($order, rideOffersDriver('amara')))->toBeTrue() + expect(sequential()->accept($order, rideOffersDriver('chen')))->toBeFalse() + ->and(sequential()->decline($order, rideOffersDriver('chen')))->toBeFalse() + ->and(sequential()->decline($order, rideOffersDriver('amara')))->toBeTrue() ->and(OrderOffers::pending($order)->driver_uuid)->toBe('chen') - ->and(OrderOffers::accept($order, rideOffersDriver('amara')))->toBeFalse() - ->and(OrderOffers::accept($order, rideOffersDriver('chen')))->toBeTrue() + ->and(sequential()->accept($order, rideOffersDriver('amara')))->toBeFalse() + ->and(sequential()->accept($order, rideOffersDriver('chen')))->toBeTrue() ->and(rideOffersStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'accepted']]); }); -test('an offer that ran out cannot be accepted and moves on once, however often it expires', function () { +test('one at a time: an offer that ran out cannot be accepted and moves on once', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); $order = rideOffersOrder($connection); - $offer = OrderOffers::start($order); + sequential()->dispatch($order); + $offer = OrderOffers::pending($order); - // Not yet expired - expect(OrderOffers::expire($offer))->toBeFalse(); + expect(sequential()->expire($offer))->toBeFalse(); Carbon::setTestNow(now()->addSeconds(30)); - $acceptedLate = OrderOffers::accept($order, rideOffersDriver('amara')); + $acceptedLate = sequential()->accept($order, rideOffersDriver('amara')); $first = (new ExpireOrderOffer($offer->uuid))->handle(); $again = (new ExpireOrderOffer($offer->uuid))->handle(); $missing = (new ExpireOrderOffer('no-such-offer'))->handle(); @@ -354,13 +363,30 @@ function rideOffersStatuses(SQLiteConnection $connection): array ->and(rideOffersStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]); }); -test('when nobody is left the ride is canceled as no driver found', function () { +test('one at a time: the scheduled check starts lost offers and moves stuck ones on', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); $order = rideOffersOrder($connection); - OrderOffers::start($order); - OrderOffers::decline($order, rideOffersDriver('amara')); - OrderOffers::decline($order, rideOffersDriver('chen')); + + expect(sequential()->redispatch($order))->toBe(1) + ->and(sequential()->redispatch($order))->toBe(0); + + Carbon::setTestNow(now()->addMinute()); + expect(sequential()->redispatch($order))->toBe(1); + Carbon::setTestNow(); + + $connection->table('order_offers')->update(['status' => 'declined']); + expect(sequential()->redispatch($order))->toBe(0) + ->and(rideOffersStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'declined']]); +}); + +test('one at a time: when nobody is left the order is canceled as no driver found', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + sequential()->dispatch($order); + sequential()->decline($order, rideOffersDriver('amara')); + sequential()->decline($order, rideOffersDriver('chen')); $meta = json_decode($connection->table('orders')->where('uuid', 'order-1')->value('meta'), true); @@ -369,16 +395,17 @@ function rideOffersStatuses(SQLiteConnection $connection): array ->and(OrderOffers::pending($order))->toBeNull(); }); -test('a ride without a usable pickup finds no driver', function () { +test('one at a time: an order without a usable pickup finds no driver', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); RideOffersOrder::$pickupPoint = null; - expect(OrderOffers::start(rideOffersOrder($connection)))->toBeNull() - ->and(RideOffersOrder::$canceled)->toHaveCount(1); + sequential()->dispatch(rideOffersOrder($connection)); + + expect(RideOffersOrder::$canceled)->toHaveCount(1); }); -test('started, assigned or finished rides are not offered again', function () { +test('one at a time: started, assigned or finished orders are not offered again', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); @@ -386,37 +413,133 @@ function rideOffersStatuses(SQLiteConnection $connection): array $assigned = rideOffersOrder($connection, ['uuid' => 'o-assigned', 'driver_assigned_uuid' => 'amara']); $canceled = rideOffersOrder($connection, ['uuid' => 'o-canceled', 'status' => 'canceled']); - expect(OrderOffers::offerNext($started))->toBeNull() - ->and(OrderOffers::offerNext($assigned))->toBeNull() - ->and(OrderOffers::offerNext($canceled))->toBeNull() + expect(sequential()->offerNext($started))->toBeNull() + ->and(sequential()->offerNext($assigned))->toBeNull() + ->and(sequential()->offerNext($canceled))->toBeNull() ->and(rideOffersStatuses($connection))->toBe([]) ->and(RideOffersOrder::$canceled)->toBe([]); }); -test('a failed push still leaves the offer open, and withdrawing closes it', function () { +test('one at a time: a failed push still leaves the offer open', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); $order = rideOffersOrder($connection); RideOffersRecorder::$notified = ['throw']; - $offer = OrderOffers::start($order); + sequential()->dispatch($order); + + expect(OrderOffers::pending($order)->driver_uuid)->toBe('amara') + ->and(app('log')->warnings)->toContain('Unable to send an order offer'); +}); + +test('at once: every nearby driver of the type is offered the order, and the first to accept gets it', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast']); + $broadcast = new BroadcastStrategy(); + + $broadcast->dispatch($order); + + expect($broadcast->name())->toBe('broadcast') + ->and(rideOffersStatuses($connection))->toBe([['amara', 'pending'], ['chen', 'pending']]) + ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class], ['chen', OrderPing::class]]) + ->and($broadcast->accept($order, rideOffersDriver('ben')))->toBeTrue(); + + OrderOffers::claimed($order, rideOffersDriver('chen')); + expect(rideOffersStatuses($connection))->toBe([['amara', 'withdrawn'], ['chen', 'accepted']]); +}); + +test('at once: a driver who declines is not offered the order again', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast', 'required_vehicle_type' => null]); + $broadcast = new BroadcastStrategy(); + $broadcast->dispatch($order); + + // Ben declines his offer; Far, never offered, declines from the list of nearby orders. + expect($broadcast->decline($order, rideOffersDriver('ben')))->toBeTrue() + ->and($broadcast->decline($order, rideOffersDriver('far')))->toBeTrue() + ->and($broadcast->decline($order, rideOffersDriver('far')))->toBeTrue(); + + Carbon::setTestNow('2026-11-06 10:00:00'); + $offered = $broadcast->redispatch($order); + Carbon::setTestNow(); + + expect($offered)->toBe(2) + ->and(OrderOffers::declinedDrivers($order))->toBe(['ben', 'far']) + ->and($connection->table('order_offers')->where('status', 'pending')->orderBy('id')->pluck('driver_uuid')->all())->toBe(['amara', 'chen']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); +}); + +test('at once: no pickup means nobody to offer, and a failed push skips only that driver', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $broadcast = new BroadcastStrategy(); + + RideOffersOrder::$pickupPoint = null; + expect($broadcast->redispatch(rideOffersOrder($connection, ['uuid' => 'o-nowhere'])))->toBe(0); + + RideOffersOrder::$pickupPoint = new Point(1.2841, 103.8511); + RideOffersRecorder::$notified = ['throw']; + expect($broadcast->redispatch(rideOffersOrder($connection)))->toBe(2); +}); + +test('which strategy an order uses: its own, its config\'s, its company\'s, then one at a time', function () { + $connection = rideOffersBoot(); + $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast']); + $fromConfig = rideOffersOrder($connection, ['uuid' => 'o-config']); + $configName = AdhocDispatch::nameFor($fromConfig); + $configWait = AdhocDispatch::offerTimeout($fromConfig); + $connection->table('order_configs')->update(['adhoc_strategy' => 'nonsense', 'adhoc_offer_timeout' => null]); + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 500]])]); + $fromCompany = RideOffersOrder::where('uuid', 'o-config')->first()->load('company'); + $connection->table('companies')->update(['options' => null]); + $fallback = RideOffersOrder::where('uuid', 'o-config')->first(); + + expect(AdhocDispatch::nameFor($order))->toBe('broadcast') + ->and(AdhocDispatch::for($order))->toBeInstanceOf(BroadcastStrategy::class) + ->and($configName)->toBe('sequential') + ->and($configWait)->toBe(15) + ->and(AdhocDispatch::nameFor($fromCompany))->toBe('broadcast') + ->and(AdhocDispatch::offerTimeout($fromCompany))->toBe(120) + ->and(AdhocDispatch::nameFor($fallback))->toBe(AdhocDispatch::DEFAULT) + ->and(AdhocDispatch::offerTimeout($fallback))->toBe(20) + ->and(AdhocDispatch::DEFAULT)->toBe('sequential'); + + $connection->table('order_configs')->update(['adhoc_offer_timeout' => 2]); + expect(AdhocDispatch::offerTimeout(RideOffersOrder::where('uuid', 'o-config')->first()))->toBe(10); +}); + +test('more strategies can be registered by name', function () { + $nearestOnly = new class extends SequentialStrategy { + public function name(): string + { + return 'nearest-only'; + } + }; + AdhocDispatch::register('nearest-only', $nearestOnly::class); - expect($offer->status)->toBe(OrderOffer::PENDING) - ->and(app('log')->warnings)->toContain('Unable to send a ride offer') - ->and(OrderOffers::withdraw($order))->toBe(1) - ->and(OrderOffers::withdraw($order))->toBe(0) - ->and(rideOffersStatuses($connection))->toBe([['amara', 'withdrawn']]); + expect(AdhocDispatch::names())->toContain('broadcast', 'sequential', 'nearest-only') + ->and(AdhocDispatch::has('nearest-only'))->toBeTrue() + ->and(AdhocDispatch::has(null))->toBeFalse() + ->and(fn () => AdhocDispatch::register('broken', stdClass::class))->toThrow(InvalidArgumentException::class); }); -test('offer settings come from the order config and are kept in range', function () { - $config = fn (array $meta) => new OrderConfig(['meta' => $meta]); +test('offers record each driver once, and a decline from a driver who was never offered the order', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $order = rideOffersOrder($connection); + $amara = rideOffersDriver('amara'); + + $first = OrderOffers::record($order, $amara); + $again = OrderOffers::record($order, $amara); + OrderOffers::recordDecline($order, rideOffersDriver('ben')); - expect($config([])->usesTimedOffers())->toBeFalse() - ->and($config([])->offerTimeout())->toBe(20) - ->and($config(['offers' => ['enabled' => true, 'timeout' => 3]])->usesTimedOffers())->toBeTrue() - ->and($config(['offers' => ['timeout' => 3]])->offerTimeout())->toBe(10) - ->and($config(['offers' => ['timeout' => 900]])->offerTimeout())->toBe(120) - ->and($config(['offers' => ['timeout' => 45]])->offerTimeout())->toBe(45); + expect($again->uuid)->toBe($first->uuid) + ->and($first->expires_at)->toBeNull() + ->and(OrderOffers::offeredDrivers($order))->toBe(['amara', 'ben']) + ->and(OrderOffers::acceptPending($order, $amara))->toBeTrue() + ->and(OrderOffers::withdraw($order))->toBe(0); }); test('the ride config is a strict flow with a no-show ending, offered one driver at a time', function () { @@ -425,7 +548,9 @@ function rideOffersStatuses(SQLiteConnection $connection): array expect($defaults['key'])->toBe('ride') ->and(array_keys($defaults['flow']))->toBe(['created', 'dispatched', 'started', 'arrived', 'in_progress', 'completed', 'no_show']) - ->and($config->usesTimedOffers())->toBeTrue() + ->and($config->adhoc_strategy)->toBe('sequential') + ->and($config->customer_orders_adhoc)->toBeTrue() + ->and($config->match_vehicle_type)->toBeTrue() ->and($config->hasStrictTransitions())->toBeTrue() ->and($config->canTransition('arrived', 'no_show'))->toBeTrue() ->and($config->canTransition('arrived', 'completed'))->toBeFalse() @@ -481,85 +606,28 @@ public function error($string, $verbosity = null) ->and(json_decode($connection->table('order_configs')->where('key', 'ride')->value('meta'), true)['rider'])->toBe(['emergency_number' => '995', 'support_email' => 'help@cabs.test']); }); -test('the dispatch listener hands rides with timed offers to the offers', function () { +test('a dispatched adhoc order is offered by its strategy, and a busy driver is left out', function () { $connection = rideOffersBoot(); rideOffersSeedDrivers($connection); - $ride = rideOffersOrder($connection); - $transport = new Order(); - $transport->setRawAttributes(['uuid' => 'order-t', 'company_uuid' => 'company-1'], true); - - $listener = new class extends Fleetbase\FleetOps\Listeners\HandleOrderDispatched { - public function call(string $method, ...$arguments): mixed - { - return $this->{$method}(...$arguments); - } - }; - - expect($listener->call('usesTimedOffers', $ride))->toBeTrue() - ->and($listener->call('usesTimedOffers', $transport))->toBeFalse() - ->and($listener->call('startOffers', $ride)->driver_uuid)->toBe('amara'); - - // Handling the dispatch of a ride offers it instead of pinging every driver. - $connection->table('order_offers')->delete(); - $connection->table('orders')->where('uuid', 'order-1')->update(['tracking_number_uuid' => 'tn-1']); + rideOffersOrder($connection, ['tracking_number_uuid' => 'tn-1']); $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'RIDE1', 'owner_uuid' => 'order-1']); - $listener->handle(new Fleetbase\FleetOps\Events\OrderDispatched(RideOffersOrder::where('uuid', 'order-1')->first())); - expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]) - ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class], ['amara', OrderPing::class]]); -}); - -test('the adhoc command moves stuck offers on and re-pings without dispatching again', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - - $command = new class extends Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders { - public array $lines = []; - - public function info($string, $verbosity = null) - { - $this->lines[] = $string; - } - - public function helper(string $method, ...$arguments): mixed - { - return $this->{$method}(...$arguments); - } - }; - - // No offer yet: the offers start. - $ride = rideOffersOrder($connection); - expect($command->helper('usesTimedOffers', $ride))->toBeTrue(); - $command->helper('advanceOffers', $ride); - expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); - - // An open offer still in time is left alone. - $command->helper('advanceOffers', $ride); - expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); - // An offer whose expiry job was lost is closed and the next driver gets the ride. - Carbon::setTestNow(now()->addMinute()); - $command->helper('advanceOffers', $ride); - Carbon::setTestNow(); - expect(rideOffersStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]) - ->and($command->lines)->toBe(['Started offers for order order_ride.', 'Moved order order_ride to the next driver.']); + (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(RideOffersOrder::where('uuid', 'order-1')->first())); - // An order whose offers all ended is not started again. - $connection->table('order_offers')->update(['status' => 'declined']); - $command->helper('advanceOffers', $ride); - expect($connection->table('order_offers')->count())->toBe(2); + expect(rideOffersStatuses($connection))->toBe([['chen', 'pending']]) + ->and(RideOffersRecorder::$notified)->toBe([['chen', OrderPing::class]]); +}); - // A re-ping restarts the interval quietly. - Carbon::setTestNow('2026-11-06 10:00:00'); - $command->helper('markPinged', $ride); - Carbon::setTestNow(); - expect($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); +test('the scheduled adhoc command asks each order\'s strategy', function () { + $connection = rideOffersBoot(); + $lookup = new ReflectionMethod(Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, 'strategyFor'); + $command = new Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders(); - // Drivers matched for a re-ping leave out busy ones and other classes. - $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); - $connection->table('drivers')->where('uuid', 'chen')->update(['current_job_uuid' => 'job-live']); - $matched = $command->helper('matchDrivers', Driver::query()->withoutGlobalScopes()->where('online', 1), $ride)->orderBy('id')->pluck('uuid')->all(); - expect($matched)->toBe(['amara', 'far', 'rival']); + expect($lookup->invoke($command, rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast'])))->toBeInstanceOf(BroadcastStrategy::class) + ->and($lookup->invoke($command, rideOffersOrder($connection, ['uuid' => 'o-2'])))->toBeInstanceOf(SequentialStrategy::class); }); test('fares carry each class\'s seats and how soon its nearest free car could arrive', function () { diff --git a/server/tests/OrderDispatchListenerContractsTest.php b/server/tests/OrderDispatchListenerContractsTest.php index bd05cb988..30ce1cded 100644 --- a/server/tests/OrderDispatchListenerContractsTest.php +++ b/server/tests/OrderDispatchListenerContractsTest.php @@ -19,7 +19,6 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\TrackingStatus; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Carbon; @@ -217,8 +216,7 @@ class FleetOpsHandleOrderDispatchedProbe extends HandleOrderDispatched public Illuminate\Support\Collection $nearbyDrivers; public array $failures = []; public array $assignedNotifications = []; - public array $adhocNotifications = []; - public array $nearbyQueries = []; + public array $adhocDispatches = []; public function __construct() { @@ -244,21 +242,11 @@ protected function getDispatchActivity($order): mixed return $order->dispatchActivity; } - protected function usesTimedOffers($order): bool + protected function dispatchAdhoc($order): mixed { - return false; - } - - protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) - { - $this->nearbyQueries[] = [(string) $pickup, $distance]; - - return $this->nearbyDrivers; - } + $this->adhocDispatches[] = $order->public_id; - protected function notifyAdhocDriver(Driver $driver, $order): void - { - $this->adhocNotifications[] = [$driver->public_id, $driver->distance, $order->driver_assigned_uuid]; + return null; } protected function findAssignedDriver($order): ?Driver @@ -543,40 +531,17 @@ function fleetOpsDispatchListenerDriver(string $publicId, float $distance = 0): ]); }); -test('order dispatched listener pings nearby adhoc drivers and ignores invalid pickup points', function () { - $listener = new FleetOpsHandleOrderDispatchedProbe(); - $listener->nearbyDrivers = collect([ - fleetOpsDispatchListenerDriver('nearby_one', 100.5), - fleetOpsDispatchListenerDriver('nearby_two', 250.25), - ]); - $order = fleetOpsDispatchListenerOrder([ +test('order dispatched listener hands adhoc orders to their dispatch strategy', function () { + $listener = new FleetOpsHandleOrderDispatchedProbe(); + $order = fleetOpsDispatchListenerOrder([ 'adhoc' => true, 'hasDriverAssigned' => false, - 'pickupLocation' => new Point(1.30, 103.80), - 'adhocDistance' => 2400, ]); + $order->public_id = 'order_adhoc'; $listener->handle(new FleetOpsOrderDispatchedEventFake($order)); - expect($order->calls)->toContain(['load', ['company']]) - ->and($order->calls)->toContain(['getPickupLocation']) - ->and($order->calls)->toContain(['getAdhocDistance']) - ->and($listener->nearbyQueries)->toBe([[(string) $order->pickupLocation, 2400]]) - ->and($listener->adhocNotifications)->toBe([ - ['nearby_one', 100.5, 'driver-uuid'], - ['nearby_two', 250.25, 'driver-uuid'], - ]) - ->and($listener->assignedNotifications)->toBe([]); - - $invalidPickup = fleetOpsDispatchListenerOrder([ - 'adhoc' => true, - 'hasDriverAssigned' => false, - 'pickupLocation' => null, - ]); - $invalidPickupListener = new FleetOpsHandleOrderDispatchedProbe(); - - $invalidPickupListener->handle(new FleetOpsOrderDispatchedEventFake($invalidPickup)); - - expect($invalidPickupListener->nearbyQueries)->toBe([]) - ->and($invalidPickupListener->adhocNotifications)->toBe([]); + expect($listener->adhocDispatches)->toBe(['order_adhoc']) + ->and($listener->assignedNotifications)->toBe([]) + ->and($listener->failures)->toBe([]); }); diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php index 0436f210d..105ac562f 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedConcreteTest.php @@ -100,9 +100,8 @@ class FleetOpsConcreteHandleOrderDispatchedProbe extends HandleOrderDispatched { public ?Driver $assignedDriver = null; public bool $throwAssignedNotification = false; - public bool $throwAdhocNotification = false; public array $assignedNotifications = []; - public array $adhocNotifications = []; + public array $adhocDispatches = []; public function getDispatchActivityForTest(Order $order): mixed { @@ -119,16 +118,11 @@ protected function findAssignedDriver($order): ?Driver return $this->assignedDriver; } - protected function usesTimedOffers($order): bool + protected function dispatchAdhoc($order): mixed { - return false; - } + $this->adhocDispatches[] = $order; - protected function nearbyAvailableDrivers($pickup, int|float $distance, ?Order $order = null) - { - return collect([ - new FleetOpsConcreteDriverForDispatch(), - ]); + return null; } protected function notifyAssignedDriver(Driver $driver, $order): void @@ -140,16 +134,6 @@ protected function notifyAssignedDriver(Driver $driver, $order): void $this->assignedNotifications[] = $driver; parent::notifyAssignedDriver($driver, $order); } - - protected function notifyAdhocDriver(Driver $driver, $order): void - { - if ($this->throwAdhocNotification) { - throw new RuntimeException('adhoc notification failed'); - } - - $this->adhocNotifications[] = $driver; - parent::notifyAdhocDriver($driver, $order); - } } function fleetopsConcreteOrderForDispatch(array $attributes = []): FleetOpsConcreteOrderForDispatch @@ -192,17 +176,15 @@ function fleetopsConcreteOrderForDispatch(array $attributes = []): FleetOpsConcr ->and($listener->assignedNotifications)->toBe([]); }); -test('order dispatched listener swallows adhoc driver notification failures', function () { +test('order dispatched listener marks an adhoc order dispatched before its strategy offers it', function () { $listener = new FleetOpsConcreteHandleOrderDispatchedProbe(); $order = fleetopsConcreteOrderForDispatch(); $order->adhoc = true; $order->hasDriverAssigned = false; - $order->pickupLocation = new Fleetbase\LaravelMysqlSpatial\Types\Point(1.30, 103.80); - - $listener->throwAdhocNotification = true; $listener->handle(new FleetOpsConcreteOrderDispatchedEvent($order)); expect($order->dispatched)->toBeTrue() - ->and($listener->adhocNotifications)->toBe([]); + ->and($listener->adhocDispatches)->toBe([$order]) + ->and($listener->assignedNotifications)->toBe([]); }); diff --git a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php index 8a0a2ad0d..387b8e88c 100644 --- a/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php +++ b/server/tests/Unit/Listeners/HandleOrderDispatchedHelpersTest.php @@ -4,7 +4,6 @@ use Fleetbase\FleetOps\Listeners\HandleOrderDispatched; use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; -use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\ConnectionResolver; use Illuminate\Database\Eloquent\Model as EloquentModel; use Illuminate\Database\SQLiteConnection; @@ -148,27 +147,6 @@ public function __call($method, $arguments) expect($probe->callHelper('doesntHaveDispatchActivity', $order))->toBeFalse(); }); -test('nearby available drivers runs the spatial company scoped query', function () { - $connection = fleetopsDispatchHelperBoot(); - - $probe = new FleetOpsDispatchHelperProbe(); - $drivers = $probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000); - - expect($drivers)->toHaveCount(1) - ->and($drivers->first()->uuid)->toBe('driver-1'); - - // For an order, only its own company's drivers who aren't on another job - $own = Order::where('uuid', 'order-1')->withoutGlobalScopes()->first(); - $other = new Order(); - $other->setRawAttributes(['uuid' => 'order-x', 'company_uuid' => 'company-2'], true); - expect($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000, $own))->toHaveCount(1) - ->and($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000, $other))->toHaveCount(0); - - // Offline drivers are excluded - $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => '0']); - expect($probe->callHelper('nearbyAvailableDrivers', new Point(1.3, 103.8), 5000))->toHaveCount(0); -}); - test('assigned driver lookup and notification helpers resolve and send', function () { fleetopsDispatchHelperBoot(); $order = Order::where('uuid', 'order-1')->withoutGlobalScopes()->first(); @@ -186,8 +164,6 @@ public function __call($method, $arguments) app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, $dispatcher); $probe->callHelper('notifyAssignedDriver', $driver, $order); - $driver->distance = 250; - $probe->callHelper('notifyAdhocDriver', $driver, $order); - expect($dispatcher->sent)->toHaveCount(2); + expect($dispatcher->sent)->toHaveCount(1); }); diff --git a/server/tests/Unit/Support/QuerySeamsTest.php b/server/tests/Unit/Support/QuerySeamsTest.php index 45dad48e8..fc8801da4 100644 --- a/server/tests/Unit/Support/QuerySeamsTest.php +++ b/server/tests/Unit/Support/QuerySeamsTest.php @@ -178,8 +178,7 @@ function fleetopsQuerySeamInvoke(object $instance, string $class, string $method $class = Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class; // The order query is bound to the named connection - expect(fleetopsQuerySeamInvoke($command, $class, 'newOrderQuery', ['mysql'])->get()->pluck('uuid')->all())->toBe(['order-adhoc-1']) - ->and(fleetopsQuerySeamInvoke($command, $class, 'newDriverQuery')->get()->pluck('uuid')->all())->toBe(['driver-adhoc-1']); + expect(fleetopsQuerySeamInvoke($command, $class, 'newOrderQuery', ['mysql'])->get()->pluck('uuid')->all())->toBe(['order-adhoc-1']); }); test('order finalization job seams resolve records and fire the ready event', function () { @@ -292,22 +291,20 @@ public function __call($method, $arguments) }); $connection->table('drivers')->insert([ // Online and in the order's company - ['uuid' => 'driver-near-1', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '1'], + ['uuid' => 'driver-near-1', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '1', 'status' => 'available'], // Online but another company - ['uuid' => 'driver-near-2', 'company_uuid' => 'company-other', 'user_uuid' => 'user-adhoc-b', 'online' => '1'], + ['uuid' => 'driver-near-2', 'company_uuid' => 'company-other', 'user_uuid' => 'user-adhoc-b', 'online' => '1', 'status' => 'available'], // Right company but offline - ['uuid' => 'driver-near-3', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '0'], + ['uuid' => 'driver-near-3', 'company_uuid' => 'company-seam-1', 'user_uuid' => 'user-adhoc-a', 'online' => '0', 'status' => 'available'], ]); $order = new Fleetbase\FleetOps\Models\Order(); $order->setRawAttributes(['uuid' => 'order-adhoc-near', 'company_uuid' => 'company-seam-1'], true); - $class = Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class; - $command = (new ReflectionClass($class))->newInstanceWithoutConstructor(); $pickup = new Fleetbase\LaravelMysqlSpatial\Types\Point(1.30, 103.80); // In testing mode the spatial predicates are skipped so the company and // online filters can be asserted on their own - $drivers = $command->getNearbyDriversForOrder($order, $pickup, 5000, true); + $drivers = Fleetbase\FleetOps\Support\DriverMatching::nearby($order, $pickup, true)->get(); expect($drivers->pluck('uuid')->all())->toBe(['driver-near-1']); }); From 8c7a4d78f57ca4372e7260fd7e317580f8358d6c Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 11:21:20 +0800 Subject: [PATCH 16/29] chore(release): v0.7.0 Set the version in composer.json, package.json and extension.json, start RELEASE.md, and run CI on pull requests into release/v* and dev-v*. --- .github/workflows/ember.yml | 2 +- .github/workflows/server.yml | 2 +- RELEASE.md | 36 ++++++++---------------------------- composer.json | 2 +- extension.json | 2 +- package.json | 2 +- 6 files changed, 13 insertions(+), 33 deletions(-) diff --git a/.github/workflows/ember.yml b/.github/workflows/ember.yml index 3d443ebb7..1aefda134 100644 --- a/.github/workflows/ember.yml +++ b/.github/workflows/ember.yml @@ -6,7 +6,7 @@ on: tags: - 'v*' pull_request: - branches: [ main, 'release/v*', 'dev-v*' ] + branches: [ main, 'release/v*', 'dev-v*', release/v*, dev-v* ] env: NODE_VERSION: 22.x diff --git a/.github/workflows/server.yml b/.github/workflows/server.yml index 002f52801..99db16172 100644 --- a/.github/workflows/server.yml +++ b/.github/workflows/server.yml @@ -6,7 +6,7 @@ on: tags: - 'v*' pull_request: - branches: [ main, 'release/v*', 'dev-v*' ] + branches: [ main, 'release/v*', 'dev-v*', release/v*, dev-v* ] jobs: build: diff --git a/RELEASE.md b/RELEASE.md index a32ec2d8d..78028531e 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,36 +1,16 @@ -> v0.6.75 ~ "Road distance and ETAs from one routing engine, tenant-isolated profile accounts and App Review access for Navigator" +> v0.7.0 ~ "Laravel 12 and core-api 2.0" --- ## Highlights -- **Feature: one routing engine for order distance, ETAs and the map.** An order's stored distance and time, its live ETAs and remaining distance, and the route drawn on the map now all come from the organization's routing engine. Before this, order distance defaulted to a straight-line estimate at a flat ~50 km/h; a reported ~30 km run was stored as 25.0 km / 30 min and is now 32.1 km / 32 min. The engine is chosen in order: the organization's routing engine, then the admin default, then the platform's Valhalla server, then the straight-line estimate. An engine only counts if it is allowed and configured. A failed road lookup falls back to the straight-line estimate and is logged, instead of storing 0. Road results are cached for 24 hours. (#406) -- **Feature: routing provider controls in Admin → Fleet-Ops → Routing.** Administrators choose which providers organizations may use (Google, Valhalla, OSRM, VROOM), with per-organization exceptions. They also set the default routing and optimization engines, and whether server-side routing uses roads or only the straight-line estimate. Saved admin settings take precedence over environment variables. **Google is off until an administrator enables it**, for map routing, optimization, order distance and ETAs. The public OSRM demo server is never called by the server. The admin menu entry "Fleet-Ops Config" is now "Fleet-Ops". (#406) -- **Feature: the OSRM server is a setting, for the platform and per organization.** Administrators set it in Admin → Fleet-Ops → Routing → OSRM Server; `OSRM_HOST` is now only the starting value. Organizations that route or optimize with OSRM can use their own server under Fleet-Ops Settings → Routing → OSRM Server, like the Valhalla and VROOM overrides. An organization host must be a public address (`OSRM_ALLOW_PRIVATE_HOSTS=true` lifts that on self-hosted installs). Order distance, ETAs, tracking and the console's OSRM routes and route control all use the resolved server. The public demo server still only draws map routes. -- **Security: an organization's routing host can't point at a private address.** Order distance, ETAs and VROOM allocation ignore an organization's Valhalla or VROOM override whose host is loopback, a private or link-local network, cloud metadata or another non-public range, and use the system server instead. This also covers values saved before the Valhalla and VROOM extensions started rejecting them. (#417) -- **Security: a profile never links to another organization's login account.** Creating a driver, customer or contact with an email or phone that belongs to another organization's account linked that account and exposed its name, email and phone. The new organization could then reset its password or deactivate it. Only accounts that already belong to the organization, or belong to no organization, are reused now. The refusal does not say whose account it is. `POST /v1/drivers` also ignores a `company` that is not the API credential's own. Logins already shared by the old behaviour can only be managed by their holder. (#414) -- **Fix: orders can be edited with a partial payload.** `PUT /v1/orders/{id}` accepts a `payload` with only the parts that change, such as only entities or only a new dropoff. (#411) -- **Fix: addresses sent with coordinates keep their street.** A place given as a street address plus `latitude`/`longitude` was reverse-geocoded and stored as a different nearby address. The street and the coordinates are now kept as sent, without a geocoding call. (#411) -- **Feature: idempotent order creation.** `POST /v1/orders` accepts an `Idempotency-Key` header. A retry with the same key within 24 hours returns the order already created, with `Idempotent-Replayed: true`, and a concurrent duplicate gets `409`. (#412) -- **Fix: `scheduled_at` keeps its UTC offset.** `2026-10-21T11:00:00-07:00` is now stored as 18:00 UTC instead of 11:00, and `PUT /v1/orders/{id}/schedule` stores the UTC instant of a date and time in the company timezone. Rows written before this keep their old values. (#412) -- **Fix: service quotes.** The `currency` filter works again, stored quotes expire after 48 hours by default (`fleetops.service_quotes.ttl_minutes`), and `preview=1` prices a request without storing quote rows. (#412) -- **Fix: tracking numbers with a space can be looked up again.** Since v0.6.72, a number such as `AL 7796486490AE`, generated for a company whose name has a space in its first three letters, got "not found". Single inner spaces are accepted now. New numbers only use letters and digits: the company prefix skips spaces and punctuation ("Al Noor" gives `ALN`), and a region such as "New York" becomes `NEWYORK`. (#413, #416) -- **Feature: App Review access for Navigator.** Apple and Google reviewers can't receive the texted sign-in code. An organization can turn on **Settings → Navigator App → App Review**: reviewers sign in to its Navigator with the test number +1 202 555 0144 (a range kept for fiction, never texted) and a six-digit code the owner creates and enters in App Store Connect and Google Play Console. The code is stored hashed, shown once, and only works for that organization. The first sign-in adds an **App Reviewer** driver, which ad-hoc offers, nearest-driver assignment and the orchestrator always leave out. Built on core-api's App Review access; the `NAVIGATOR_*` review env settings still work on self-hosted installs. See `docs/NAVIGATOR_APP_REVIEW.md`. (#418) +- **Laravel 12.** The server package now runs on Laravel 12 with Carbon 3 and requires `fleetbase/core-api` ^2.0. It installs into the Laravel 12 Fleetbase API (fleetbase/fleetbase v0.8.0); Laravel 10 installs stay on the v0.6.75 line. +- **No security advisory exceptions.** `composer audit` reports no advisories on the Laravel 12 dependency set, so the Composer advisory workarounds are gone. +- fix(request): call core-api's inputArray instead of array (#423) +- chore(l12): keep fresh-install columns identical without Doctrine (#422) +- feat(customers): add rider routes with owner checks (#420) --- ## Upgrading -- **Requires fleetbase/core-api v1.6.74** (`composer.json` now requires `^1.6.74`), which adds App Review access and its `review_accesses` table: run `php artisan migrate`. -- **Routing defaults changed (#406).** Review **Admin → Fleet-Ops → Routing** after upgrading: - - The default routing engine is now **Valhalla** (it was OSRM). Without a Valhalla server (`VALHALLA_HOST`, or the Valhalla extension's settings), order distance and ETAs use the straight-line estimate. Self-hosters running their own OSRM can make it the default in the panel or with `ROUTING_DISPLAY_ENGINE=osrm`. - - **Google is off.** Turn it on in the panel or set `ROUTING_GOOGLE_ENABLED=true`. `DISTANCE_MATRIX_PROVIDER=google` also enables it until the panel is saved. - - Tracking follows the routing engine. `TRACKING_PROVIDER` and `TRACKING_PROVIDER_FALLBACKS` are no longer read, and saved tracking provider and fallback choices are ignored. - - `DISTANCE_MATRIX_PROVIDER` only seeds the admin defaults now; it no longer overrides order distance. - - New starting values, read until the panel is first saved: `ROUTING_GOOGLE_ENABLED`, `ROUTING_DISPLAY_ENGINE`, `ROUTING_OPTIMIZATION_ENGINE`, `ROUTING_SERVER_ROUTING`, plus `VALHALLA_HOST`, `VALHALLA_API_KEY`, `VALHALLA_COSTING` and `VALHALLA_TIMEOUT`. - - Existing orders: started, unfinished orders from the last 2 days are re-measured by `fleetops:update-estimations`; unstarted orders pick up road distance at their next ready or edit; completed and cancelled orders keep their stored values. No migration. -- **OSRM server.** Nothing to do: `OSRM_HOST` keeps working until a host is saved in Admin → Fleet-Ops → Routing. Organization OSRM servers are new and empty. -- **Private routing hosts (#417).** On self-hosted installs, an organization override pointing at a private host (for example `http://valhalla:8002`) now falls back to the system server. Set `VALHALLA_ALLOW_PRIVATE_HOSTS=true` or `VROOM_ALLOW_PRIVATE_HOSTS=true` to allow it. System-level private hosts are unaffected. -- **Fleetbase Cloud.** After deploying, set the Valhalla host to `https://valhalla.routing.fleetbase.io` with Cloud's gateway key, Google and OSRM off, and Valhalla as the default engine with road routing. Enter the gateway key only after fleetbase/valhalla v0.0.5 and fleetbase/vroom v0.0.5 ship (valhalla#9, vroom#8), because the extensions' settings endpoints return the key to any signed-in user until then. ---- -## Need help? -- [GitHub Discussions](https://github.com/fleetbase/fleetbase/discussions) -- [Discord](https://discord.gg/HnTqQ6zAVn) +- **Requires fleetbase/core-api v2.0.0** (Laravel 12, PHP 8.2 or later). Upgrade the API to fleetbase/fleetbase v0.8.0 first, then this extension. +- Run `php artisan migrate` after upgrading. diff --git a/composer.json b/composer.json index a7f527367..e3fccdb8d 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "fleetbase/fleetops-api", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "keywords": [ "fleetbase-extension", diff --git a/extension.json b/extension.json index c0757d489..c6ec6a88a 100644 --- a/extension.json +++ b/extension.json @@ -1,6 +1,6 @@ { "name": "Fleet-Ops", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "repository": "https://github.com/fleetbase/fleetops", "license": "AGPL-3.0-or-later", diff --git a/package.json b/package.json index 0822d957b..827bad169 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@fleetbase/fleetops-engine", - "version": "0.6.75", + "version": "0.7.0", "description": "Fleet & Transport Management Extension for Fleetbase", "fleetbase": { "route": "fleet-ops" From 961601732b9cea9d58c1b2dc93ea3953f4e4e11f Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 12:49:09 +0800 Subject: [PATCH 17/29] fix(dispatch): a driver's nearby orders show only adhoc orders they can take MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Navigator lists offers with `GET orders?nearby=driver_…&adhoc=1&unassigned=1`. With one-at-a-time offers as the default, every nearby driver saw every adhoc order and all but one got a 409 on accept. - For a driver asking with `nearby=driver_…`, an unassigned adhoc order shows only if they hold an open offer for it, or if its strategy lists orders openly and they haven't declined it. The strategy is worked out in SQL (the order's, then its config's, then the company default). Other orders are untouched. - Each order carries `adhoc_offer: { status, expires_at }` for that driver, for a countdown. - These lists skip the response cache, because they change with every offer. - Strategies declare `listsOpenly()`: broadcast does, sequential doesn't. --- .../src/Contracts/AdhocDispatchStrategy.php | 7 ++ .../Controllers/Api/v1/OrderController.php | 30 ++++++- server/src/Http/Resources/v1/Order.php | 3 + .../Support/AdhocDispatch/AdhocDispatch.php | 41 +++++++--- .../AdhocDispatch/AdhocOfferListing.php | 82 +++++++++++++++++++ .../AdhocDispatch/BroadcastStrategy.php | 5 ++ .../AdhocDispatch/SequentialStrategy.php | 5 ++ server/tests/CommandContractsTest.php | 5 ++ .../Api/OrderControllerNearbyFiltersTest.php | 4 +- server/tests/Feature/RidesTest.php | 55 +++++++++++++ 10 files changed, 224 insertions(+), 13 deletions(-) create mode 100644 server/src/Support/AdhocDispatch/AdhocOfferListing.php diff --git a/server/src/Contracts/AdhocDispatchStrategy.php b/server/src/Contracts/AdhocDispatchStrategy.php index 6b901239a..acea8e246 100644 --- a/server/src/Contracts/AdhocDispatchStrategy.php +++ b/server/src/Contracts/AdhocDispatchStrategy.php @@ -20,6 +20,13 @@ interface AdhocDispatchStrategy */ public function name(): string; + /** + * Whether a driver nearby sees the order in their list without holding an offer for it. + * True for everyone-at-once offering, false when it goes to one driver at a time. A driver + * who declined never sees it, and one holding an open offer always does. + */ + public function listsOpenly(): bool; + /** * The order was just dispatched: offer it to drivers. */ diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index 93be2e351..3004d24fb 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -26,6 +26,7 @@ use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing; use Fleetbase\FleetOps\Support\OrderEdit; use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\ResolvesOrderServiceStops; @@ -772,7 +773,15 @@ public function query(Request $request) { set_time_limit(180); - $results = Order::queryWithRequest($request, function (&$query, $request) { + // A driver listing orders near them sees only the adhoc orders they could take. That + // depends on live offers, so the list isn't cached. + $offerDriver = $this->nearbyDriverUuid($request); + + $results = Order::queryWithRequest($request, function (&$query, $request) use ($offerDriver) { + if ($offerDriver) { + AdhocOfferListing::apply($query, $offerDriver, Company::currentSession()); + } + $query->with(['trackingStatuses', 'driverAssigned', 'vehicleAssigned', 'customer', 'facilitator']); $query->where('company_uuid', session('company')); $query->whereNotNull('payload_uuid'); @@ -945,7 +954,11 @@ public function query(Request $request) } } } - }); + }, (bool) $offerDriver); + + if ($offerDriver) { + AdhocOfferListing::attach($results, $offerDriver); + } return OrderResource::collection($results); } @@ -1286,6 +1299,19 @@ public function declineOrder(string $id, Request $request) return response()->json(['status' => 'declined', 'order' => $order->public_id]); } + /** + * The driver whose surroundings are asked for with `nearby=driver_…`, if they belong to this company. + */ + protected function nearbyDriverUuid(Request $request): ?string + { + $nearby = $request->input('nearby'); + if (!is_string($nearby) || !Str::startsWith($nearby, 'driver_')) { + return null; + } + + return Driver::withoutGlobalScopes()->where('public_id', $nearby)->where('company_uuid', session('company'))->whereNull('deleted_at')->value('uuid'); + } + protected function findAdhocDriver(string $publicId): ?Driver { return Driver::withoutGlobalScopes()->where('public_id', $publicId)->whereNull('deleted_at')->first(); diff --git a/server/src/Http/Resources/v1/Order.php b/server/src/Http/Resources/v1/Order.php index d9bc4ff7d..fa77bbc5f 100644 --- a/server/src/Http/Resources/v1/Order.php +++ b/server/src/Http/Resources/v1/Order.php @@ -3,6 +3,7 @@ namespace Fleetbase\FleetOps\Http\Resources\v1; use Fleetbase\FleetOps\Models\Contact as ContactModel; +use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Resources\Comment; use Fleetbase\Http\Resources\File; @@ -90,6 +91,8 @@ public function toArray($request): array 'adhoc_distance' => (int) $this->getAdhocDistance(), 'adhoc_strategy' => $this->adhoc_strategy, 'required_vehicle_type' => $this->required_vehicle_type, + // The asking driver's open offer, when they listed orders near them. + 'adhoc_offer' => $this->when($this->resource->relationLoaded('adhocOffer'), fn () => AdhocOfferListing::present($this->adhocOffer)), 'distance' => (int) $this->distance, 'time' => (int) $this->time, 'transaction_amount' => $this->transaction_amount, diff --git a/server/src/Support/AdhocDispatch/AdhocDispatch.php b/server/src/Support/AdhocDispatch/AdhocDispatch.php index daafb2332..c0f1782c5 100644 --- a/server/src/Support/AdhocDispatch/AdhocDispatch.php +++ b/server/src/Support/AdhocDispatch/AdhocDispatch.php @@ -4,6 +4,7 @@ use Fleetbase\FleetOps\Contracts\AdhocDispatchStrategy; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\Models\Company; /** * The registry of adhoc dispatch strategies, and which one an order uses. @@ -62,24 +63,44 @@ public static function has(?string $name): bool */ public static function nameFor(Order $order): string { - $candidates = [ - $order->adhoc_strategy, - $order->config()?->adhoc_strategy, - data_get($order, 'company.options.fleetops.adhoc_strategy'), - ]; - - foreach ($candidates as $name) { + foreach ([$order->adhoc_strategy, $order->config()?->adhoc_strategy] as $name) { if (static::has($name)) { return $name; } } - return self::DEFAULT; + return static::companyDefault($order->company); + } + + /** + * The company's default strategy (`fleetops.adhoc_strategy`), or the default when it has none. + */ + public static function companyDefault(?Company $company): string + { + $name = $company?->getOption('fleetops.adhoc_strategy'); + + return static::has($name) ? $name : self::DEFAULT; } public static function for(Order $order): AdhocDispatchStrategy { - return app(static::$strategies[static::nameFor($order)]); + return static::strategy(static::nameFor($order)); + } + + /** + * The registered strategy of that name. + */ + public static function strategy(string $name): AdhocDispatchStrategy + { + return app(static::$strategies[$name]); + } + + /** + * Strategies whose orders drivers see without holding an offer. + */ + public static function openlyListed(): array + { + return array_values(array_filter(static::names(), fn (string $name) => static::strategy($name)->listsOpenly())); } /** @@ -87,7 +108,7 @@ public static function for(Order $order): AdhocDispatchStrategy */ public static function offerTimeout(Order $order): int { - $timeout = $order->config()?->adhoc_offer_timeout ?? data_get($order, 'company.options.fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; + $timeout = $order->config()?->adhoc_offer_timeout ?? $order->company?->getOption('fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; return max(self::MIN_OFFER_TIMEOUT, min(self::MAX_OFFER_TIMEOUT, (int) $timeout)); } diff --git a/server/src/Support/AdhocDispatch/AdhocOfferListing.php b/server/src/Support/AdhocDispatch/AdhocOfferListing.php new file mode 100644 index 000000000..badebe027 --- /dev/null +++ b/server/src/Support/AdhocDispatch/AdhocOfferListing.php @@ -0,0 +1,82 @@ +getModel()->getTable(); + $names = AdhocDispatch::names(); + $open = AdhocDispatch::openlyListed(); + $inNames = implode(', ', array_fill(0, count($names), '?')); + $strategy = "CASE WHEN {$orders}.adhoc_strategy IN ({$inNames}) THEN {$orders}.adhoc_strategy" + . " WHEN (SELECT oc.adhoc_strategy FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid) IN ({$inNames})" + . " THEN (SELECT oc.adhoc_strategy FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid) ELSE ? END"; + $bindings = [...$names, ...$names, AdhocDispatch::companyDefault($company)]; + + return $query->where(function ($query) use ($orders, $driverUuid, $open, $strategy, $bindings) { + $query->whereNull("{$orders}.adhoc") + ->orWhere("{$orders}.adhoc", 0) + ->orWhereNotNull("{$orders}.driver_assigned_uuid") + ->orWhereExists(fn ($offers) => static::offersOf($offers, $orders, $driverUuid) + ->where('order_offers.status', OrderOffer::PENDING) + ->where(fn ($expiry) => $expiry->whereNull('order_offers.expires_at')->orWhere('order_offers.expires_at', '>', now()))); + + if ($open !== []) { + $query->orWhere(function ($query) use ($orders, $driverUuid, $open, $strategy, $bindings) { + $query->whereRaw("({$strategy}) IN (" . implode(', ', array_fill(0, count($open), '?')) . ')', [...$bindings, ...$open]) + ->whereNotExists(fn ($offers) => static::offersOf($offers, $orders, $driverUuid)->where('order_offers.status', OrderOffer::DECLINED)); + }); + } + }); + } + + /** + * Put each order's open offer for the driver on it (`adhocOffer`), for the order resource's `adhoc_offer`. + */ + public static function attach(iterable $orders, string $driverUuid): void + { + // A page of results is a paginator, whose array form wraps the orders. + $orders = $orders instanceof AbstractPaginator ? $orders->getCollection() : collect($orders); + $offers = OrderOffer::where('driver_uuid', $driverUuid) + ->whereIn('order_uuid', $orders->pluck('uuid')->filter()->all()) + ->where('status', OrderOffer::PENDING) + ->get() + ->keyBy('order_uuid'); + + foreach ($orders as $order) { + $order->setRelation('adhocOffer', $offers->get($order->uuid)); + } + } + + /** + * The driver's open offer as the order resource shows it. + */ + public static function present(?OrderOffer $offer): ?array + { + return $offer ? ['status' => $offer->status, 'expires_at' => $offer->expires_at?->toISOString()] : null; + } + + protected static function offersOf($offers, string $orders, string $driverUuid) + { + return $offers->selectRaw('1') + ->from('order_offers') + ->whereColumn('order_offers.order_uuid', "{$orders}.uuid") + ->where('order_offers.driver_uuid', $driverUuid) + ->whereNull('order_offers.deleted_at'); + } +} diff --git a/server/src/Support/AdhocDispatch/BroadcastStrategy.php b/server/src/Support/AdhocDispatch/BroadcastStrategy.php index dd3c5f626..70a698d40 100644 --- a/server/src/Support/AdhocDispatch/BroadcastStrategy.php +++ b/server/src/Support/AdhocDispatch/BroadcastStrategy.php @@ -23,6 +23,11 @@ public function name(): string return AdhocDispatch::BROADCAST; } + public function listsOpenly(): bool + { + return true; + } + public function dispatch(Order $order): void { $this->offer($order); diff --git a/server/src/Support/AdhocDispatch/SequentialStrategy.php b/server/src/Support/AdhocDispatch/SequentialStrategy.php index be00e9931..4d60ef940 100644 --- a/server/src/Support/AdhocDispatch/SequentialStrategy.php +++ b/server/src/Support/AdhocDispatch/SequentialStrategy.php @@ -25,6 +25,11 @@ public function name(): string return AdhocDispatch::SEQUENTIAL; } + public function listsOpenly(): bool + { + return false; + } + public function dispatch(Order $order): void { if (!OrderOffer::where('order_uuid', $order->uuid)->exists()) { diff --git a/server/tests/CommandContractsTest.php b/server/tests/CommandContractsTest.php index d4c98eea4..0d873cd72 100644 --- a/server/tests/CommandContractsTest.php +++ b/server/tests/CommandContractsTest.php @@ -420,6 +420,11 @@ public function name(): string return 'fake'; } + public function listsOpenly(): bool + { + return false; + } + public function dispatch(Order $order): void { } diff --git a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php index 87dc1367b..09a20f049 100644 --- a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php @@ -135,7 +135,7 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); $tables = [ - 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'payload_uuid', 'driver_assigned_uuid', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'tracking_number_uuid', 'status', 'pod_required', 'dispatched', 'scheduled_at', 'type'], + 'orders' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'order_config_uuid', 'adhoc', 'adhoc_strategy', 'payload_uuid', 'driver_assigned_uuid', 'customer_uuid', 'customer_type', 'facilitator_uuid', 'facilitator_type', 'tracking_number_uuid', 'status', 'pod_required', 'dispatched', 'scheduled_at', 'type'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'return_uuid', 'current_waypoint_uuid', 'type'], 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'street1', 'city', 'country', 'location', 'meta'], 'waypoints' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'place_uuid'], @@ -146,6 +146,8 @@ public function __call($method, $arguments) 'vendors' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'name'], 'integrated_vendors' => ['uuid', 'public_id', 'company_uuid', 'provider'], 'companies' => ['uuid', 'public_id', 'name', 'options'], + 'order_configs' => ['uuid', 'company_uuid', 'adhoc_strategy'], + 'order_offers' => ['uuid', 'order_uuid', 'driver_uuid', 'status', 'expires_at'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'owner_type', 'status_uuid', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'code', 'status', 'details'], 'directives' => ['uuid', 'company_uuid', 'permission_uuid', 'subject_type', 'subject_uuid', 'key', 'rules'], diff --git a/server/tests/Feature/RidesTest.php b/server/tests/Feature/RidesTest.php index 8a2b737be..c0b5a46be 100644 --- a/server/tests/Feature/RidesTest.php +++ b/server/tests/Feature/RidesTest.php @@ -1083,3 +1083,58 @@ function ridesJson($response): array expect(json_decode($connection->table('orders')->value('meta'), true)['fare']['final'])->toBeTrue() ->and(RideOffersRecorder::$notified)->toBe([['contact-sam', Fleetbase\FleetOps\Notifications\RideUpdate::class]]); }); + +test('a driver listing nearby orders sees only the adhoc orders they could take', function () { + $connection = rideOffersBoot(); + rideOffersSeedDrivers($connection); + $connection->table('orders')->insert([ + ['uuid' => 'o-held', 'public_id' => 'order_held', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-ride', 'adhoc_strategy' => null], + ['uuid' => 'o-other', 'public_id' => 'order_other', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-ride', 'adhoc_strategy' => null], + ['uuid' => 'o-lapsed', 'public_id' => 'order_lapsed', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'sequential'], + ['uuid' => 'o-open', 'public_id' => 'order_open', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-refused', 'public_id' => 'order_refused', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-default', 'public_id' => 'order_default', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ['uuid' => 'o-planned', 'public_id' => 'order_planned', 'company_uuid' => 'company-1', 'adhoc' => 0, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ]); + $connection->table('orders')->insert(['uuid' => 'o-taken', 'public_id' => 'order_taken', 'company_uuid' => 'company-1', 'adhoc' => 1, 'driver_assigned_uuid' => 'chen']); + $connection->table('order_offers')->insert([ + ['uuid' => 'f1', 'order_uuid' => 'o-held', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f2', 'order_uuid' => 'o-other', 'driver_uuid' => 'chen', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f3', 'order_uuid' => 'o-lapsed', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2020-01-01 00:00:00'], + ['uuid' => 'f4', 'order_uuid' => 'o-refused', 'driver_uuid' => 'amara', 'status' => 'declined', 'expires_at' => null], + ]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + $listed = fn ($company) => Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::apply(Order::query()->withoutGlobalScopes(), 'amara', $company)->orderBy('id')->pluck('public_id')->all(); + + // One at a time by default: Amara sees her own open offer, the open order she didn't decline, + // planned orders, and an order someone already took. + expect($listed($company))->toBe(['order_held', 'order_open', 'order_planned', 'order_taken']); + + // With the company defaulting to everyone at once, unset orders show too. + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast']])]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + expect($listed($company))->toBe(['order_held', 'order_open', 'order_default', 'order_planned', 'order_taken']); + + // Each order carries Amara's open offer, or none. + $orders = Order::withoutGlobalScopes()->whereIn('uuid', ['o-held', 'o-open'])->orderBy('id')->get(); + Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::attach($orders, 'amara'); + expect($orders[0]->adhocOffer->uuid)->toBe('f1') + ->and($orders[1]->adhocOffer)->toBeNull() + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present($orders[0]->adhocOffer))->toBe(['status' => 'pending', 'expires_at' => '2099-01-01T00:00:00.000000Z']) + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present(null))->toBeNull(); +}); + +test('only a strategy that lists openly shows orders without an offer, and a driver is found by public id', function () { + rideOffersBoot(); + rideOffersSeedDrivers(Illuminate\Support\Facades\DB::connection()); + $helper = new ReflectionMethod(Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController::class, 'nearbyDriverUuid'); + $ask = fn ($nearby) => $helper->invoke(new Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController(), Illuminate\Http\Request::create('/', 'GET', ['nearby' => $nearby])); + + expect(AdhocDispatch::openlyListed())->toBe(['broadcast']) + ->and((new BroadcastStrategy())->listsOpenly())->toBeTrue() + ->and((new SequentialStrategy())->listsOpenly())->toBeFalse() + ->and($ask('driver_amara'))->toBe('amara') + ->and($ask('driver_rival'))->toBeNull() + ->and($ask('1.28,103.85'))->toBeNull() + ->and($ask(null))->toBeNull(); +}); From df31112ab620d7d9f989fc0b964968a069022aa2 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Fri, 6 Nov 2026 13:55:19 +0800 Subject: [PATCH 18/29] feat(dispatch): dispatch settings, console screens, offer-closed events and rider data out of meta MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Strategies and settings: - Strategies have a `label()` and `description()`. `settings/adhoc-dispatch-strategies` lists them. - `settings/adhoc-dispatch-settings` reads and saves the company defaults: ping radius, strategy and offer time. - Order configs drop an unknown strategy and keep the offer time between 10 and 120 seconds. - `order.offer_closed` tells a driver's app when their offer expired or was withdrawn. Console: - A Settings → Dispatch page. - An "Adhoc dispatch" section in the order config editor. - A strategy and vehicle type on the order form, for adhoc orders. Rider data moves out of order meta, and #424's migrations become one: - The payment method is kept on the payload. - The final fare is the final quote, which records its distance and time, marked by `fare_finalized_at` and read with `Order::fare()`. - Ratings go in `driver_ratings`, with each driver's average and count on `drivers`. - The chat channel is `orders.chat_channel_uuid`. - Payment is `orders.paid_at`, set with `Order::markPaid()`. - The dispatch outcome is worked out from the offers. - Fare previews return seats and pickup ETA as quote fields. - Riders get these as top-level fields (`RiderOrder`). --- addon/components/layout/fleet-ops-sidebar.js | 14 +- .../order-config-manager/details.hbs | 43 +++++ .../order-config-manager/details.js | 32 ++++ addon/components/order/form/details.hbs | 19 +++ addon/components/order/form/details.js | 26 +++ addon/controllers/settings/dispatch.js | 56 +++++++ addon/routes.js | 1 + addon/routes/settings/dispatch.js | 16 ++ addon/templates/settings/dispatch.hbs | 48 ++++++ app/controllers/settings/dispatch.js | 1 + app/routes/settings/dispatch.js | 1 + app/templates/settings/dispatch.js | 1 + ..._11_06_000001_adhoc_dispatch_and_rides.php | 89 +++++++++++ ...11_06_000001_create_order_offers_table.php | 35 ---- ...1_06_000002_add_adhoc_dispatch_columns.php | 41 ----- .../src/Contracts/AdhocDispatchStrategy.php | 10 ++ server/src/Events/OrderOfferClosed.php | 62 ++++++++ .../Controllers/Api/v1/CustomerController.php | 50 +++--- .../Api/v1/ServiceQuoteController.php | 4 +- .../Internal/v1/SettingController.php | 53 +++++++ .../Internal/CreateOrderConfigRequest.php | 5 + server/src/Http/Resources/v1/RiderOrder.php | 23 +++ server/src/Http/Resources/v1/ServiceQuote.php | 2 + server/src/Models/Driver.php | 4 + server/src/Models/DriverRating.php | 32 ++++ server/src/Models/Order.php | 90 +++++++++-- server/src/Models/OrderConfig.php | 17 ++ server/src/Models/ServiceQuote.php | 10 +- .../Support/AdhocDispatch/AdhocDispatch.php | 14 ++ .../AdhocDispatch/BroadcastStrategy.php | 10 ++ .../AdhocDispatch/SequentialStrategy.php | 11 ++ server/src/Support/OrderOffers.php | 49 +++++- server/src/Support/Rides/DriverRatings.php | 62 ++++---- server/src/Support/Rides/FinalFare.php | 13 +- server/src/Support/Rides/RideChat.php | 5 +- server/src/Support/Rides/RideUpdates.php | 3 +- server/src/routes.php | 3 + .../ApiCustomerControllerContractsTest.php | 22 ++- server/tests/CommandContractsTest.php | 10 ++ .../CompactResourceSerializationTest.php | 40 +++++ server/tests/Feature/RidesTest.php | 150 ++++++++++++++---- .../tests/SettingControllerContractsTest.php | 45 ++++++ .../controllers/settings/dispatch-test.js | 74 +++++++++ translations/en-us.yaml | 27 ++++ 44 files changed, 1122 insertions(+), 201 deletions(-) create mode 100644 addon/controllers/settings/dispatch.js create mode 100644 addon/routes/settings/dispatch.js create mode 100644 addon/templates/settings/dispatch.hbs create mode 100644 app/controllers/settings/dispatch.js create mode 100644 app/routes/settings/dispatch.js create mode 100644 app/templates/settings/dispatch.js create mode 100644 server/migrations/2026_11_06_000001_adhoc_dispatch_and_rides.php delete mode 100644 server/migrations/2026_11_06_000001_create_order_offers_table.php delete mode 100644 server/migrations/2026_11_06_000002_add_adhoc_dispatch_columns.php create mode 100644 server/src/Events/OrderOfferClosed.php create mode 100644 server/src/Http/Resources/v1/RiderOrder.php create mode 100644 server/src/Models/DriverRating.php create mode 100644 tests/unit/controllers/settings/dispatch-test.js diff --git a/addon/components/layout/fleet-ops-sidebar.js b/addon/components/layout/fleet-ops-sidebar.js index 6c643569d..47cf18d29 100644 --- a/addon/components/layout/fleet-ops-sidebar.js +++ b/addon/components/layout/fleet-ops-sidebar.js @@ -206,6 +206,7 @@ export default class LayoutFleetOpsSidebarComponent extends Component { this.createItem('menu.payments', 'cash-register', 'settings.payments', 'fleet-ops view payments', 'fleet-ops see payments'), this.createItem('menu.notifications', 'bell', 'settings.notifications', 'fleet-ops view notification-settings', 'fleet-ops see notification-settings'), this.createItem('menu.routing', 'route', 'settings.routing', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), + this.createItem('menu.dispatch', 'paper-plane', 'settings.dispatch', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), this.createItem('menu.orchestrator', 'circle-nodes', 'settings.orchestrator', 'fleet-ops view routing-settings', 'fleet-ops see routing-settings'), this.createItem('menu.scheduling', 'calendar-days', 'settings.scheduling', 'fleet-ops view scheduling-settings', 'fleet-ops see scheduling-settings'), this.createItem( @@ -411,12 +412,13 @@ export default class LayoutFleetOpsSidebarComponent extends Component { 'settings.payments': 3, 'settings.notifications': 4, 'settings.routing': 5, - 'settings.orchestrator': 6, - 'settings.scheduling': 7, - 'settings.tracking-page': 8, - 'settings.telematics': 9, - 'settings.custom-fields': 10, - 'settings.avatars': 11, + 'settings.dispatch': 6, + 'settings.orchestrator': 7, + 'settings.scheduling': 8, + 'settings.tracking-page': 9, + 'settings.telematics': 10, + 'settings.custom-fields': 11, + 'settings.avatars': 12, }; return priorities[route] ?? 0; diff --git a/addon/components/order-config-manager/details.hbs b/addon/components/order-config-manager/details.hbs index dc7eb7e42..52753347a 100644 --- a/addon/components/order-config-manager/details.hbs +++ b/addon/components/order-config-manager/details.hbs @@ -23,6 +23,49 @@ + + {{#let (cannot "fleet-ops update order-config") as |disabled|}} + + + +
{{t "order.fields.adhoc-ping-message"}} diff --git a/addon/components/order/form/details.js b/addon/components/order/form/details.js index 2a56f8ef0..ac58a3cc2 100644 --- a/addon/components/order/form/details.js +++ b/addon/components/order/form/details.js @@ -14,11 +14,37 @@ export default class OrderFormDetailsComponent extends Component { @service leafletLayerVisibilityManager; @service currentUser; @service orderPresentation; + @service fetch; + @service intl; @tracked customFields; + @tracked adhocStrategies = []; constructor() { super(...arguments); this.orderConfigActions.loadAll.perform(); + this.loadAdhocStrategies.perform(); + } + + /** Strategy choices for an adhoc order, with the default first. An empty name stands for no strategy of the order's own. */ + get adhocStrategyOptions() { + return [{ name: '', label: this.intl.t('order.fields.adhoc-strategy-default') }, ...this.adhocStrategies]; + } + + get adhocStrategy() { + return this.args.resource?.adhoc_strategy ?? ''; + } + + @action setAdhocStrategy(name) { + this.args.resource.adhoc_strategy = name || null; + } + + @task *loadAdhocStrategies() { + try { + const { strategies } = yield this.fetch.get('fleet-ops/settings/adhoc-dispatch-strategies'); + this.adhocStrategies = strategies ?? []; + } catch { + this.adhocStrategies = []; + } } /** The presentation profile applying to the order's current config, if any. */ diff --git a/addon/controllers/settings/dispatch.js b/addon/controllers/settings/dispatch.js new file mode 100644 index 000000000..a3daa92a7 --- /dev/null +++ b/addon/controllers/settings/dispatch.js @@ -0,0 +1,56 @@ +import Controller from '@ember/controller'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { task } from 'ember-concurrency'; + +/** + * How adhoc orders, those without an assigned driver, are offered to drivers by default. Order + * configs and single orders can choose otherwise. + */ +export default class SettingsDispatchController extends Controller { + @service fetch; + @service notifications; + @service intl; + @tracked adhocDistance = 6000; + @tracked adhocStrategy = 'sequential'; + @tracked adhocOfferTimeout = 20; + @tracked strategies = []; + + constructor() { + super(...arguments); + this.getSettings.perform(); + } + + get selectedStrategy() { + return this.strategies.find((strategy) => strategy.name === this.adhocStrategy); + } + + get usesOfferTimeout() { + return this.adhocStrategy === 'sequential'; + } + + @task *getSettings() { + try { + const settings = yield this.fetch.get('fleet-ops/settings/adhoc-dispatch-settings'); + this.adhocDistance = settings.adhoc_distance; + this.adhocStrategy = settings.adhoc_strategy; + this.adhocOfferTimeout = settings.adhoc_offer_timeout; + this.strategies = settings.strategies ?? []; + } catch (error) { + this.notifications.serverError(error); + } + } + + @task *saveSettings() { + try { + yield this.fetch.post('fleet-ops/settings/adhoc-dispatch-settings', { + adhoc_distance: Number(this.adhocDistance), + adhoc_strategy: this.adhocStrategy, + adhoc_offer_timeout: Number(this.adhocOfferTimeout), + }); + this.notifications.success(this.intl.t('settings.dispatch.saved')); + } catch (error) { + this.notifications.serverError(error); + } + } +} diff --git a/addon/routes.js b/addon/routes.js index 5dc216772..6130c28c1 100644 --- a/addon/routes.js +++ b/addon/routes.js @@ -320,6 +320,7 @@ export default buildRoutes(function () { this.route('custom-fields'); this.route('avatars'); this.route('routing'); + this.route('dispatch'); this.route('map'); this.route('orchestrator'); this.route('scheduling'); diff --git a/addon/routes/settings/dispatch.js b/addon/routes/settings/dispatch.js new file mode 100644 index 000000000..81cdc1891 --- /dev/null +++ b/addon/routes/settings/dispatch.js @@ -0,0 +1,16 @@ +import Route from '@ember/routing/route'; +import { inject as service } from '@ember/service'; + +export default class SettingsDispatchRoute extends Route { + @service notifications; + @service hostRouter; + @service abilities; + @service intl; + + beforeModel() { + if (this.abilities.cannot('fleet-ops view routing-settings')) { + this.notifications.warning(this.intl.t('common.unauthorized-access')); + return this.hostRouter.transitionTo('console.fleet-ops'); + } + } +} diff --git a/addon/templates/settings/dispatch.hbs b/addon/templates/settings/dispatch.hbs new file mode 100644 index 000000000..ac3701951 --- /dev/null +++ b/addon/templates/settings/dispatch.hbs @@ -0,0 +1,48 @@ + + + {{/if}} + + {{/each}} +
+
+ {{/each}} + + {{#if this.canEdit}} +
+
+ {{/if}} + \ No newline at end of file diff --git a/addon/components/order-config-manager/policies.js b/addon/components/order-config-manager/policies.js new file mode 100644 index 000000000..6e03ac0e6 --- /dev/null +++ b/addon/components/order-config-manager/policies.js @@ -0,0 +1,198 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action, get } from '@ember/object'; +import { task } from 'ember-concurrency'; +import humanize from '@fleetbase/ember-core/utils/humanize'; + +/** + * Manages an order config's policies: the settings that decide how its orders behave, such as how + * adhoc orders are offered, what customers may do and whether a completed order is priced again. + * The policies and their settings come from the server (`order-configs/capabilities`), so a policy + * an extension registers shows up here too. A setting left at its default isn't stored. + * + * @extends Component + */ +export default class OrderConfigManagerPoliciesComponent extends Component { + @service fetch; + @service notifications; + @service abilities; + @service intl; + + /** The config being managed. */ + @tracked config; + + /** The registered policies, each with its settings. */ + @tracked policies = []; + + /** Working copy of the config's stored policies. */ + @tracked values = {}; + + /** Stored policies as last saved, serialized, to tell whether there is anything to save. */ + @tracked saved = '{}'; + + constructor(owner, { config, configManagerContext }) { + super(...arguments); + this.changeConfig(config); + this.loadPolicies.perform(); + + configManagerContext.on('onConfigChanged', (newConfig) => { + this.changeConfig(newConfig); + }); + } + + get canEdit() { + return this.abilities.can('fleet-ops update order-config'); + } + + get isDirty() { + return JSON.stringify(this.values) !== this.saved; + } + + /** The config's activities, for settings that name one. */ + get activityChoices() { + return Object.values(this.config?.flow ?? {}) + .filter((activity) => activity && activity.code) + .map((activity) => ({ value: activity.code, label: activity.status || activity.code })); + } + + /** Policies with each setting's current value and choices, for the template. */ + get rows() { + return this.policies.map((policy) => ({ + ...policy, + settings: (policy.settings ?? []).map((setting) => ({ + ...setting, + label: humanize(setting.name), + value: this.valueOf(policy.key, setting), + isSet: this.storedValue(policy.key, setting.name) !== undefined, + options: this.optionsFor(setting), + })), + })); + } + + storedValue(policyKey, name) { + return this.values?.[policyKey]?.[name]; + } + + valueOf(policyKey, setting) { + const stored = this.storedValue(policyKey, setting.name); + return stored === undefined ? setting.default : stored; + } + + optionsFor(setting) { + if (setting.type !== 'choice') { + return null; + } + + const choices = setting.choices === 'activity' ? this.activityChoices : (setting.choices ?? []); + return [{ value: null, label: this.intl.t('order-config-manager.policies.default') }, ...choices]; + } + + @action setValue(policyKey, name, value) { + const policy = { ...(this.values[policyKey] ?? {}) }; + if (value === '' || value === undefined) { + delete policy[name]; + } else { + policy[name] = value; + } + + this.values = { ...this.values, [policyKey]: policy }; + } + + @action setNumber(policyKey, name, event) { + const raw = event?.target?.value ?? event; + this.setValue(policyKey, name, raw === '' || raw === null ? undefined : Number(raw)); + } + + @action setText(policyKey, name, event) { + this.setValue(policyKey, name, event?.target?.value ?? event); + } + + @action addListItem(policyKey, setting, item) { + const list = [...(this.valueOf(policyKey, setting) ?? [])]; + if (item && !list.includes(item)) { + list.push(item); + } + this.setValue(policyKey, setting.name, list); + } + + @action removeListItem(policyKey, setting, index) { + const list = [...(this.valueOf(policyKey, setting) ?? [])]; + list.splice(index, 1); + this.setValue(policyKey, setting.name, list); + } + + @action reset(policyKey, name) { + this.setValue(policyKey, name, undefined); + } + + @task *loadPolicies() { + try { + const { policies } = yield this.fetch.get('order-configs/capabilities'); + this.policies = policies ?? []; + this.changeConfig(this.config); + } catch (error) { + this.policies = []; + this.notifications.serverError(error); + } + } + + @task *save() { + this.config.policies = this.merge(this.config.policies, this.values); + + try { + yield this.config.save(); + this.saved = JSON.stringify(this.values); + this.notifications.success(this.intl.t('order-config-manager.saved-success-message', { orderConfigName: this.config.name })); + if (typeof this.args.onConfigUpdated === 'function') { + this.args.onConfigUpdated(this.config); + } + } catch (error) { + this.notifications.serverError(error); + } + } + + /** + * The stored policies with the edited ones written in, nested by key as the server keeps them + * (`dispatch.adhoc` under `dispatch`). Policies this console doesn't know are kept as they are. + */ + merge(stored, values) { + const nested = JSON.parse(JSON.stringify(stored ?? {})); + for (const policy of this.policies) { + const path = policy.key.split('.'); + let node = nested; + path.slice(0, -1).forEach((segment) => { + node[segment] = node[segment] && typeof node[segment] === 'object' ? node[segment] : {}; + node = node[segment]; + }); + + const settings = values[policy.key] ?? {}; + if (Object.keys(settings).length) { + node[path[path.length - 1]] = settings; + } else { + delete node[path[path.length - 1]]; + } + } + + return nested; + } + + /** The stored settings of each known policy, keyed by policy key, for editing. */ + flatten(stored) { + const flat = {}; + for (const policy of this.policies) { + const settings = get(stored ?? {}, policy.key); + if (settings && typeof settings === 'object' && !Array.isArray(settings)) { + flat[policy.key] = { ...settings }; + } + } + + return flat; + } + + changeConfig(config) { + this.config = config; + this.values = this.flatten(config?.policies ?? {}); + this.saved = JSON.stringify(this.values); + } +} diff --git a/addon/components/order-config-manager/triggers.hbs b/addon/components/order-config-manager/triggers.hbs new file mode 100644 index 000000000..f77f7e3e9 --- /dev/null +++ b/addon/components/order-config-manager/triggers.hbs @@ -0,0 +1,98 @@ +
+ +

{{t "order-config-manager.triggers.description"}}

+ + {{#if this.loadCapabilities.isRunning}} +
+ {{else}} +
+ {{#each this.editableRows as |row|}} +
+
+ + + +
+ {{#if this.canEdit}} +
+
+ + {{#if row.isApproaching}} +
+ + + + + + +
+ {{/if}} + + {{#if row.parameters.length}} +
+ {{#each row.parameters as |parameter|}} + + + + {{/each}} +
+ {{/if}} + + {{#if row.conditionCount}} +

{{t "order-config-manager.triggers.conditions" count=row.conditionCount}}

+ {{/if}} +
+ {{else}} +

{{t "order-config-manager.triggers.empty"}}

+ {{/each}} +
+ + {{#if this.canEdit}} +
+
+ {{/if}} + {{/if}} +
+
\ No newline at end of file diff --git a/addon/components/order-config-manager/triggers.js b/addon/components/order-config-manager/triggers.js new file mode 100644 index 000000000..e6054856a --- /dev/null +++ b/addon/components/order-config-manager/triggers.js @@ -0,0 +1,221 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { task } from 'ember-concurrency'; +import humanize from '@fleetbase/ember-core/utils/humanize'; + +const ACTIVITY_PREFIX = 'activity:'; + +/** + * Manages what an order config does when things happen to its orders: when an order reaches one + * of its activities (the activity's `actions` in the flow) or on an order event such as + * `order.created` or `driver.approaching` (the config's `triggers`). Both are edited here as one + * list of "when ..., do ..." rows. The actions and events come from the server + * (`order-configs/capabilities`), so an extension's actions show up too. + * + * A trigger's conditions (`when`) are kept as they are; they are set through the API. + * + * @extends Component + */ +export default class OrderConfigManagerTriggersComponent extends Component { + @service fetch; + @service notifications; + @service abilities; + @service intl; + + /** The config being managed. */ + @tracked config; + + /** The registered actions and trigger events. */ + @tracked actions = []; + @tracked events = []; + + /** Working list of triggers: `{ id, on, action, params, options, when }`. */ + @tracked rows = []; + + /** Rows as last saved, serialized, to tell whether there is anything to save. */ + @tracked saved = '[]'; + + constructor(owner, { config, configManagerContext }) { + super(...arguments); + this.changeConfig(config); + this.loadCapabilities.perform(); + + configManagerContext.on('onConfigChanged', (newConfig) => { + this.changeConfig(newConfig); + }); + } + + get canEdit() { + return this.abilities.can('fleet-ops update order-config'); + } + + get isDirty() { + return JSON.stringify(this.serialize(this.rows)) !== this.saved; + } + + /** What a trigger can run on: reaching an activity, or an order event. */ + get eventOptions() { + const activities = Object.values(this.config?.flow ?? {}) + .filter((activity) => activity && activity.code) + .map((activity) => ({ + value: ACTIVITY_PREFIX + activity.code, + label: this.intl.t('order-config-manager.triggers.reaches-activity', { activity: activity.status || activity.code }), + })); + const events = this.events.map((event) => ({ value: event, label: this.intl.t(`order-config-manager.triggers.events.${event}`, { default: humanize(event) }) })); + + return [...activities, ...events]; + } + + get actionOptions() { + return this.actions.map((action) => ({ value: action.name, label: action.label })); + } + + /** Rows with what the template needs to show each one. */ + get editableRows() { + return this.rows.map((row) => { + const definition = this.actions.find((action) => action.name === row.action); + return { + ...row, + parameters: Object.entries(definition?.parameters ?? {}).map(([name, description]) => ({ name, description, label: humanize(name), value: row.params?.[name] ?? '' })), + isApproaching: row.on === 'driver.approaching', + conditionCount: Array.isArray(row.when) ? row.when.length : 0, + }; + }); + } + + @action addRow() { + this.rows = [ + ...this.rows, + { id: this.nextId(), on: this.eventOptions[0]?.value ?? 'order.created', action: this.actionOptions[0]?.value ?? 'notify_customer', params: {}, options: {}, when: [] }, + ]; + } + + @action removeRow(id) { + this.rows = this.rows.filter((row) => row.id !== id); + } + + @action setRowField(id, field, value) { + this.rows = this.rows.map((row) => (row.id === id ? { ...row, [field]: value } : row)); + } + + @action setParam(id, name, event) { + const value = event?.target?.value ?? event; + this.rows = this.rows.map((row) => (row.id === id ? { ...row, params: { ...row.params, [name]: value } } : row)); + } + + @action setOption(id, name, event) { + let value = event?.target?.value ?? event; + if (name === 'distance') { + value = value === '' ? undefined : Number(value); + } + this.rows = this.rows.map((row) => (row.id === id ? { ...row, options: { ...row.options, [name]: value } } : row)); + } + + @task *loadCapabilities() { + try { + const { actions, events } = yield this.fetch.get('order-configs/capabilities'); + this.actions = actions ?? []; + this.events = events ?? []; + } catch (error) { + this.notifications.serverError(error); + } + } + + @task *save() { + const { triggers, flow } = this.split(this.rows); + this.config.triggers = triggers; + this.config.flow = flow; + + try { + yield this.config.save(); + this.saved = JSON.stringify(this.serialize(this.rows)); + this.notifications.success(this.intl.t('order-config-manager.saved-success-message', { orderConfigName: this.config.name })); + if (typeof this.args.onConfigUpdated === 'function') { + this.args.onConfigUpdated(this.config); + } + } catch (error) { + this.notifications.serverError(error); + } + } + + /** The rows as the server keeps them: activity rows in the flow, the rest in `triggers`. */ + split(rows) { + const flow = JSON.parse(JSON.stringify(this.config.flow ?? {})); + Object.values(flow).forEach((activity) => { + if (activity && typeof activity === 'object') { + activity.actions = []; + } + }); + + const triggers = []; + for (const row of this.serialize(rows)) { + const { on, ...trigger } = row; + if (on.startsWith(ACTIVITY_PREFIX)) { + const activity = flow[on.slice(ACTIVITY_PREFIX.length)]; + if (activity) { + delete trigger.options; + activity.actions.push(trigger); + } + } else { + triggers.push({ event: on, ...trigger }); + } + } + + return { triggers, flow }; + } + + /** Rows without their editor ids and empty values. */ + serialize(rows) { + return rows.map(({ on, action, params, options, when }) => { + const row = { on, action }; + const cleanParams = Object.fromEntries(Object.entries(params ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); + const cleanOptions = Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); + if (Object.keys(cleanParams).length) { + row.params = cleanParams; + } + if (on === 'driver.approaching' && Object.keys(cleanOptions).length) { + row.options = cleanOptions; + } + if (Array.isArray(when) && when.length) { + row.when = when; + } + + return row; + }); + } + + /** The config's triggers and its activities' actions as one list of rows. */ + read(config) { + const rows = []; + Object.values(config?.flow ?? {}).forEach((activity) => { + (activity?.actions ?? []).forEach((trigger) => { + rows.push({ id: this.nextId(), on: ACTIVITY_PREFIX + activity.code, action: trigger.action, params: { ...(trigger.params ?? {}) }, options: {}, when: trigger.when ?? [] }); + }); + }); + (config?.triggers ?? []).forEach((trigger) => { + rows.push({ + id: this.nextId(), + on: trigger.event, + action: trigger.action, + params: { ...(trigger.params ?? {}) }, + options: { ...(trigger.options ?? {}) }, + when: trigger.when ?? [], + }); + }); + + return rows; + } + + nextId() { + this._id = (this._id ?? 0) + 1; + return this._id; + } + + changeConfig(config) { + this.config = config; + this.rows = this.read(config); + this.saved = JSON.stringify(this.serialize(this.rows)); + } +} diff --git a/addon/components/tracking-page.js b/addon/components/tracking-page.js index 27ce9acc6..349e730b5 100644 --- a/addon/components/tracking-page.js +++ b/addon/components/tracking-page.js @@ -170,7 +170,7 @@ export default class TrackingPageComponent extends Component { return; } - // A rider's shared link opens their live view on this device first. + // A customer's shared link opens their live view on this device first. const share = this.urlSearchParams.get('share'); if (this.trackingInput && share) { try { diff --git a/server/migrations/2026_11_06_000001_adhoc_dispatch_and_rides.php b/server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php similarity index 75% rename from server/migrations/2026_11_06_000001_adhoc_dispatch_and_rides.php rename to server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php index 1f4b4c639..5c03618ba 100644 --- a/server/migrations/2026_11_06_000001_adhoc_dispatch_and_rides.php +++ b/server/migrations/2026_11_06_000001_adhoc_dispatch_and_order_config_policies.php @@ -5,16 +5,15 @@ use Illuminate\Support\Facades\Schema; /** - * Adhoc dispatch strategies, and what a rider app needs around a ride. + * Adhoc dispatch strategies, order config policies and triggers, and driver ratings. * * - order_offers: who an adhoc order was offered to and how each driver answered. - * - orders: `adhoc_strategy` and `required_vehicle_type` for how the order is offered, - * `chat_channel_uuid` for its rider-driver chat, `fare_finalized_at` once its price is set - * from the trip, and `paid_at` once it is paid. - * - order_configs: the adhoc strategy and offer timeout for orders on the config, whether - * customers' orders are adhoc, and whether they are matched by vehicle type. + * - orders: `adhoc_strategy` and `required_vehicle_type` for how the order is offered, and + * `chat_channel_uuid` for its customer-driver chat. + * - order_configs: `policies`, the settings that decide how the config's orders behave, and + * `triggers`, the actions it runs on order events. * - service_quotes: the `distance` (metres) and `time` (seconds) a quote was priced on. - * - driver_ratings: a rider's stars for the driver of a finished order, with each driver's + * - driver_ratings: a customer's stars for the driver of a finished order, with each driver's * average and count kept on `drivers`. */ return new class extends Migration { @@ -55,15 +54,11 @@ public function up(): void $table->string('adhoc_strategy', 32)->nullable()->after('adhoc_distance'); $table->string('required_vehicle_type')->nullable()->after('adhoc_strategy'); $table->uuid('chat_channel_uuid')->nullable(); - $table->timestamp('fare_finalized_at')->nullable(); - $table->timestamp('paid_at')->nullable(); }); Schema::table('order_configs', function (Blueprint $table) { - $table->string('adhoc_strategy', 32)->nullable(); - $table->unsignedSmallInteger('adhoc_offer_timeout')->nullable(); - $table->boolean('customer_orders_adhoc')->default(false); - $table->boolean('match_vehicle_type')->default(false); + $table->json('policies')->nullable(); + $table->json('triggers')->nullable(); }); Schema::table('service_quotes', function (Blueprint $table) { @@ -81,8 +76,8 @@ public function down(): void { Schema::table('drivers', fn (Blueprint $table) => $table->dropColumn(['rating_average', 'rating_count'])); Schema::table('service_quotes', fn (Blueprint $table) => $table->dropColumn(['distance', 'time'])); - Schema::table('order_configs', fn (Blueprint $table) => $table->dropColumn(['adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type'])); - Schema::table('orders', fn (Blueprint $table) => $table->dropColumn(['adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid', 'fare_finalized_at', 'paid_at'])); + Schema::table('order_configs', fn (Blueprint $table) => $table->dropColumn(['policies', 'triggers'])); + Schema::table('orders', fn (Blueprint $table) => $table->dropColumn(['adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid'])); Schema::dropIfExists('driver_ratings'); Schema::dropIfExists('order_offers'); } diff --git a/server/src/Console/Commands/CreateOrderConfig.php b/server/src/Console/Commands/CreateOrderConfig.php new file mode 100644 index 000000000..3780198c3 --- /dev/null +++ b/server/src/Console/Commands/CreateOrderConfig.php @@ -0,0 +1,49 @@ +option('list') || !$this->argument('template')) { + $this->table(['Key', 'Name', 'Description'], OrderConfigTemplates::describe()); + + return self::SUCCESS; + } + + $key = (string) $this->argument('template'); + if (!OrderConfigTemplates::has($key)) { + $this->error('No order config template named ' . $key . '. Run with --list to see them.'); + + return self::FAILURE; + } + + $id = (string) $this->option('company'); + $company = $id !== '' ? Company::where('uuid', $id)->orWhere('public_id', $id)->first() : null; + if (!$company) { + $this->error($id === '' ? 'Give the company with --company.' : 'No company found for ' . $id . '.'); + + return self::FAILURE; + } + + $name = $this->option('name'); + $config = OrderConfigTemplates::create($key, $company, is_string($name) && trim($name) !== '' ? trim($name) : null); + + $this->info(($config->wasRecentlyCreated ? 'Created' : 'Found') . ' order config ' . $config->name . ' (' . $config->public_id . ', key ' . $config->key . ') for ' . $company->name . '.'); + + return self::SUCCESS; + } +} diff --git a/server/src/Console/Commands/CreateRideConfig.php b/server/src/Console/Commands/CreateRideConfig.php deleted file mode 100644 index 91baf9b68..000000000 --- a/server/src/Console/Commands/CreateRideConfig.php +++ /dev/null @@ -1,44 +0,0 @@ -argument('company'); - $company = Company::where('uuid', $id)->orWhere('public_id', $id)->first(); - if (!$company) { - $this->error('No company found for ' . $id . '.'); - - return self::FAILURE; - } - - $config = FleetOps::createRideConfig($company); - - // What the rider app shows from these settings: see customers/ride-settings. - $rider = array_filter([ - 'emergency_number' => $this->option('emergency-number'), - 'support_phone' => $this->option('support-phone'), - 'support_email' => $this->option('support-email'), - ], fn ($value) => is_string($value) && trim($value) !== ''); - if ($rider) { - $config->update(['meta' => array_replace_recursive((array) $config->meta, ['rider' => $rider])]); - } - $this->info('Ride config ' . $config->public_id . ' is ready for ' . $company->name . '.'); - - return self::SUCCESS; - } -} diff --git a/server/src/Contracts/OrderConfigAction.php b/server/src/Contracts/OrderConfigAction.php new file mode 100644 index 000000000..375b1407d --- /dev/null +++ b/server/src/Contracts/OrderConfigAction.php @@ -0,0 +1,32 @@ + description`. + */ + public function parameters(): array; + + /** + * Run the action for the order. The context names the event and, for an activity, its code, + * status and details. + */ + public function handle(Order $order, array $params = [], array $context = []): void; +} diff --git a/server/src/Contracts/OrderConfigPolicy.php b/server/src/Contracts/OrderConfigPolicy.php new file mode 100644 index 000000000..f860400c9 --- /dev/null +++ b/server/src/Contracts/OrderConfigPolicy.php @@ -0,0 +1,38 @@ +flow->getActivity($childActivityCode); // if waypoint context skip `created` - `started` - `dispatched` - if ($waypointContext && in_array($childActivity->code, ['created', 'started', 'dispatched'])) { + if ($childActivity && $waypointContext && in_array($childActivity->code, ['created', 'started', 'dispatched'])) { return $childActivity->getChildActivities($context); } diff --git a/server/src/Flow/Condition.php b/server/src/Flow/Condition.php index 80cb23199..fa6aa5a6a 100644 --- a/server/src/Flow/Condition.php +++ b/server/src/Flow/Condition.php @@ -10,6 +10,11 @@ class Condition extends FlowResource /** * Evaluate the condition against an order. * + * The field is read from the order (`Order::resolveDynamicValue()`: payload shortcuts such as + * `pickup.city`, attributes, the config's custom fields, meta, then relations). Strings compare + * without case. A list operator (`in`, `notIn`) takes the value as a list, or a comma + * separated string; `has` and `doesntHave` look for the value in a field that is a list. + * * @param Order $order the order to evaluate the condition against * * @return bool the result of the condition evaluation @@ -18,36 +23,37 @@ class Condition extends FlowResource */ public function eval(Order $order) { - $field = $this->field; $operator = $this->operator; - $value = $this->value; - $actualValue = strtolower($order->resolveDynamicValue($field)); - - // if value is string convert to lowercase - if (is_string($value)) { - $value = strtolower($value); - } + $value = static::normalize($this->value); + $field = (string) $this->field; + $resolved = $order->resolveDynamicValue($field); + // `resolveDynamicValue()` hands back the field name itself when the order has no such value. + $actualValue = static::normalize($resolved === $field ? null : $resolved); switch ($operator) { case 'exists': - return isset($actualValue); + return $actualValue !== null && $actualValue !== '' && $actualValue !== []; case 'in': - case 'has': - return is_array($actualValue) && in_array($actualValue, $value); + return !is_array($actualValue) && in_array($actualValue, static::toList($value), false); case 'notIn': + return !in_array($actualValue, static::toList($value), false); + + case 'has': + return in_array($value, static::toList($actualValue), false); + case 'doesntHave': - return is_array($actualValue) && !in_array($actualValue, $value); + return !in_array($value, static::toList($actualValue), false); case 'contains': - return is_string($value) && is_string($actualValue) && Str::contains($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::contains($actualValue, $value); case 'beginsWith': - return is_string($value) && is_string($actualValue) && Str::startsWith($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::startsWith($actualValue, $value); case 'endsWith': - return is_string($value) && is_string($actualValue) && Str::endsWith($value, $actualValue); + return is_string($value) && is_string($actualValue) && Str::endsWith($actualValue, $value); case 'equal': return $actualValue == $value; @@ -76,9 +82,41 @@ public function eval(Order $order) case 'lessThanOrEqual': return $actualValue <= $value; - // ... and so on for the other operators default: throw new \Exception("Unknown operator: {$operator}"); } } + + /** + * Lower-case strings, and each string in a list, so comparisons ignore case. + */ + protected static function normalize(mixed $value): mixed + { + if (is_string($value)) { + return strtolower(trim($value)); + } + + if ($value instanceof \Illuminate\Support\Collection) { + $value = $value->all(); + } + + if (is_array($value)) { + return array_map(fn ($item) => is_string($item) ? strtolower(trim($item)) : $item, $value); + } + + return $value; + } + + protected static function toList(mixed $value): array + { + if (is_array($value)) { + return array_values($value); + } + + if (is_string($value) && str_contains($value, ',')) { + return array_map('trim', explode(',', $value)); + } + + return $value === null ? [] : [$value]; + } } diff --git a/server/src/Flow/Flow.php b/server/src/Flow/Flow.php index cec61f0ca..3b0e66855 100644 --- a/server/src/Flow/Flow.php +++ b/server/src/Flow/Flow.php @@ -11,8 +11,13 @@ class Flow extends FlowResource implements \IteratorAggregate */ public function getIterator(): \Traversable { - foreach ($this->attributes['activities'] as $activityAttributes) { - yield new Activity($activityAttributes, $this->serialize()); + // Stored flows are keyed by activity code; older ones list them under `activities`. + $activities = isset($this->attributes['activities']) && is_array($this->attributes['activities']) ? $this->attributes['activities'] : $this->attributes; + + foreach ($activities as $activityAttributes) { + if (is_array($activityAttributes) && isset($activityAttributes['code'])) { + yield new Activity($activityAttributes, $this->serialize()); + } } } diff --git a/server/src/Http/Controllers/Api/v1/CustomerController.php b/server/src/Http/Controllers/Api/v1/CustomerController.php index ae8a5279f..48e506c00 100644 --- a/server/src/Http/Controllers/Api/v1/CustomerController.php +++ b/server/src/Http/Controllers/Api/v1/CustomerController.php @@ -9,8 +9,8 @@ use Fleetbase\FleetOps\Http\Requests\UpdateContactRequest; use Fleetbase\FleetOps\Http\Requests\VerifyCreateCustomerRequest; use Fleetbase\FleetOps\Http\Resources\v1\Customer as CustomerResource; +use Fleetbase\FleetOps\Http\Resources\v1\Order as OrderResource; use Fleetbase\FleetOps\Http\Resources\v1\Place as PlaceResource; -use Fleetbase\FleetOps\Http\Resources\v1\RiderOrder as RiderOrderResource; use Fleetbase\FleetOps\Models\Contact; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\OrderConfig; @@ -18,9 +18,10 @@ use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Models\ServiceQuote; use Fleetbase\FleetOps\Support\CustomerAuth; +use Fleetbase\FleetOps\Support\DriverRatings; +use Fleetbase\FleetOps\Support\OrderChat; +use Fleetbase\FleetOps\Support\OrderCustomFields; use Fleetbase\FleetOps\Support\PlaceSearch; -use Fleetbase\FleetOps\Support\Rides\DriverRatings; -use Fleetbase\FleetOps\Support\Rides\RideChat; use Fleetbase\FleetOps\Support\TrackingCode; use Fleetbase\FleetOps\Support\TrackingPage\TrackingShare; use Fleetbase\FleetOps\Support\TrackingScope; @@ -55,9 +56,9 @@ class CustomerController extends Controller public const DEACTIVATED_LOGIN_MESSAGE = 'This customer login has been deactivated.'; /** - * Relations a rider's order is returned with. + * Relations a customer's order is returned with. */ - protected const RIDER_ORDER_RELATIONS = ['payload', 'payload.pickup', 'payload.dropoff']; + protected const CUSTOMER_ORDER_RELATIONS = ['payload', 'payload.pickup', 'payload.dropoff', 'transaction', 'driverRating']; /** * Wrong guesses a single code tolerates before it locks itself (core's check()). @@ -194,7 +195,7 @@ public function create(CreateCustomerRequest $request) 'email' => $isEmail ? $identity : $request->input('email'), 'phone' => $isEmail ? static::phone($request->input('phone')) : $identity, ]); - // Phone riders sign in with a code, so they may have no password at all. + // Customers who sign in by phone use a code, so they may have no password at all. if ($request->filled('password')) { $user->password = $request->input('password'); } @@ -449,7 +450,7 @@ public function loginWithPhone(Request $request) /** * Send a code to a phone number without revealing whether it has an account. An - * existing rider gets a login code and a new one gets a signup code; both answer the + * existing customer gets a login code and a new one gets a signup code; both answer the * same way. {@see verifyCode} tells them apart once the code is proven. */ public function requestCode(Request $request) @@ -697,8 +698,9 @@ public function updateMe(UpdateContactRequest $request) } /** - * Delete the rider's account: sign them out everywhere, delete their saved places and remove - * their name and contact details. Their past trips stay on the operator's books without them. + * Delete the customer's account: sign them out everywhere, delete their saved places and + * remove their name and contact details. Their past orders stay on the operator's books + * without them. */ public function deleteMe() { @@ -707,8 +709,8 @@ public function deleteMe() return response()->apiError('Not authenticated.', 401); } - if ($this->hasActiveRide($customer)) { - return response()->apiError('Finish or cancel your ride before deleting your account.', 422); + if ($this->hasOrdersInProgress($customer)) { + return response()->apiError('You have orders in progress. Wait for them to finish, or cancel them, before deleting your account.', 422); } $user = $customer->user_uuid ? $this->findUserByUuid($customer->user_uuid) : null; @@ -831,18 +833,34 @@ public function createOrder(CreateCustomerOrderRequest $request) return response()->apiError('No order config available for this company.', 422); } + if (!$this->customersMayOrder($orderConfig)) { + return response()->apiError('Customers cannot place this type of order.', 422); + } + $serviceQuote = $this->resolveServiceQuote($request); if ($serviceQuote instanceof ServiceQuote && ($serviceQuote->company_uuid !== $sessionCompany || $serviceQuote->expired_at?->isPast())) { - return response()->apiError('This fare has expired. Please get a new one.', 422); + return response()->apiError('This quote has expired. Please get a new one.', 422); + } + + // Matching drivers by vehicle type needs a quote, whose service says the type. + $byVehicleType = (bool) $orderConfig->policy('dispatch.matching.vehicle_type'); + if (($byVehicleType || $orderConfig->policy('customer.ordering.require_quote')) && !$serviceQuote instanceof ServiceQuote) { + return response()->apiError('Choose a service quote for this order first.', 422); } - // A config that matches customer orders by vehicle type needs a fare, which says the type. - $byVehicleType = (bool) $orderConfig->match_vehicle_type; - if ($byVehicleType && !$serviceQuote instanceof ServiceQuote) { - return response()->apiError('Choose a ride option first.', 422); + $paymentMethod = $request->input('payment_method'); + $paymentMethods = array_values((array) $orderConfig->policy('customer.ordering.payment_methods', [])); + if ($paymentMethod !== null && $paymentMethods !== [] && !in_array($paymentMethod, $paymentMethods, true)) { + return response()->apiError('Choose a payment method: ' . implode(', ', $paymentMethods) . '.', 422); } - if ($orderConfig->key === 'ride' && $this->hasUnpaidRide($customer)) { - return response()->apiError('Pay for your last trip before you book another.', 402); + + if ($this->hasUnsettledOrder($customer, $orderConfig)) { + return response()->apiError('Settle your previous order before placing another.', 402); + } + + $customFieldErrors = OrderCustomFields::validate($orderConfig, (array) $request->input('custom_fields', [])); + if ($customFieldErrors) { + return response()->apiError($customFieldErrors, 422); } $vehicleType = $byVehicleType ? $serviceQuote->serviceRate?->service_type : null; @@ -871,8 +889,7 @@ public function createOrder(CreateCustomerOrderRequest $request) } // How the customer will pay, kept on the payload this order was given. - $paymentMethod = $request->input('payment_method'); - if ($builtHere && in_array($paymentMethod, ['cash', 'card'], true)) { + if ($builtHere && is_string($paymentMethod) && in_array($paymentMethod, $paymentMethods, true)) { $this->setPayloadPaymentMethod($payloadUuid, $paymentMethod); } @@ -883,11 +900,11 @@ public function createOrder(CreateCustomerOrderRequest $request) 'payload_uuid' => $payloadUuid, 'order_config_uuid' => $orderConfig->uuid, 'type' => $orderConfig->key, - 'status' => 'created', + 'status' => $orderConfig->getInitialStatusCode(), 'scheduled_at' => $request->input('scheduled_at'), 'notes' => $request->input('notes'), 'internal_id' => $request->input('internal_id'), - 'adhoc' => (bool) $orderConfig->customer_orders_adhoc, + 'adhoc' => (bool) $orderConfig->policy('dispatch.adhoc.customer_orders'), 'required_vehicle_type' => $vehicleType, 'meta' => (array) $request->input('meta', []), ]); @@ -899,7 +916,9 @@ public function createOrder(CreateCustomerOrderRequest $request) $order->purchaseServiceQuote($serviceQuote); } - return $this->orderResource($order->fresh(['payload', 'payload.pickup', 'payload.dropoff', 'payload.entities'])); + OrderCustomFields::apply($order, (array) $request->input('custom_fields', [])); + + return $this->orderResource($order->fresh([...static::CUSTOMER_ORDER_RELATIONS, 'payload.entities'])); } /** @@ -964,8 +983,8 @@ public function places(Request $request) } /** - * Search this rider's saved places and the geocoder. Other riders' places are never - * returned, and neither are unowned rows, which hold addresses from other riders' trips. + * Search this customer's saved places and the geocoder. Other customers' places are never + * returned, and neither are unowned rows, which hold addresses from other customers' orders. */ public function searchPlaces(Request $request) { @@ -974,7 +993,7 @@ public function searchPlaces(Request $request) return response()->apiError('Not authenticated.', 401); } - return $this->placeResourceCollection($this->runPlaceSearch($this->riderPlaceQuery($customer), (string) $request->input('query', ''), [ + return $this->placeResourceCollection($this->runPlaceSearch($this->customerPlaceQuery($customer), (string) $request->input('query', ''), [ 'limit' => min((int) $request->input('limit', 10), 50), 'geo' => true, 'latitude' => $request->input('latitude', false), @@ -1004,7 +1023,7 @@ public function geocode(Request $request) } /** - * Save a place for the authenticated rider. + * Save a place for the authenticated customer. */ public function savePlace(Request $request) { @@ -1029,7 +1048,7 @@ public function savePlace(Request $request) } /** - * Update one of the authenticated rider's saved places. + * Update one of the authenticated customer's saved places. */ public function updatePlace(string $id, Request $request) { @@ -1053,7 +1072,7 @@ public function updatePlace(string $id, Request $request) } /** - * Delete one of the authenticated rider's saved places. + * Delete one of the authenticated customer's saved places. */ public function deletePlace(string $id) { @@ -1068,7 +1087,7 @@ public function deletePlace(string $id) } /** - * Send a code to the number a rider wants to change to, so {@see updateMe} can prove + * Send a code to the number a customer wants to change to, so {@see updateMe} can prove * they hold it. */ public function requestPhoneChangeCode(Request $request) @@ -1111,7 +1130,7 @@ public function requestPhoneChangeCode(Request $request) } /** - * Request a driver for one of the authenticated rider's orders. + * Request a driver for one of the authenticated customer's orders. */ public function dispatchOrder(string $id) { @@ -1123,7 +1142,7 @@ public function dispatchOrder(string $id) if ($order->dispatched) { return response()->apiError('Order has already been dispatched.', 422); } - if ($order->status !== 'created') { + if ($this->orderHasEnded($order) || $order->status !== $order->config()->getInitialStatusCode() || !$order->config()->allowsDispatch()) { return response()->apiError('This order can no longer be dispatched.', 422); } if (!$order->hasDriverAssigned && !$order->adhoc) { @@ -1133,11 +1152,11 @@ public function dispatchOrder(string $id) $order->dispatch(); $order->insertDispatchActivity(); - return $this->orderResource($order->fresh(static::RIDER_ORDER_RELATIONS)); + return $this->orderResource($order->fresh(static::CUSTOMER_ORDER_RELATIONS)); } /** - * Cancel one of the authenticated rider's orders. + * Cancel one of the authenticated customer's orders, when its config lets customers cancel. */ public function cancelOrder(string $id, Request $request) { @@ -1146,7 +1165,7 @@ public function cancelOrder(string $id, Request $request) return response()->apiError('Order not found.', 404); } - if (in_array($order->status, ['completed', 'canceled'], true) || $order->config()->isTerminalActivityCode($order->status)) { + if (!$this->customerMayCancel($order)) { return response()->apiError('This order can no longer be canceled.', 422); } @@ -1157,12 +1176,12 @@ public function cancelOrder(string $id, Request $request) $order->cancel(); } - return $this->orderResource($order->fresh(static::RIDER_ORDER_RELATIONS)); + return $this->orderResource($order->fresh(static::CUSTOMER_ORDER_RELATIONS)); } /** - * The driver and car a rider needs to find their ride. The driver's contact details stay - * out, because riders and drivers don't share phone numbers. + * The driver and vehicle of one of the customer's orders, so the customer can recognise them. + * The driver's contact details stay out: customers and drivers don't share phone numbers. */ public function orderDriver(string $id) { @@ -1189,7 +1208,7 @@ public function orderDriver(string $id) } /** - * Live tracking data for one of the authenticated rider's orders. + * Live tracking data for one of the authenticated customer's orders. */ public function orderTracker(string $id, Request $request) { @@ -1206,7 +1225,7 @@ public function orderTracker(string $id, Request $request) } /** - * ETA for one of the authenticated rider's orders. + * ETA for one of the authenticated customer's orders. */ public function orderEta(string $id, Request $request) { @@ -1223,8 +1242,8 @@ public function orderEta(string $id, Request $request) } /** - * The chat with the driver of one of the rider's rides, oldest message first. Empty until a - * driver accepts. + * The chat with the driver of one of the customer's orders, oldest message first. Empty until + * a driver is assigned. Needs the config's `customer.interactions.chat` policy. */ public function orderMessages(string $id) { @@ -1232,14 +1251,17 @@ public function orderMessages(string $id) if (!$order) { return response()->apiError('Order not found.', 404); } + if (!$order->config()->policy('customer.interactions.chat')) { + return response()->apiError('Messaging the driver is not available for this order.', 403); + } - $channel = $this->rideChannel($order); + $channel = $this->orderChannel($order); - return response()->json($channel ? RideChat::messages($channel, $this->currentCustomer()->user_uuid)->all() : []); + return response()->json($channel ? OrderChat::messages($channel, $this->currentCustomer()->user_uuid)->all() : []); } /** - * Send the driver a message. The rider always writes as themselves. + * Send the driver a message. The customer always writes as themselves. */ public function sendOrderMessage(string $id, Request $request) { @@ -1248,27 +1270,31 @@ public function sendOrderMessage(string $id, Request $request) return response()->apiError('Order not found.', 404); } + if (!$order->config()->policy('customer.interactions.chat')) { + return response()->apiError('Messaging the driver is not available for this order.', 403); + } + $text = trim((string) $request->input('text')); if ($text === '' || mb_strlen($text) > 2000) { return response()->apiError('Write a message of up to 2000 characters.', 422); } - if ($this->rideHasEnded($order)) { - return response()->apiError('This ride has ended.', 422); - } - $channel = $this->rideChannel($order); + $channel = $this->orderChannel($order); + if ($this->chatIsClosed($order, $channel)) { + return response()->apiError('This conversation has ended.', 422); + } if (!$channel) { - return response()->apiError('You can message your driver once they accept.', 422); + return response()->apiError('You can message the driver once one is assigned.', 422); } - $riderUser = $this->currentCustomer()->user_uuid; - $message = RideChat::send($channel, $riderUser, $text); + $customerUser = $this->currentCustomer()->user_uuid; + $message = OrderChat::send($channel, $customerUser, $text); - return response()->json(RideChat::messages($channel, $riderUser)->firstWhere('id', $message->public_id ?? $message->uuid), 201); + return response()->json(OrderChat::messages($channel, $customerUser)->firstWhere('id', $message->public_id ?? $message->uuid), 201); } /** - * Rate the driver of a finished ride, once. + * Rate the driver of a completed order, once. Needs the config's `customer.interactions.rating` policy. */ public function rateOrder(string $id, Request $request) { @@ -1277,24 +1303,29 @@ public function rateOrder(string $id, Request $request) return response()->apiError('Order not found.', 404); } + if (!$order->config()->policy('customer.interactions.rating')) { + return response()->apiError('Rating the driver is not available for this order.', 403); + } + $stars = $request->input('stars'); if (!is_numeric($stars) || (int) $stars != $stars || $stars < 1 || $stars > 5) { return response()->apiError('Rate from 1 to 5 stars.', 422); } - if ($order->status !== 'completed' || !$order->driver_assigned_uuid) { - return response()->apiError('Only a finished ride can be rated.', 422); + if ($order->status !== $order->config()->getCompletedActivity()?->code || !$order->driver_assigned_uuid) { + return response()->apiError('Only a completed order can be rated.', 422); } $comment = $request->input('comment'); if (!DriverRatings::rate($order, (int) $stars, is_string($comment) ? Str::limit($comment, 1000, '') : null)) { - return response()->apiError('You already rated this ride.', 409); + return response()->apiError('You already rated this order.', 409); } return response()->json(['status' => 'rated']); } /** - * A link the rider can send to someone they trust to follow the ride live, without a code. + * A link the customer can send to someone they trust to follow the order live, without a + * code. Needs the config's `customer.interactions.share_tracking` policy. */ public function shareOrder(string $id) { @@ -1303,9 +1334,13 @@ public function shareOrder(string $id) return response()->apiError('Order not found.', 404); } + if (!$order->config()->policy('customer.interactions.share_tracking')) { + return response()->apiError('Sharing tracking is not available for this order.', 403); + } + $number = data_get($order, 'trackingNumber.tracking_number'); - if (!$number || $this->rideHasEnded($order)) { - return response()->apiError('This ride can no longer be shared.', 422); + if (!$number || $this->orderHasEnded($order)) { + return response()->apiError('This order can no longer be shared.', 422); } $scope = TrackingScope::forCustomer($order, $this->currentCustomer()); @@ -1318,20 +1353,6 @@ public function shareOrder(string $id) ]); } - /** - * What the rider app shows from the operator's ride settings: the emergency number and support contacts. - */ - public function rideSettings() - { - $config = OrderConfig::where('company_uuid', $this->sessionCompany())->where('key', 'ride')->first(); - $rider = (array) data_get($config?->meta, 'rider', []); - - return response()->json([ - 'emergency_number' => $rider['emergency_number'] ?? null, - 'support' => ['phone' => $rider['support_phone'] ?? null, 'email' => $rider['support_email'] ?? null], - ]); - } - /** * Register a push-notification device for the authenticated customer's user. */ @@ -1366,7 +1387,7 @@ public function registerDevice(Request $request) * ============================================================ */ /** - * Why a rider can't change to this phone number, or null if they can. A number is only + * Why a customer can't change to this phone number, or null if they can. A number is only * accepted with a code sent to it, and never if another account holds it. */ protected function refusePhoneChange(Contact $customer, string $phone, mixed $code): ?JsonResponse @@ -1396,60 +1417,110 @@ protected function trackingPageUrl(string $number, ?string $companyUuid): string return TrackingCode::pageUrl($number, $companyUuid); } - protected function rideChannel(Order $order): mixed + protected function orderChannel(Order $order): mixed { - return RideChat::channel($order); + return OrderChat::open($order); } - protected function rideHasEnded(Order $order): bool + protected function chatIsClosed(Order $order, mixed $channel): bool + { + return OrderChat::isClosed($order, $channel ?: null); + } + + protected function orderHasEnded(Order $order): bool { return in_array($order->status, ['completed', 'canceled'], true) || (bool) $order->config()?->isTerminalActivityCode($order->status); } /** - * Whether one of the rider's recent card trips has a final fare and isn't paid (`paid_at`, - * set by the billing package). Cash is collected by the driver, so it never blocks a booking. + * Whether customers may place orders of the config: every config, unless the company chose + * which configs customers may use (`fleet-ops.customer-enabled-order-configs`). + */ + protected function customersMayOrder(OrderConfig $orderConfig): bool + { + $enabled = array_filter((array) $this->lookupCompanySetting('fleet-ops.customer-enabled-order-configs', [])); + + return $enabled === [] || in_array($orderConfig->uuid, $enabled, true) || in_array($orderConfig->public_id, $enabled, true); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed + { + return \Fleetbase\Models\Setting::lookupFromCompany($key, $default); + } + + /** + * Whether the customer may still cancel the order: their config lets customers cancel, the + * order hasn't finished, and it hasn't reached the config's `allowed_until` activity. + */ + protected function customerMayCancel(Order $order): bool + { + if ($this->orderHasEnded($order)) { + return false; + } + + $config = $order->config(); + if (!$config->policy('customer.cancellation.enabled', true)) { + return false; + } + + $until = $config->policy('customer.cancellation.allowed_until'); + $limit = is_string($until) && $until !== '' ? $config->getActivityByCode($until) : null; + + return !$limit || ($order->status !== $limit->code && !$order->hasCompletedActivity($limit)); + } + + /** + * Whether an earlier order of the config, paid by one of the methods its + * `customer.ordering.require_settlement` policy names, is completed but its transaction + * isn't paid. Methods the policy leaves out (cash collected by the driver, say) never block. */ - protected function hasUnpaidRide(Contact $customer): bool + protected function hasUnsettledOrder(Contact $customer, OrderConfig $orderConfig): bool { + $methods = array_values(array_filter((array) $orderConfig->policy('customer.ordering.require_settlement', []), 'is_string')); + if ($methods === []) { + return false; + } + return Order::withoutGlobalScopes() ->where('customer_uuid', $customer->uuid) - ->where('type', 'ride') - ->where('status', 'completed') - ->whereNotNull('fare_finalized_at') - ->whereNull('paid_at') + ->where('order_config_uuid', $orderConfig->uuid) + ->where('status', $orderConfig->getCompletedActivity()?->code ?? 'completed') ->whereNull('deleted_at') - ->whereHas('payload', fn ($payload) => $payload->where('payment_method', 'card')) + ->whereHas('payload', fn ($payload) => $payload->whereIn('payment_method', $methods)) + ->whereHas('transaction', fn ($transaction) => $transaction->where('amount', '>', 0)->whereNotIn('settlement_status', ['paid', 'refunded', 'partially_refunded'])) ->exists(); } /** - * Whether the rider has a ride that was sent to drivers and hasn't ended. + * Whether the customer has an order that was sent to drivers and hasn't finished, by the + * order's own config. */ - protected function hasActiveRide(Contact $customer): bool + protected function hasOrdersInProgress(Contact $customer): bool { return Order::withoutGlobalScopes() + ->with('orderConfig') ->where('customer_uuid', $customer->uuid) ->where('dispatched', 1) ->whereNull('deleted_at') - ->whereNotIn('status', ['completed', 'canceled', 'no_show']) - ->exists(); + ->whereNotIn('status', ['completed', 'canceled']) + ->get() + ->contains(fn (Order $order) => !$this->orderHasEnded($order)); } /** - * Remove what identifies the rider, then delete their records. A user who is only this - * company's rider goes too; one with other roles or companies keeps their account. + * Remove what identifies the customer, then delete their records. A user who is only this + * company's customer goes too; one with other roles or companies keeps their account. */ protected function eraseCustomer(Contact $customer, ?User $user): void { Place::where('owner_uuid', $customer->uuid)->delete(); - $customer->forceFill(['name' => 'Deleted rider', 'email' => null, 'phone' => null, 'photo_uuid' => null, 'meta' => []])->saveQuietly(); + $customer->forceFill(['name' => 'Deleted customer', 'email' => null, 'phone' => null, 'photo_uuid' => null, 'meta' => []])->saveQuietly(); $customer->delete(); $otherContacts = $user ? Contact::withoutGlobalScopes()->where('user_uuid', $user->uuid)->where('uuid', '!=', $customer->uuid)->exists() : true; if ($user && $user->type === 'customer' && !$otherContacts) { - $user->forceFill(['name' => 'Deleted rider', 'email' => 'deleted-' . $user->uuid . '@deleted.invalid', 'phone' => null])->saveQuietly(); + $user->forceFill(['name' => 'Deleted customer', 'email' => 'deleted-' . $user->uuid . '@deleted.invalid', 'phone' => null])->saveQuietly(); $user->delete(); } } @@ -1808,12 +1879,19 @@ protected function customerResource(Contact $contact): mixed protected function orderResource(Order $order): mixed { - return new RiderOrderResource($order); + $order->loadMissing(static::CUSTOMER_ORDER_RELATIONS); + + return new OrderResource($order); } protected function orderResourceCollection(mixed $results): mixed { - return RiderOrderResource::collection($results); + if ($results instanceof \Illuminate\Support\Collection || $results instanceof \Illuminate\Contracts\Pagination\Paginator) { + collect($results instanceof \Illuminate\Contracts\Pagination\Paginator ? $results->items() : $results) + ->each(fn ($order) => $order instanceof Order ? $order->loadMissing(static::CUSTOMER_ORDER_RELATIONS) : null); + } + + return OrderResource::collection($results); } protected function placeResourceCollection(mixed $results): mixed @@ -1826,7 +1904,7 @@ protected function placeResource(Place $place): mixed return new PlaceResource($place); } - protected function riderPlaceQuery(Contact $customer): mixed + protected function customerPlaceQuery(Contact $customer): mixed { return Place::where('company_uuid', $this->sessionCompany()) ->where('owner_uuid', $customer->uuid) diff --git a/server/src/Http/Controllers/Api/v1/DriverController.php b/server/src/Http/Controllers/Api/v1/DriverController.php index ae623eb3b..a73deb09b 100644 --- a/server/src/Http/Controllers/Api/v1/DriverController.php +++ b/server/src/Http/Controllers/Api/v1/DriverController.php @@ -26,9 +26,9 @@ use Fleetbase\FleetOps\Support\Geocoding; use Fleetbase\FleetOps\Support\GeofenceIntersectionService; use Fleetbase\FleetOps\Support\NavigatorReview; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; use Fleetbase\FleetOps\Support\OSRM; use Fleetbase\FleetOps\Support\ProfileAccountManager; -use Fleetbase\FleetOps\Support\Rides\RideUpdates; use Fleetbase\FleetOps\Support\TrackingPublisher; use Fleetbase\FleetOps\Support\Utils; use Fleetbase\Http\Controllers\Controller; @@ -395,8 +395,8 @@ public function track(string $id, Request $request) broadcast(new DriverLocationChanged($driver)); app(TrackingPublisher::class)->driverMoved($driver); - // A rider is told once when their car is about to arrive. - RideUpdates::driverMoved($driver, $order instanceof Order ? $order : null); + // The order's config can act when its driver comes close to the pickup or drop-off. + OrderConfigTriggers::driverMoved($driver, $order instanceof Order ? $order : null); // ---------------------------------------------------------------- // Geofence intersection detection diff --git a/server/src/Http/Controllers/Api/v1/OrderConfigController.php b/server/src/Http/Controllers/Api/v1/OrderConfigController.php index 02ec96a40..4d340fdb3 100644 --- a/server/src/Http/Controllers/Api/v1/OrderConfigController.php +++ b/server/src/Http/Controllers/Api/v1/OrderConfigController.php @@ -69,11 +69,17 @@ protected function findOrderConfigOrFail(string $id): OrderConfig protected function orderConfigCollection($results) { + collect($results instanceof \Illuminate\Contracts\Pagination\Paginator ? $results->items() : $results) + ->each(fn ($orderConfig) => $orderConfig instanceof OrderConfig ? $orderConfig->loadMissing('customFields') : null); + return OrderConfigResource::collection($results); } protected function orderConfigResource(OrderConfig $orderConfig) { + // Customer apps read the config's custom fields to ask for them when ordering. + $orderConfig->loadMissing('customFields'); + return new OrderConfigResource($orderConfig); } diff --git a/server/src/Http/Controllers/Api/v1/OrderController.php b/server/src/Http/Controllers/Api/v1/OrderController.php index 5612e033b..4afdd5022 100644 --- a/server/src/Http/Controllers/Api/v1/OrderController.php +++ b/server/src/Http/Controllers/Api/v1/OrderController.php @@ -27,6 +27,7 @@ use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing; +use Fleetbase\FleetOps\Support\OrderCustomFields; use Fleetbase\FleetOps\Support\OrderEdit; use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\ResolvesOrderServiceStops; @@ -355,9 +356,14 @@ protected function createOrderFromRequest(CreateOrderRequest $request) } } - // if no status is set its default to `created` + // if no status is set it starts at the config's initial activity, `created` by default if (!isset($input['status'])) { - $input['status'] = 'created'; + $input['status'] = $orderConfig->getInitialStatusCode(); + } + + $customFieldErrors = OrderCustomFields::validate($orderConfig, (array) $request->input('custom_fields', [])); + if ($customFieldErrors) { + return response()->apiError($customFieldErrors, 422); } // if adhoc set convert to sql ready boolean value 1 or 0 @@ -377,6 +383,7 @@ protected function createOrderFromRequest(CreateOrderRequest $request) // create the order $order = $this->createOrder($input); + OrderCustomFields::apply($order, (array) $request->input('custom_fields', [])); // if it's integrated vendor order apply to meta if ($integratedVendorOrder) { @@ -389,8 +396,8 @@ protected function createOrderFromRequest(CreateOrderRequest $request) // load required relations $order->load(['trackingNumber', 'trackingStatuses', 'driverAssigned', 'vehicleAssigned', 'purchaseRate.serviceQuote.items', 'customer', 'facilitator']); - // Determine if order should be dispatched on creation - $shouldDispatch = $request->boolean('dispatch') && $integratedVendorOrder === null; + // Determine if order should be dispatched on creation, unless its config turns dispatch off + $shouldDispatch = $request->boolean('dispatch') && $integratedVendorOrder === null && $orderConfig->allowsDispatch(); $this->dispatchFinalizeApiOrderCreation( $order->uuid, @@ -1070,6 +1077,10 @@ public function dispatchOrder(string $id) return $this->apiError('Order has already been dispatched!'); } + if ($order->currentConfig()?->allowsDispatch() === false) { + return $this->apiError('Orders of this type are not dispatched.'); + } + $order->dispatch(); $order->insertDispatchActivity(); @@ -1408,16 +1419,15 @@ public function updateActivity($id, Request $request) $activity = new Activity($activity, $order->getConfigFlow()); } - // Configs with strict transitions only accept a configured child of the current - // activity, and the server's activity definition replaces the one sent. - if ($orderConfig && $orderConfig->hasStrictTransitions() && !($activity->is('dispatched') && $skipDispatch)) { - $targetCode = $activity->get('code'); - $configured = $targetCode ? $orderConfig->getActivityByCode($targetCode) : null; - if (!$configured || !$orderConfig->canTransition($order->status, $targetCode)) { - return response()->apiError('This activity is not a permitted next step for the order.', 422); + // The order's config decides whether the update is allowed: a finished order, a step the + // config's strict transitions don't permit, dispatch on a config that turns it off, or a + // step that needs proof of delivery without it. With strict transitions the server's + // activity definition replaces the one sent. + if ($orderConfig && !($activity->is('dispatched') && $skipDispatch)) { + [$activity, $refusal] = $orderConfig->authorizeTransition($order, $activity, $proof); + if ($refusal) { + return response()->apiError($refusal, 422); } - - $activity = $configured; } // if we're going to skip the dispatch get the next activity status and flow and continue diff --git a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php index 8de2b6396..5c8805f1d 100644 --- a/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php +++ b/server/src/Http/Controllers/Api/v1/ServiceQuoteController.php @@ -347,7 +347,7 @@ protected function generateServiceQuoteRequestId(): string protected function createPlaceFromMixed(mixed $value): Place { - // A preview must not leave a place behind for every fare a rider checks. + // A preview must not leave a place behind for every price a customer checks. return Place::createFromMixed($value, [], !$this->previewOnly); } @@ -454,7 +454,7 @@ protected function serviceQuoteResourceCollection(iterable $serviceQuotes) } /** - * Where a rider asked to be picked up, when they asked how soon a car could come (`availability`). + * Where the request asked how soon a vehicle could come (`availability`). */ protected ?SpatialPoint $availabilityFrom = null; @@ -467,20 +467,22 @@ protected function availabilityPoint(Request $request, mixed $pickup): ?SpatialP } /** - * Average speed in metres per second used to turn the nearest car's distance into a pickup ETA. + * Average speed in metres per second used to turn the nearest vehicle's distance into a pickup + * ETA, unless `fleetops.availability.pickup_speed` sets another. */ public const PICKUP_SPEED = 7.0; /** - * Add the class's seats and how soon its nearest free car could reach the pickup, in seconds. - * Both are null when the company has no such car; the ETA is a straight-line estimate. + * Add the most seats a vehicle of the quote's service type has, and how soon its nearest free + * driver could reach the pickup, in seconds. Both are null when the company has no such + * vehicle; the ETA is a straight-line estimate. */ protected function addAvailability(ServiceQuote $quote, SpatialPoint $pickup): void { $class = data_get($quote, 'serviceRate.service_type'); $company = $quote->company_uuid; - $seats = $class ? Vehicle::where('company_uuid', $company)->whereRaw('LOWER(type) = ?', [strtolower($class)])->max('seating_capacity') : null; + $seatingCapacity = $class ? Vehicle::where('company_uuid', $company)->whereRaw('LOWER(type) = ?', [strtolower($class)])->max('seating_capacity') : null; $drivers = Driver::query() ->withoutGlobalScopes() @@ -491,13 +493,15 @@ protected function addAvailability(ServiceQuote $quote, SpatialPoint $pickup): v ->distanceSphereValue('location', $pickup) ->orderBy('distance'); DriverMatching::inCompany($drivers, $company); - DriverMatching::notBusy($drivers); + DriverMatching::notBusy($drivers, $company); DriverMatching::forVehicleClass($drivers, $class); $nearest = $drivers->first(); + $speed = (float) config('fleetops.availability.pickup_speed', self::PICKUP_SPEED) ?: self::PICKUP_SPEED; + $quote->availability = [ - 'seats' => $seats ? (int) $seats : null, - 'pickup_eta' => $nearest ? (int) round(60 + (float) $nearest->distance / self::PICKUP_SPEED) : null, + 'seating_capacity' => $seatingCapacity ? (int) $seatingCapacity : null, + 'pickup_eta' => $nearest ? (int) round(60 + (float) $nearest->distance / $speed) : null, ]; } diff --git a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php index fc99602be..fa2a5c63f 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php @@ -6,8 +6,15 @@ use Fleetbase\FleetOps\Http\Controllers\FleetOpsController; use Fleetbase\FleetOps\Http\Requests\Internal\CreateOrderConfigRequest; use Fleetbase\FleetOps\Models\OrderConfig; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigActions; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\Models\Company; +use Fleetbase\Support\Auth; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; +use Illuminate\Support\Str; class OrderConfigController extends FleetOpsController { @@ -72,6 +79,49 @@ public function deleteRecord($id, Request $request) return $this->deletedResource($orderConfig); } + /** + * The templates, policies, actions and trigger events order configs can use, for the console. + */ + public function capabilities() + { + return response()->json([ + 'templates' => OrderConfigTemplates::describe(), + 'policies' => OrderConfigPolicies::describe(), + 'actions' => OrderConfigActions::describe(), + 'events' => OrderConfigTriggers::EVENTS, + ]); + } + + /** + * Create a config from a template, under a name of the company's choosing. + */ + public function createFromTemplate(Request $request) + { + $template = (string) $request->input('template'); + $name = trim((string) $request->input('name')); + if (!OrderConfigTemplates::has($template)) { + return $this->errorResponse('Choose an order config template.'); + } + if ($name === '') { + return $this->errorResponse('Give the order config a name.'); + } + + $company = $this->currentCompany(); + if (!$company) { + return $this->errorResponse('No organization in session.'); + } + if (OrderConfig::where('company_uuid', $company->uuid)->where(fn ($query) => $query->where('name', $name)->orWhere('key', Str::slug($name)))->exists()) { + return $this->errorResponse('An order config with this name already exists.'); + } + + return $this->createdOrderConfigResource(OrderConfigTemplates::create($template, $company, $name)); + } + + protected function currentCompany(): ?Company + { + return Auth::getCompany(); + } + protected function findOrderConfig(string $id): ?OrderConfig { return OrderConfig::where('uuid', $id)->first(); diff --git a/server/src/Http/Controllers/Internal/v1/OrderController.php b/server/src/Http/Controllers/Internal/v1/OrderController.php index 46061e37e..866887b4c 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderController.php @@ -960,23 +960,14 @@ public function updateActivity(string $id, Request $request) $activity = $request->inputArray('activity'); $activity = new Activity($activity, $order->getConfigFlow()); - // Configs with strict transitions only accept a configured child of the current - // activity, and the server-side activity definition replaces the client payload. + // The order's config decides whether the update is allowed. Operators may still correct a + // finished order, so a terminal status alone doesn't refuse it here. $orderConfig = $order->config(); - if ($orderConfig && $orderConfig->hasStrictTransitions()) { - $targetCode = $activity->get('code'); - $configured = $targetCode ? $orderConfig->getActivityByCode($targetCode) : null; - if (!$configured || !$orderConfig->canTransition($order->status, $targetCode)) { - return response()->error('This activity is not a permitted next step for the order.', 422); + if ($orderConfig) { + [$activity, $refusal] = $orderConfig->authorizeTransition($order, $activity, $proof, $bypassProof, true); + if ($refusal) { + return response()->error($refusal, 422); } - - $activity = $configured; - } - - $requiresProof = Utils::isActivity($activity) - && ($activity->get('require_pod') || ($activity->completesOrder() && $order->pod_required)); - if ($requiresProof && !$proof && !$bypassProof) { - return response()->error('Proof of delivery is required for this activity or must be explicitly bypassed.', 422); } // Handle pickup/dropoff order activity update as normal diff --git a/server/src/Http/Controllers/Public/TrackingController.php b/server/src/Http/Controllers/Public/TrackingController.php index 1b5325515..255e1d6c8 100644 --- a/server/src/Http/Controllers/Public/TrackingController.php +++ b/server/src/Http/Controllers/Public/TrackingController.php @@ -154,8 +154,8 @@ public function verifyCode(Request $request, string $number): JsonResponse } /** - * Open a link a rider shared: a valid token gives this device the rider's live view, as a - * verified code would. + * Open a link a customer shared: a valid token gives this device the customer's live view, + * as a verified code would. */ public function redeemShare(Request $request, string $number): JsonResponse { diff --git a/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php b/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php index a667cb957..7ad96302e 100644 --- a/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php +++ b/server/src/Http/Requests/Internal/CreateOrderConfigRequest.php @@ -2,7 +2,9 @@ namespace Fleetbase\FleetOps\Http\Requests\Internal; -use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigActions; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; use Fleetbase\Http\Requests\FleetbaseRequest; use Fleetbase\Support\Auth; use Illuminate\Validation\Rule; @@ -22,7 +24,7 @@ public function authorize(): bool */ public function rules(): array { - return [ + return array_merge([ 'name' => [ 'required', Rule::unique('order_configs', 'name') @@ -33,10 +35,12 @@ public function rules(): array Rule::unique('order_configs', 'key') ->where('company_uuid', request()->session()->get('company'))->whereNull('deleted_at'), ], - 'adhoc_strategy' => ['nullable', 'string', Rule::in(AdhocDispatch::names())], - 'adhoc_offer_timeout' => ['nullable', 'integer', 'min:' . AdhocDispatch::MIN_OFFER_TIMEOUT, 'max:' . AdhocDispatch::MAX_OFFER_TIMEOUT], - 'customer_orders_adhoc' => ['nullable', 'boolean'], - 'match_vehicle_type' => ['nullable', 'boolean'], - ]; + 'triggers' => ['nullable', 'array'], + 'triggers.*.event' => ['required', 'string', Rule::in(OrderConfigTriggers::EVENTS)], + 'triggers.*.action' => ['required', 'string', Rule::in(OrderConfigActions::names())], + 'triggers.*.params' => ['nullable', 'array'], + 'triggers.*.options' => ['nullable', 'array'], + 'triggers.*.when' => ['nullable', 'array'], + ], OrderConfigPolicies::rules()); } } diff --git a/server/src/Http/Resources/v1/Order.php b/server/src/Http/Resources/v1/Order.php index fa77bbc5f..17dc5acda 100644 --- a/server/src/Http/Resources/v1/Order.php +++ b/server/src/Http/Resources/v1/Order.php @@ -93,6 +93,11 @@ public function toArray($request): array 'required_vehicle_type' => $this->required_vehicle_type, // The asking driver's open offer, when they listed orders near them. 'adhoc_offer' => $this->when($this->resource->relationLoaded('adhocOffer'), fn () => AdhocOfferListing::present($this->adhocOffer)), + // How offering an adhoc order ended, e.g. `no_driver_found`; null while it is open or taken. + 'dispatch_outcome' => $this->when((bool) data_get($this, 'adhoc', false), fn () => $this->resource->dispatchOutcome()), + 'driver_rating' => $this->when($this->resource->relationLoaded('driverRating'), fn () => $this->driverRating ? ['stars' => $this->driverRating->stars, 'comment' => $this->driverRating->comment] : null), + // Whether the order's transaction is paid (core's settlement status), when it was loaded. + 'payment_status' => $this->when($this->resource->relationLoaded('transaction'), fn () => $this->transaction?->settlement_status), 'distance' => (int) $this->distance, 'time' => (int) $this->time, 'transaction_amount' => $this->transaction_amount, diff --git a/server/src/Http/Resources/v1/OrderConfig.php b/server/src/Http/Resources/v1/OrderConfig.php index 99c8d54c4..5796b6efb 100644 --- a/server/src/Http/Resources/v1/OrderConfig.php +++ b/server/src/Http/Resources/v1/OrderConfig.php @@ -35,15 +35,33 @@ public function toArray($request): array 'status' => $this->status, 'version' => $this->version, 'flow' => $this->projectFlow(), - 'adhoc_strategy' => $this->adhoc_strategy, - 'adhoc_offer_timeout' => $this->adhoc_offer_timeout, - 'customer_orders_adhoc' => (bool) $this->customer_orders_adhoc, - 'match_vehicle_type' => (bool) $this->match_vehicle_type, + // Every policy setting, defaults filled in: what a customer app needs to know about + // ordering, cancelling, payment methods and the like for this order type. + 'policies' => $this->resource->resolvedPolicies(), + 'triggers' => $this->when(Http::isInternalRequest(), $this->triggers ?? []), + 'custom_fields' => $this->when($this->resource->relationLoaded('customFields'), fn () => $this->projectCustomFields()), 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } + /** + * The custom fields orders of the config carry, with what a form needs to ask for them. + */ + protected function projectCustomFields(): array + { + return $this->resource->customFields->map(fn ($field) => [ + 'name' => $field->name, + 'label' => $field->label, + 'type' => $field->type, + 'component' => $field->component, + 'options' => $field->options, + 'required' => (bool) $field->required, + 'default_value' => $field->default_value, + 'help_text' => $field->help_text, + ])->values()->all(); + } + /** * Project the flow JSON into a list of activities, keeping the public-safe * per-activity fields. diff --git a/server/src/Http/Resources/v1/PurchaseRate.php b/server/src/Http/Resources/v1/PurchaseRate.php index 86ca1106e..36d5d408f 100644 --- a/server/src/Http/Resources/v1/PurchaseRate.php +++ b/server/src/Http/Resources/v1/PurchaseRate.php @@ -24,9 +24,12 @@ public function toArray($request) 'order' => $this->order_id, 'customer' => $this->customer_id, 'transaction' => $this->transaction_id, + 'service_name' => data_get($this, 'serviceQuote.serviceRate.service_name'), 'amount' => $this->amount, 'currency' => $this->currency, 'status' => $this->status, + // Priced again from the order's actual distance and time (the config's pricing policy). + 'repriced' => (bool) data_get($this->meta, 'repriced'), // 'type' => $this->when(Http::isInternalRequest(), 'service-rate'), 'updated_at' => $this->updated_at, 'created_at' => $this->created_at, diff --git a/server/src/Http/Resources/v1/RiderOrder.php b/server/src/Http/Resources/v1/RiderOrder.php deleted file mode 100644 index eb55881e2..000000000 --- a/server/src/Http/Resources/v1/RiderOrder.php +++ /dev/null @@ -1,23 +0,0 @@ -resource->driverRating; - - return array_merge(parent::toArray($request), [ - 'fare' => $this->resource->fare(), - 'rating' => $rating ? ['stars' => $rating->stars, 'comment' => $rating->comment] : null, - 'payment_method' => data_get($this->resource, 'payload.payment_method'), - 'paid_at' => $this->paid_at, - 'dispatch_outcome' => $this->resource->dispatchOutcome(), - ]); - } -} diff --git a/server/src/Http/Resources/v1/ServiceQuote.php b/server/src/Http/Resources/v1/ServiceQuote.php index 13da60ba2..cba5e4974 100644 --- a/server/src/Http/Resources/v1/ServiceQuote.php +++ b/server/src/Http/Resources/v1/ServiceQuote.php @@ -32,7 +32,7 @@ public function toArray($request) 'amount' => $this->amount, 'currency' => $this->currency, 'meta' => data_get($this, 'meta', Utils::createObject()), - 'seats' => $this->when($this->resource->availability !== null, fn () => $this->resource->availability['seats']), + 'seating_capacity' => $this->when($this->resource->availability !== null, fn () => $this->resource->availability['seating_capacity']), 'pickup_eta' => $this->when($this->resource->availability !== null, fn () => $this->resource->availability['pickup_eta']), 'updated_at' => $this->updated_at, 'created_at' => $this->created_at, diff --git a/server/src/Jobs/RunOrderConfigAction.php b/server/src/Jobs/RunOrderConfigAction.php new file mode 100644 index 000000000..b719b29d7 --- /dev/null +++ b/server/src/Jobs/RunOrderConfigAction.php @@ -0,0 +1,43 @@ +orderUuid = $order->uuid; + } + + public function handle(): bool + { + $order = Order::withoutGlobalScopes()->where('uuid', $this->orderUuid)->first(); + $action = OrderConfigActions::get($this->action); + if (!$order || !$action) { + return false; + } + + $action->handle($order, $this->params, $this->context); + + return true; + } +} diff --git a/server/src/Models/DriverRating.php b/server/src/Models/DriverRating.php index 09d121166..b9aabafab 100644 --- a/server/src/Models/DriverRating.php +++ b/server/src/Models/DriverRating.php @@ -6,7 +6,7 @@ use Fleetbase\Traits\HasUuid; /** - * A rider's stars, from 1 to 5, for the driver of a finished order. One per order. + * A customer's stars, from 1 to 5, for the driver of a finished order. One per order. */ class DriverRating extends Model { diff --git a/server/src/Models/Order.php b/server/src/Models/Order.php index 480dcb259..263c846c2 100644 --- a/server/src/Models/Order.php +++ b/server/src/Models/Order.php @@ -120,8 +120,6 @@ class Order extends Model 'adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid', - 'fare_finalized_at', - 'paid_at', 'started', 'started_at', 'pod_method', @@ -257,8 +255,6 @@ class Order extends Model 'pod_required' => 'boolean', 'scheduled_at' => 'datetime', 'dispatched_at' => 'datetime', - 'fare_finalized_at' => 'datetime', - 'paid_at' => 'datetime', 'started_at' => 'datetime', // Orchestrator 'required_skills' => Json::class, @@ -514,7 +510,7 @@ public function purchaseRate(): BelongsTo } /** - * The rider's rating of the driver, once the order is finished and rated. + * The customer's rating of the driver, once the order is finished and rated. */ public function driverRating(): HasOne { @@ -539,40 +535,11 @@ public function dispatchOutcome(): ?string } /** - * Record that the order has been paid. Called by the billing package (Ledger). + * The custom fields of the order's config. Values are stored on the order. */ - public function markPaid(?Carbon $at = null): bool + public function customFields(): HasMany { - if ($this->paid_at) { - return false; - } - - return $this->forceFill(['paid_at' => $at ?? Carbon::now()])->saveQuietly(); - } - - /** - * The order's fare: the price it was bought at, with its lines, and the first price it was - * booked at as the estimate. `final` once the price was set from the actual trip. - */ - public function fare(): ?array - { - $quote = data_get($this, 'purchaseRate.serviceQuote'); - if (!$quote instanceof ServiceQuote) { - return null; - } - - $first = PurchaseRate::where('payload_uuid', $this->payload_uuid)->whereNotNull('payload_uuid')->oldest()->first()?->serviceQuote; - - return [ - 'final' => (bool) $this->fare_finalized_at, - 'total' => (int) $quote->amount, - 'currency' => $quote->currency, - 'estimate' => $first ? (int) $first->amount : null, - 'distance' => $quote->distance, - 'time' => $quote->time, - 'service' => data_get($quote, 'serviceRate.service_name'), - 'lines' => $quote->items()->get()->map(fn ($item) => ['label' => (string) ($item->details ?? $item->code), 'amount' => (int) $item->amount])->all(), - ]; + return $this->hasMany(\Fleetbase\Models\CustomField::class, 'subject_uuid', 'order_config_uuid')->orderBy('order'); } /** @@ -2086,7 +2053,9 @@ public function isIntegratedVendorOrder() */ public function getAdhocPingDistance(): int { - return (int) Utils::get($this, 'adhoc_distance', Utils::get($this, 'company.options.fleetops.adhoc_distance', 6000)); + $radius = $this->adhoc_distance ?? $this->currentConfig()?->policy('dispatch.adhoc.radius'); + + return (int) ($radius ?? Utils::get($this, 'company.options.fleetops.adhoc_distance', 6000)); } /** @@ -2155,6 +2124,21 @@ public function config(): ?OrderConfig return null; } + /** + * The order's own config, reusing the one already loaded on the order, for reading its + * policies and triggers often without loading it each time. Null for an order without a + * config of its own, which has no policies or triggers; `config()` falls back to the + * company's default config instead. + */ + public function currentConfig(): ?OrderConfig + { + if ($this->relationLoaded('orderConfig') && $this->orderConfig instanceof OrderConfig && $this->orderConfig->uuid === $this->order_config_uuid) { + return $this->orderConfig->setOrderContext($this); + } + + return $this->order_config_uuid ? $this->config() : null; + } + /** * Ensure the order has a persisted order config and normalized type. */ diff --git a/server/src/Models/OrderConfig.php b/server/src/Models/OrderConfig.php index fe561fc87..b783f8cbf 100644 --- a/server/src/Models/OrderConfig.php +++ b/server/src/Models/OrderConfig.php @@ -7,6 +7,7 @@ use Fleetbase\FleetOps\Flow\Activity; use Fleetbase\FleetOps\Support\AdhocDispatch\AdhocDispatch; use Fleetbase\FleetOps\Support\FleetOps; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; use Fleetbase\Models\Company; use Fleetbase\Models\Model; use Fleetbase\Support\Auth; @@ -69,10 +70,8 @@ class OrderConfig extends Model 'flow', 'entities', 'meta', - 'adhoc_strategy', - 'adhoc_offer_timeout', - 'customer_orders_adhoc', - 'match_vehicle_type', + 'policies', + 'triggers', ]; /** @@ -81,13 +80,12 @@ class OrderConfig extends Model * @var array */ protected $casts = [ - 'tags' => Json::class, - 'flow' => Json::class, - 'entities' => OrderConfigEntities::class, - 'meta' => Json::class, - 'adhoc_offer_timeout' => 'integer', - 'customer_orders_adhoc' => 'boolean', - 'match_vehicle_type' => 'boolean', + 'tags' => Json::class, + 'flow' => Json::class, + 'entities' => OrderConfigEntities::class, + 'meta' => Json::class, + 'policies' => Json::class, + 'triggers' => Json::class, ]; /** @@ -131,21 +129,51 @@ protected static function boot() $model->key = Str::slug($model->name); }); - static::saving(fn ($model) => $model->normalizeAdhocSettings()); + static::saving(fn ($model) => $model->normalizePolicies()); } /** - * Drop a strategy that isn't registered, and keep the offer timeout within its limits. + * Keep stored policies valid: drop an adhoc strategy that isn't registered, and keep the + * offer timeout within its limits. */ - public function normalizeAdhocSettings(): void + public function normalizePolicies(): void { - if ($this->adhoc_strategy !== null && !AdhocDispatch::has($this->adhoc_strategy)) { - $this->adhoc_strategy = null; + if (!is_array($this->policies)) { + return; } - if ($this->adhoc_offer_timeout !== null) { - $this->adhoc_offer_timeout = max(AdhocDispatch::MIN_OFFER_TIMEOUT, min(AdhocDispatch::MAX_OFFER_TIMEOUT, (int) $this->adhoc_offer_timeout)); + $policies = $this->policies; + + $strategy = data_get($policies, 'dispatch.adhoc.strategy'); + if ($strategy !== null && !AdhocDispatch::has($strategy)) { + data_set($policies, 'dispatch.adhoc.strategy', null); + } + + $timeout = data_get($policies, 'dispatch.adhoc.offer_timeout'); + if ($timeout !== null && $timeout !== '') { + data_set($policies, 'dispatch.adhoc.offer_timeout', max(AdhocDispatch::MIN_OFFER_TIMEOUT, min(AdhocDispatch::MAX_OFFER_TIMEOUT, (int) $timeout))); } + + $this->policies = $policies; + } + + /** + * Every policy setting, with each one the config doesn't set taken from its default. + */ + public function resolvedPolicies(): array + { + return OrderConfigPolicies::resolve(is_array($this->policies) ? $this->policies : []); + } + + /** + * One policy setting, in dot notation (`dispatch.adhoc.strategy`), or a whole policy + * (`dispatch.adhoc`). The registered default applies when the config doesn't set it. + */ + public function policy(string $key, mixed $default = null): mixed + { + $value = data_get($this->resolvedPolicies(), $key); + + return $value ?? $default; } /** @@ -523,6 +551,47 @@ public function canTransition(?string $fromCode, string $toCode): bool return $from->children()->contains(fn ($activity) => $activity->code === $toCode); } + /** + * Check an activity update against what the config declares, for every path that moves an + * order (console, API, driver app). Returns the activity to apply, which is the config's own + * definition when transitions are strict, and the reason the update is refused, or null. + * + * - a finished order takes no more activities, unless `$fromTerminal` (operator corrections) + * - strict transitions only allow a configured child of the current activity + * - a config whose lifecycle turns dispatch off refuses `dispatched` + * - an activity that needs proof of delivery (`require_pod`, or completing an order that + * requires proof) needs proof, unless `$bypassProof` + * + * @return array{0: Activity, 1: ?string} + */ + public function authorizeTransition(Order $order, Activity $activity, mixed $proof = null, bool $bypassProof = false, bool $fromTerminal = false): array + { + if (!$fromTerminal && $this->isTerminalActivityCode($order->status)) { + return [$activity, 'This order has already finished.']; + } + + if ($this->hasStrictTransitions()) { + $targetCode = $activity->get('code'); + $configured = $targetCode ? $this->getActivityByCode($targetCode) : null; + if (!$configured || !$this->canTransition($order->status, $targetCode)) { + return [$activity, 'This activity is not a permitted next step for the order.']; + } + + $activity = $configured; + } + + if ($activity->is('dispatched') && !$this->allowsDispatch()) { + return [$activity, 'Orders of this type are not dispatched.']; + } + + $requiresProof = $activity->get('require_pod') || ($activity->completesOrder() && $order->pod_required); + if ($requiresProof && !$proof && !$bypassProof) { + return [$activity, 'Proof of delivery is required for this activity or must be explicitly bypassed.']; + } + + return [$activity, null]; + } + /** * Creates an Activity instance representing a canceled order. * diff --git a/server/src/Models/ServiceQuote.php b/server/src/Models/ServiceQuote.php index a0dd40570..9d0593357 100644 --- a/server/src/Models/ServiceQuote.php +++ b/server/src/Models/ServiceQuote.php @@ -64,10 +64,10 @@ class ServiceQuote extends Model * The attributes that are mass assignable. */ /** - * Seats and pickup ETA for the quote's vehicle type, when the request asked for availability. - * Not stored. + * Seating capacity and pickup ETA for the quote's service type, when the request asked for + * availability. Not stored. * - * @var array{seats: ?int, pickup_eta: ?int}|null + * @var array{seating_capacity: ?int, pickup_eta: ?int}|null */ public ?array $availability = null; diff --git a/server/src/Notifications/OrderUpdate.php b/server/src/Notifications/OrderUpdate.php new file mode 100644 index 000000000..f7729d8bf --- /dev/null +++ b/server/src/Notifications/OrderUpdate.php @@ -0,0 +1,42 @@ +data = ['id' => $order->public_id, 'type' => $event]; + } + + public function via($notifiable) + { + return [FcmChannel::class, ApnChannel::class]; + } + + public function toFcm($notifiable) + { + return PushNotification::createFcmMessage($this->title, $this->message, $this->data); + } + + public function toApn($notifiable) + { + return PushNotification::createApnMessage($this->title, $this->message, $this->data, 'view_order'); + } +} diff --git a/server/src/Notifications/RideUpdate.php b/server/src/Notifications/RideUpdate.php deleted file mode 100644 index 61ce103f9..000000000 --- a/server/src/Notifications/RideUpdate.php +++ /dev/null @@ -1,81 +0,0 @@ - ['Your driver is on the way', '{driver} accepted your ride.'], - 'arriving' => ['Your driver is almost there', '{driver} is about a minute away.'], - 'arrived' => ['Your driver has arrived', '{driver} is waiting at the pickup point.'], - 'in_progress' => ['Your trip has started', 'Enjoy the ride.'], - 'completed' => ['You have arrived', 'Your trip is complete. See your fare in the app.'], - 'canceled' => ['Your ride was canceled', "You haven't been charged. You can book again."], - 'no_driver_found' => ['No driver found', 'No drivers are free right now. Try again in a few minutes.'], - ]; - - public string $title; - public string $message; - public array $data; - - public function __construct(public Order $order, public string $kind) - { - [$title, $message] = self::MESSAGES[$kind]; - $driver = trim((string) strtok((string) static::driverName($order), ' ')) ?: 'Your driver'; - - $this->title = $title; - $this->message = str_replace('{driver}', $driver, $message); - $this->data = ['id' => $order->public_id, 'type' => 'ride_' . $kind]; - } - - /** - * The driver's name, read without loading their whole record. - */ - public static function driverName(Order $order): ?string - { - if ($order->relationLoaded('driverAssigned')) { - return data_get($order, 'driverAssigned.name'); - } - - $userUuid = $order->driver_assigned_uuid ? Driver::withoutGlobalScopes()->where('uuid', $order->driver_assigned_uuid)->value('user_uuid') : null; - - return $userUuid ? User::where('uuid', $userUuid)->value('name') : null; - } - - public static function knows(string $kind): bool - { - return isset(self::MESSAGES[$kind]); - } - - public function via($notifiable) - { - return [FcmChannel::class, ApnChannel::class]; - } - - public function toFcm($notifiable) - { - return PushNotification::createFcmMessage($this->title, $this->message, $this->data); - } - - public function toApn($notifiable) - { - return PushNotification::createApnMessage($this->title, $this->message, $this->data, 'view_ride'); - } -} diff --git a/server/src/Observers/OrderObserver.php b/server/src/Observers/OrderObserver.php index ecf9cc5a4..b1fdaf73f 100644 --- a/server/src/Observers/OrderObserver.php +++ b/server/src/Observers/OrderObserver.php @@ -9,8 +9,8 @@ use Fleetbase\FleetOps\Models\TrackingStatus; use Fleetbase\FleetOps\Models\Waypoint; use Fleetbase\FleetOps\Support\LiveCacheService; -use Fleetbase\FleetOps\Support\Rides\FinalFare; -use Fleetbase\FleetOps\Support\Rides\RideUpdates; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\FleetOps\Support\OrderRepricing; use Fleetbase\FleetOps\Support\TrackingPublisher; use Fleetbase\Support\ApiModelCache; use Illuminate\Support\Facades\Cache; @@ -34,6 +34,8 @@ class OrderObserver public function created(Order $order) { $this->invalidateCache($order); + + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); } /** @@ -76,13 +78,36 @@ public function updated(Order $order) // Public tracking channels follow status, assignment and ETA changes. app(TrackingPublisher::class)->orderChanged($order); - // A rider hears about each step of their ride. This reads the order's changes, so it - // comes before pricing, which saves the order again. - RideUpdates::statusChanged($order); - - // A finished ride is priced from the actual trip. if ($order->wasChanged('status')) { - FinalFare::settle($order); + // A completed order is priced again from what actually happened, when its config's + // pricing policy asks for it. This comes first, so triggers see the final price. + OrderRepricing::settle($order); + + $this->runStatusTriggers($order); + } + } + + /** + * Run the config's triggers for the order's new status: the actions of the activity it + * reached, then `order.completed` or `order.canceled` when it reached one of those. + */ + protected function runStatusTriggers(Order $order): void + { + $config = $order->currentConfig(); + if (!$config) { + return; + } + + $completed = $config->getCompletedActivity()?->code; + $canceled = $config->getCanceledActivity()?->code; + $activity = $config->getActivityByCode((string) $order->status); + + OrderConfigTriggers::activity($order, $activity); + + if ($order->status === $completed) { + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED); + } elseif ($order->status === $canceled) { + OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CANCELED); } } diff --git a/server/src/Providers/FleetOpsServiceProvider.php b/server/src/Providers/FleetOpsServiceProvider.php index e037b2723..7e48459ea 100644 --- a/server/src/Providers/FleetOpsServiceProvider.php +++ b/server/src/Providers/FleetOpsServiceProvider.php @@ -58,7 +58,7 @@ class FleetOpsServiceProvider extends CoreServiceProvider public $commands = [ \Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, \Fleetbase\FleetOps\Console\Commands\DispatchOrders::class, - \Fleetbase\FleetOps\Console\Commands\CreateRideConfig::class, + \Fleetbase\FleetOps\Console\Commands\CreateOrderConfig::class, \Fleetbase\FleetOps\Console\Commands\TrackOrderDistanceAndTime::class, \Fleetbase\FleetOps\Console\Commands\FixDriverCompanies::class, \Fleetbase\FleetOps\Console\Commands\FixCustomerCompanies::class, diff --git a/server/src/Support/AdhocDispatch/AdhocDispatch.php b/server/src/Support/AdhocDispatch/AdhocDispatch.php index 8e7e9cf8e..c2809da59 100644 --- a/server/src/Support/AdhocDispatch/AdhocDispatch.php +++ b/server/src/Support/AdhocDispatch/AdhocDispatch.php @@ -58,12 +58,12 @@ public static function has(?string $name): bool } /** - * The strategy name for the order: its own, its config's, its company's, or the default. - * A name that isn't registered is skipped. + * The strategy name for the order: its own, its config's `dispatch.adhoc` policy, its + * company's, or the default. A name that isn't registered is skipped. */ public static function nameFor(Order $order): string { - foreach ([$order->adhoc_strategy, $order->config()?->adhoc_strategy] as $name) { + foreach ([$order->adhoc_strategy, $order->currentConfig()?->policy('dispatch.adhoc.strategy')] as $name) { if (static::has($name)) { return $name; } @@ -118,11 +118,12 @@ public static function openlyListed(): array } /** - * Seconds a driver has to accept a one-at-a-time offer: the config's, the company's, or the default. + * Seconds a driver has to accept a one-at-a-time offer: the config's `dispatch.adhoc` + * policy, the company's, or the default. */ public static function offerTimeout(Order $order): int { - $timeout = $order->config()?->adhoc_offer_timeout ?? $order->company?->getOption('fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; + $timeout = $order->currentConfig()?->policy('dispatch.adhoc.offer_timeout') ?? $order->company?->getOption('fleetops.adhoc_offer_timeout') ?? self::OFFER_TIMEOUT; return max(self::MIN_OFFER_TIMEOUT, min(self::MAX_OFFER_TIMEOUT, (int) $timeout)); } diff --git a/server/src/Support/AdhocDispatch/AdhocOfferListing.php b/server/src/Support/AdhocDispatch/AdhocOfferListing.php index badebe027..1921231d8 100644 --- a/server/src/Support/AdhocDispatch/AdhocOfferListing.php +++ b/server/src/Support/AdhocDispatch/AdhocOfferListing.php @@ -23,9 +23,10 @@ public static function apply(Builder $query, string $driverUuid, ?Company $compa $names = AdhocDispatch::names(); $open = AdhocDispatch::openlyListed(); $inNames = implode(', ', array_fill(0, count($names), '?')); - $strategy = "CASE WHEN {$orders}.adhoc_strategy IN ({$inNames}) THEN {$orders}.adhoc_strategy" - . " WHEN (SELECT oc.adhoc_strategy FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid) IN ({$inNames})" - . " THEN (SELECT oc.adhoc_strategy FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid) ELSE ? END"; + // The config's strategy is its `dispatch.adhoc` policy, in the `policies` JSON. + $configStrategy = "(SELECT oc.policies->>'$.dispatch.adhoc.strategy' FROM order_configs oc WHERE oc.uuid = {$orders}.order_config_uuid)"; + $strategy = "CASE WHEN {$orders}.adhoc_strategy IN ({$inNames}) THEN {$orders}.adhoc_strategy" + . " WHEN {$configStrategy} IN ({$inNames}) THEN {$configStrategy} ELSE ? END"; $bindings = [...$names, ...$names, AdhocDispatch::companyDefault($company)]; return $query->where(function ($query) use ($orders, $driverUuid, $open, $strategy, $bindings) { diff --git a/server/src/Support/AdhocDispatch/SequentialStrategy.php b/server/src/Support/AdhocDispatch/SequentialStrategy.php index de654ead1..dca66939e 100644 --- a/server/src/Support/AdhocDispatch/SequentialStrategy.php +++ b/server/src/Support/AdhocDispatch/SequentialStrategy.php @@ -15,8 +15,8 @@ /** * Offer the order to one driver at a time, nearest first, for the offer timeout. The next driver - * gets it when one declines or the time runs out, and the order is canceled as "No driver found" - * when nobody is left. Only the driver with the open offer may accept. + * gets it when one declines or the time runs out. When nobody is left, the order's config decides + * what happens (see `OrderOffers::exhausted()`). Only the driver with the open offer may accept. */ class SequentialStrategy implements AdhocDispatchStrategy { @@ -113,7 +113,7 @@ public function offerNext(Order $order): ?OrderOffer ? DriverMatching::nearby($order, $pickup)->whereNotIn('uuid', OrderOffers::offeredDrivers($order))->orderBy('distance')->first() : null; if (!$driver) { - OrderOffers::noDriverFound($order); + OrderOffers::exhausted($order); return null; } diff --git a/server/src/Support/DriverMatching.php b/server/src/Support/DriverMatching.php index e9b3b0625..87aa00863 100644 --- a/server/src/Support/DriverMatching.php +++ b/server/src/Support/DriverMatching.php @@ -4,19 +4,22 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\FleetOps\Models\OrderConfig; use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\Eloquent\Builder; /** - * Filters shared by every query that finds drivers for an order: the order's own company, - * drivers not already on a job, and the vehicle type the order needs. + * Filters shared by every query that finds drivers for an order: the order's own company, the + * vehicle type the order needs, and, when the order's config asks for it, drivers not already + * on an order. */ class DriverMatching { /** - * A driver whose current job has one of these statuses is free again. + * A driver whose current job has one of these statuses is free again, along with the + * terminal statuses of the company's order configs. */ - public const FREE_JOB_STATUSES = ['completed', 'canceled', 'no_show']; + public const FREE_JOB_STATUSES = ['completed', 'canceled']; /** * Available, online drivers who could take the order, with their `distance` from the pickup in @@ -48,7 +51,10 @@ public static function nearby(Order $order, Point $pickup, bool $testing = false public static function forOrder(Builder $query, Order $order): Builder { static::inCompany($query, $order->company_uuid); - static::notBusy($query); + + if ($order->currentConfig()?->policy('dispatch.matching.exclude_busy_drivers')) { + static::notBusy($query, $order->company_uuid); + } return static::forVehicleClass($query, static::vehicleClass($order)); } @@ -68,22 +74,39 @@ public static function inCompany(Builder $query, ?string $companyUuid): Builder * Drivers with no current job, or whose current job has finished. A job left behind by an * order that ended without clearing it doesn't keep the driver busy. */ - public static function notBusy(Builder $query): Builder + public static function notBusy(Builder $query, ?string $companyUuid = null): Builder { - $drivers = $query->getModel()->getTable(); + $drivers = $query->getModel()->getTable(); + $freeStatuses = static::freeJobStatuses($companyUuid); - return $query->where(function ($query) use ($drivers) { + return $query->where(function ($query) use ($drivers, $freeStatuses) { $query->whereNull($drivers . '.current_job_uuid') - ->orWhereNotExists(function ($jobs) use ($drivers) { + ->orWhereNotExists(function ($jobs) use ($drivers, $freeStatuses) { $jobs->selectRaw('1') ->from('orders') ->whereColumn('orders.uuid', $drivers . '.current_job_uuid') ->whereNull('orders.deleted_at') - ->whereNotIn('orders.status', self::FREE_JOB_STATUSES); + ->whereNotIn('orders.status', $freeStatuses); }); }); } + /** + * The statuses at which an order no longer keeps its driver busy: completed, canceled, and + * every terminal activity of the company's order configs. + */ + public static function freeJobStatuses(?string $companyUuid): array + { + $statuses = self::FREE_JOB_STATUSES; + if ($companyUuid) { + foreach (OrderConfig::where('company_uuid', $companyUuid)->get() as $config) { + $statuses = array_merge($statuses, $config->getTerminalActivityCodes()); + } + } + + return array_values(array_unique(array_filter($statuses, 'is_string'))); + } + /** * Drivers whose vehicle is of the class, compared without case. No class matches everyone. */ diff --git a/server/src/Support/Rides/DriverRatings.php b/server/src/Support/DriverRatings.php similarity index 97% rename from server/src/Support/Rides/DriverRatings.php rename to server/src/Support/DriverRatings.php index abfeb7d6c..7d9608daa 100644 --- a/server/src/Support/Rides/DriverRatings.php +++ b/server/src/Support/DriverRatings.php @@ -1,6 +1,6 @@ $company->uuid, - 'key' => 'transport', - 'namespace' => 'system:order-config:transport', - ], - static::transportConfigDefaults() - ); - } - - private static function transportConfigDefaults(): array - { - return [ - 'name' => 'Transport', - 'key' => 'transport', - 'namespace' => 'system:order-config:transport', - 'description' => 'Default order configuration for transport', - 'core_service' => 1, - 'status' => 'private', - 'version' => '0.0.1', - 'tags' => ['transport', 'delivery'], - 'entities' => [], - 'meta' => [], - 'flow' => [ - 'created' => [ - 'key' => 'created', - 'code' => 'created', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Created', - 'actions' => [], - 'details' => 'New order was created.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['dispatched'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'enroute' => [ - 'key' => 'enroute', - 'code' => 'enroute', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Driver Enroute', - 'actions' => [], - 'details' => 'Driver is en-route.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['completed'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'started' => [ - 'key' => 'started', - 'code' => 'started', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Started', - 'actions' => [], - 'details' => 'Order has been started', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['enroute'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'completed' => [ - 'key' => 'completed', - 'code' => 'completed', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Completed', - 'actions' => [], - 'details' => 'Order has been completed.', - 'options' => [], - 'complete' => true, - 'entities' => [], - 'sequence' => 0, - 'activities' => [], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - 'dispatched' => [ - 'key' => 'dispatched', - 'code' => 'dispatched', - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => 'Order Dispatched', - 'actions' => [], - 'details' => 'Order has been dispatched.', - 'options' => [], - 'complete' => false, - 'entities' => [], - 'sequence' => 0, - 'activities' => ['started'], - 'internalId' => Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ], - ], - ]; - } - - /** - * Creates or retrieves the ride config for a company: a rider's trip from request to drop-off. - * - * The driver accepting starts the order ("on the way"), then arrives, starts the trip and - * completes it, or records a no-show. Transitions are strict. Riders' orders are adhoc, - * priced and matched by vehicle class, and offered to one driver at a time. - */ - public static function createRideConfig(Company $company): OrderConfig - { - return OrderConfig::firstOrCreate( - [ - 'company_uuid' => $company->uuid, - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - ], - static::rideConfigDefaults() - ); - } - - /** - * The ride flow, keyed by activity code. - */ - public static function rideConfigDefaults(): array - { - $activity = fn (string $code, string $status, string $details, array $next, bool $complete = false) => [ - 'key' => $code, - 'code' => $code, - 'color' => '#1f2937', - 'logic' => [], - 'events' => [], - 'status' => $status, - 'actions' => [], - 'details' => $details, - 'options' => [], - 'complete' => $complete, - 'entities' => [], - 'sequence' => 0, - 'activities' => $next, - 'internalId' => (string) Str::uuid(), - 'pod_method' => 'scan', - 'require_pod' => false, - ]; - - return [ - 'name' => 'Ride', - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - 'description' => 'A rider\'s trip, from request to drop-off', - 'core_service' => 1, - 'status' => 'private', - 'version' => '0.0.1', - 'tags' => ['ride', 'passenger'], - // Riders' orders go to nearby drivers of the class they booked, one driver at a time. - 'customer_orders_adhoc' => true, - 'match_vehicle_type' => true, - 'adhoc_strategy' => 'sequential', - 'adhoc_offer_timeout' => 20, - 'entities' => [], - 'meta' => [ - 'lifecycle' => [ - 'initial' => 'created', - 'completed' => 'completed', - 'canceled' => 'canceled', - 'terminal' => ['no_show'], - 'strict_transitions' => true, - ], - ], - 'flow' => [ - 'created' => $activity('created', 'Ride requested', 'The rider requested a ride.', ['dispatched']), - 'dispatched' => $activity('dispatched', 'Finding a driver', 'Looking for a driver nearby.', ['started']), - 'started' => $activity('started', 'Driver on the way', 'The driver accepted and is on the way to the pickup.', ['arrived']), - 'arrived' => $activity('arrived', 'Driver has arrived', 'The driver is waiting at the pickup.', ['in_progress', 'no_show']), - 'in_progress' => $activity('in_progress', 'Trip in progress', 'The rider is on board.', ['completed']), - 'completed' => $activity('completed', 'Trip completed', 'The rider was dropped off.', [], true), - 'no_show' => $activity('no_show', 'Rider didn\'t show', 'The rider didn\'t come to the pickup.', []), - ], - ]; + return OrderConfigTemplates::create('transport', $company); } } diff --git a/server/src/Support/OrderChat.php b/server/src/Support/OrderChat.php new file mode 100644 index 000000000..401c64d9f --- /dev/null +++ b/server/src/Support/OrderChat.php @@ -0,0 +1,148 @@ + $order->company_uuid, + 'created_by_uuid' => $customerUser, + 'name' => 'Order ' . $order->public_id, + 'meta' => ['order_public_id' => $order->public_id, 'kind' => 'group'], + ]); + $order->forceFill(['chat_channel_uuid' => $channel->uuid])->saveQuietly(); + } + + static::participant($channel, $customerUser, 'customer'); + static::participant($channel, $driverUser, 'driver'); + + return $channel; + }); + } + + /** + * The order's channel if it was opened. + */ + public static function find(Order $order): ?ChatChannel + { + return $order->chat_channel_uuid ? ChatChannel::where('uuid', $order->chat_channel_uuid)->first() : null; + } + + /** + * Stop new messages in the order's channel. Its history stays readable. + */ + public static function close(Order $order): bool + { + $channel = static::find($order); + if (!$channel) { + return false; + } + + $channel->meta = array_merge((array) ($channel->meta ?? []), ['closed_at' => now()->toISOString()]); + + return $channel->save(); + } + + /** + * No one can write: the channel was closed, or the order has finished. + */ + public static function isClosed(Order $order, ?ChatChannel $channel = null): bool + { + $channel ??= static::find($order); + + return (bool) data_get($channel, 'meta.closed_at') || (bool) $order->config()?->isTerminalActivityCode($order->status); + } + + /** + * Messages oldest first, each marked as the customer's or the driver's. + */ + public static function messages(ChatChannel $channel, string $customerUser): Collection + { + return ChatMessage::where('chat_channel_uuid', $channel->uuid) + ->with('sender') + ->latest() + ->limit(self::MESSAGE_LIMIT) + ->get() + ->reverse() + ->values() + ->map(fn (ChatMessage $message) => [ + 'id' => $message->public_id ?? $message->uuid, + 'from' => data_get($message, 'sender.user_uuid') === $customerUser ? 'customer' : 'driver', + 'text' => (string) $message->content, + 'sent_at' => $message->created_at?->toISOString(), + ]); + } + + /** + * Send a message as the customer, and tell the driver. + */ + public static function send(ChatChannel $channel, string $customerUser, string $text): ChatMessage + { + return static::asUser($customerUser, function () use ($channel, $customerUser, $text) { + $sender = static::participant($channel, $customerUser, 'customer'); + $message = ChatMessage::create([ + 'company_uuid' => $channel->company_uuid, + 'chat_channel_uuid' => $channel->uuid, + 'sender_uuid' => $sender->uuid, + 'content' => $text, + ]); + $message->notifyParticipants(); + + return $message; + }); + } + + /** + * Core's chat logs record who added a participant from the signed-in user, which on a + * customer request is the key's owner rather than the customer, so the customer is signed in + * for the change. + */ + protected static function asUser(string $userUuid, callable $callback): mixed + { + $previous = session('user'); + session(['user' => $userUuid]); + + try { + return $callback(); + } finally { + session(['user' => $previous]); + } + } + + protected static function participant(ChatChannel $channel, string $userUuid, string $role): ChatParticipant + { + return ChatParticipant::firstOrCreate( + ['chat_channel_uuid' => $channel->uuid, 'user_uuid' => $userUuid], + ['company_uuid' => $channel->company_uuid, 'meta' => ['role' => $role]] + ); + } +} diff --git a/server/src/Support/OrderConfig/Actions/Action.php b/server/src/Support/OrderConfig/Actions/Action.php new file mode 100644 index 000000000..419dc70b5 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/Action.php @@ -0,0 +1,81 @@ +name; + } + + public function label(): string + { + return $this->label; + } + + public function description(): string + { + return $this->description; + } + + public function parameters(): array + { + return $this->parameters; + } + + /** + * Fill `{placeholders}` in the text: `{driver.name}`, `{driver.first_name}`, + * `{customer.name}`, `{order.id}`, `{order.tracking_number}`, `{order.status}`, and the + * activity's `{activity.status}` and `{activity.details}`. An unknown placeholder is left out. + */ + public static function render(?string $text, Order $order, array $context = []): string + { + if ($text === null || $text === '') { + return ''; + } + + $driverName = static::driverName($order); + $values = [ + 'driver.name' => $driverName ?? '', + 'driver.first_name' => $driverName ? (string) strtok($driverName, ' ') : '', + 'customer.name' => (string) data_get($order, 'customer.name', ''), + 'order.id' => (string) $order->public_id, + 'order.tracking_number' => (string) data_get($order, 'trackingNumber.tracking_number', ''), + 'order.status' => (string) $order->status, + 'activity.status' => (string) data_get($context, 'activity.status', ''), + 'activity.details' => (string) data_get($context, 'activity.details', ''), + ]; + + $rendered = preg_replace_callback('/\{\s*([a-z_]+(?:\.[a-z_]+)*)\s*\}/i', fn ($match) => $values[strtolower($match[1])] ?? '', $text); + + return trim(preg_replace('/\s{2,}/', ' ', $rendered)); + } + + /** + * The assigned driver's name, read without loading their whole record. + */ + public static function driverName(Order $order): ?string + { + if ($order->relationLoaded('driverAssigned')) { + return data_get($order, 'driverAssigned.name'); + } + + $userUuid = $order->driver_assigned_uuid ? Driver::withoutGlobalScopes()->where('uuid', $order->driver_assigned_uuid)->value('user_uuid') : null; + + return $userUuid ? User::where('uuid', $userUuid)->value('name') : null; + } +} diff --git a/server/src/Support/OrderConfig/Actions/CancelOrder.php b/server/src/Support/OrderConfig/Actions/CancelOrder.php new file mode 100644 index 000000000..2d8f85548 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/CancelOrder.php @@ -0,0 +1,27 @@ + 'Why the order was canceled.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + if ($order->config()?->isTerminalActivityCode($order->status)) { + return; + } + + $order->cancelWithReason(isset($params['reason']) ? (string) $params['reason'] : null); + } +} diff --git a/server/src/Support/OrderConfig/Actions/CloseChat.php b/server/src/Support/OrderConfig/Actions/CloseChat.php new file mode 100644 index 000000000..70d93d871 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/CloseChat.php @@ -0,0 +1,21 @@ + 'Notification title. Defaults to the activity\'s status. Placeholders such as {driver.first_name} are filled in.', + 'message' => 'Notification message. Defaults to the activity\'s details.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $customer = $order->customer; + if (!$customer || !method_exists($customer, 'notify')) { + return; + } + + $title = static::render($params['title'] ?? data_get($context, 'activity.status'), $order, $context); + $message = static::render($params['message'] ?? data_get($context, 'activity.details'), $order, $context); + if ($title === '' && $message === '') { + return; + } + + $customer->notify(new OrderUpdate($order, $title, $message, static::eventType($context))); + } + + /** + * The `type` apps receive in the push: the activity code or event, as `order_`. + */ + public static function eventType(array $context): string + { + $name = data_get($context, 'activity.code') ?? data_get($context, 'event', 'update'); + + return 'order_' . preg_replace('/[^a-z0-9_]+/', '_', strtolower((string) $name)); + } +} diff --git a/server/src/Support/OrderConfig/Actions/NotifyDriver.php b/server/src/Support/OrderConfig/Actions/NotifyDriver.php new file mode 100644 index 000000000..a132d68b9 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/NotifyDriver.php @@ -0,0 +1,36 @@ + 'Notification title. Defaults to the activity\'s status.', + 'message' => 'Notification message. Defaults to the activity\'s details.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $driver = $order->driver_assigned_uuid ? $order->loadAssignedDriver()->driverAssigned : null; + if (!$driver) { + return; + } + + $title = static::render($params['title'] ?? data_get($context, 'activity.status'), $order, $context); + $message = static::render($params['message'] ?? data_get($context, 'activity.details'), $order, $context); + if ($title === '' && $message === '') { + return; + } + + $driver->notify(new OrderUpdate($order, $title, $message, NotifyCustomer::eventType($context))); + } +} diff --git a/server/src/Support/OrderConfig/Actions/OpenChat.php b/server/src/Support/OrderConfig/Actions/OpenChat.php new file mode 100644 index 000000000..6260d7aa6 --- /dev/null +++ b/server/src/Support/OrderConfig/Actions/OpenChat.php @@ -0,0 +1,21 @@ + 'The meta key, in dot notation.', + 'value' => 'The value. `{now}` writes the current time.', + ]; + + public function handle(Order $order, array $params = [], array $context = []): void + { + $key = $params['key'] ?? null; + if (!is_string($key) || trim($key) === '') { + return; + } + + $value = $params['value'] ?? null; + $order->updateMeta(trim($key), $value === '{now}' ? now()->toISOString() : $value); + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigActions.php b/server/src/Support/OrderConfig/OrderConfigActions.php new file mode 100644 index 000000000..f77dbe2fa --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigActions.php @@ -0,0 +1,73 @@ +> + */ + protected static array $actions = [ + 'notify_customer' => NotifyCustomer::class, + 'notify_driver' => NotifyDriver::class, + 'open_chat' => OpenChat::class, + 'close_chat' => CloseChat::class, + 'set_meta' => SetMeta::class, + 'cancel' => CancelOrder::class, + ]; + + /** + * Add an action, or replace one, under its name. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigAction::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigAction::class . '.'); + } + + static::$actions[app($class)->name()] = $class; + } + + public static function has(?string $name): bool + { + return is_string($name) && isset(static::$actions[$name]); + } + + public static function get(string $name): ?OrderConfigAction + { + return static::has($name) ? app(static::$actions[$name]) : null; + } + + public static function names(): array + { + return array_keys(static::$actions); + } + + /** + * Every action, for people configuring triggers. + * + * @return array + */ + public static function describe(): array + { + return array_map(function (string $name) { + $action = static::get($name); + + return ['name' => $name, 'label' => $action->label(), 'description' => $action->description(), 'parameters' => $action->parameters()]; + }, static::names()); + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigPolicies.php b/server/src/Support/OrderConfig/OrderConfigPolicies.php new file mode 100644 index 000000000..feec4ba22 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigPolicies.php @@ -0,0 +1,134 @@ +> + */ + protected static array $policies = [ + 'dispatch.adhoc' => AdhocDispatchPolicy::class, + 'dispatch.matching' => DriverMatchingPolicy::class, + 'customer.ordering' => CustomerOrderingPolicy::class, + 'customer.cancellation' => CustomerCancellationPolicy::class, + 'customer.interactions' => CustomerInteractionsPolicy::class, + 'pricing' => PricingPolicy::class, + ]; + + /** + * Add a policy, or replace one, under its key. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigPolicy::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigPolicy::class . '.'); + } + + static::$policies[app($class)->key()] = $class; + } + + /** + * @return array + */ + public static function all(): array + { + return array_map(fn (string $class) => app($class), static::$policies); + } + + public static function get(string $key): ?OrderConfigPolicy + { + return isset(static::$policies[$key]) ? app(static::$policies[$key]) : null; + } + + /** + * Every policy's defaults, nested by key. + */ + public static function defaults(): array + { + $defaults = []; + foreach (static::all() as $key => $policy) { + data_set($defaults, $key, $policy->defaults()); + } + + return $defaults; + } + + /** + * The stored policies with every missing setting filled in from its default. Settings of + * policies that aren't registered are kept as stored. + */ + public static function resolve(?array $stored): array + { + $resolved = $stored ?? []; + foreach (static::all() as $key => $policy) { + $settings = data_get($resolved, $key); + data_set($resolved, $key, array_replace($policy->defaults(), is_array($settings) ? $settings : [])); + } + + return $resolved; + } + + /** + * Validation rules for a request carrying `policies`. + */ + public static function rules(string $prefix = 'policies'): array + { + $rules = [$prefix => ['nullable', 'array']]; + foreach (static::all() as $key => $policy) { + $rules[$prefix . '.' . $key] = ['nullable', 'array']; + foreach ($policy->rules() as $setting => $settingRules) { + $rules[$prefix . '.' . $key . '.' . $setting] = $settingRules; + } + } + + return $rules; + } + + /** + * Every policy, for people configuring them, with each setting's type (`boolean`, `number`, + * `text`, `list` or `choice`) and choices. + * + * @return array + */ + public static function describe(): array + { + return array_values(array_map(function (OrderConfigPolicy $policy) { + $rules = $policy->rules(); + $choices = $policy->choices(); + $settings = []; + foreach ($policy->defaults() as $name => $default) { + $settingRules = (array) ($rules[$name] ?? []); + $type = match (true) { + isset($choices[$name]) => 'choice', + is_bool($default) || in_array('boolean', $settingRules, true) => 'boolean', + is_array($default) || in_array('array', $settingRules, true) => 'list', + in_array('integer', $settingRules, true) || in_array('numeric', $settingRules, true) => 'number', + default => 'text', + }; + $settings[] = ['name' => $name, 'type' => $type, 'default' => $default, 'choices' => $choices[$name] ?? null]; + } + + return [ + 'key' => $policy->key(), + 'label' => $policy->label(), + 'description' => $policy->description(), + 'defaults' => $policy->defaults(), + 'settings' => $settings, + ]; + }, static::all())); + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigTemplates.php b/server/src/Support/OrderConfig/OrderConfigTemplates.php new file mode 100644 index 000000000..6fdaf7a49 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigTemplates.php @@ -0,0 +1,121 @@ +> + */ + protected static array $templates = [ + 'transport' => TransportTemplate::class, + 'passenger' => PassengerTemplate::class, + ]; + + /** + * Add a template, or replace one, under its key. + * + * @param class-string $class + */ + public static function register(string $class): void + { + if (!is_subclass_of($class, OrderConfigTemplate::class)) { + throw new \InvalidArgumentException($class . ' does not implement ' . OrderConfigTemplate::class . '.'); + } + + static::$templates[app($class)->key()] = $class; + } + + public static function has(?string $key): bool + { + return is_string($key) && isset(static::$templates[$key]); + } + + public static function get(string $key): ?OrderConfigTemplate + { + return static::has($key) ? app(static::$templates[$key]) : null; + } + + /** + * Every template, for people choosing one. + * + * @return array + */ + public static function describe(): array + { + return array_values(array_map(function (string $class) { + $template = app($class); + + return ['key' => $template->key(), 'name' => $template->name(), 'description' => $template->description()]; + }, static::$templates)); + } + + /** + * The attributes of the system config made from the template (`system:order-config:`). + */ + public static function attributes(string $key): array + { + $template = static::get($key); + if (!$template) { + throw new \InvalidArgumentException('No order config template named ' . $key . '.'); + } + + return array_replace([ + 'name' => $template->name(), + 'key' => $template->key(), + 'namespace' => 'system:order-config:' . $template->key(), + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + ], $template->attributes()); + } + + /** + * The company's config from the template, made when it doesn't have one yet. Without a name + * it is the company's system config for the template (`system:order-config:`), found + * again on the next call; with a name it is a new config of that name. + */ + public static function create(string $key, Company $company, ?string $name = null): OrderConfig + { + $template = static::get($key); + if (!$template) { + throw new \InvalidArgumentException('No order config template named ' . $key . '.'); + } + + $attributes = static::attributes($key); + + if ($name) { + $config = OrderConfig::create(array_replace($attributes, [ + 'company_uuid' => $company->uuid, + 'name' => $name, + 'core_service' => 0, + 'key' => Str::slug($name), + 'namespace' => Str::slug($company->name) . ':order-config:' . Str::slug($name), + ])); + } else { + $config = OrderConfig::firstOrCreate( + ['company_uuid' => $company->uuid, 'key' => $attributes['key'], 'namespace' => $attributes['namespace']], + $attributes + ); + } + + if ($config->wasRecentlyCreated) { + foreach ($template->customFields() as $field) { + $config->customFields()->create(array_replace($field, ['company_uuid' => $company->uuid])); + } + } + + return $config; + } +} diff --git a/server/src/Support/OrderConfig/OrderConfigTriggers.php b/server/src/Support/OrderConfig/OrderConfigTriggers.php new file mode 100644 index 000000000..b67b61887 --- /dev/null +++ b/server/src/Support/OrderConfig/OrderConfigTriggers.php @@ -0,0 +1,165 @@ + 'order.activity', + 'activity' => ['code' => $activity->code, 'status' => $activity->status, 'details' => $activity->details], + ]; + + return static::run($order, (array) ($activity->get('actions') ?? []), $context); + } + + /** + * An order event happened: run the config's triggers for it. + */ + public static function fire(Order $order, string $event, array $context = []): int + { + return static::run($order, static::forEvent($order, $event), ['event' => $event] + $context); + } + + /** + * The driver of an order reported a position: fire `driver.approaching` for each target + * the driver has just come close to. + */ + public static function driverMoved(Driver $driver, ?Order $order): int + { + if (!$order || !Utils::isPoint($driver->location)) { + return 0; + } + + $ran = 0; + foreach (static::forEvent($order, self::DRIVER_APPROACHING) as $trigger) { + $target = data_get($trigger, 'options.target', 'pickup') === 'dropoff' ? 'dropoff' : 'pickup'; + $distance = (int) data_get($trigger, 'options.distance', self::APPROACHING_DISTANCE); + $point = $target === 'dropoff' ? $order->payload?->dropoff?->location : $order->getPickupLocation(); + + if (!Utils::isPoint($point) || Utils::vincentyGreatCircleDistance($driver->location, $point) > $distance) { + continue; + } + + $onceKey = 'fleetops:order-config:approaching:' . $order->uuid . ':' . $target . ':' . $distance; + if (!static::passes($order, $trigger) || !Cache::add($onceKey, 1, now()->addHours(12))) { + continue; + } + + $ran += static::run($order, [$trigger], ['event' => self::DRIVER_APPROACHING, 'target' => $target]); + } + + return $ran; + } + + /** + * The config's triggers for the event. + */ + public static function forEvent(Order $order, string $event): array + { + $triggers = $order->currentConfig()?->triggers; + + return array_values(array_filter(is_array($triggers) ? $triggers : [], fn ($trigger) => is_array($trigger) && ($trigger['event'] ?? null) === $event)); + } + + /** + * Whether every condition of the trigger passes for the order. A trigger without any always passes. + */ + public static function passes(Order $order, array $trigger): bool + { + $when = $trigger['when'] ?? []; + if (!is_array($when) || $when === []) { + return true; + } + + try { + return collect($when)->every(fn ($logic) => is_array($logic) && (new Logic($logic))->passes($order)); + } catch (\Throwable $exception) { + Log::warning('Skipped an order config trigger whose conditions could not be read', ['order' => $order->public_id, 'error' => $exception->getMessage()]); + + return false; + } + } + + /** + * Queue (or run) each trigger whose action is registered and whose conditions pass. + */ + protected static function run(Order $order, array $triggers, array $context): int + { + $ran = 0; + foreach ($triggers as $trigger) { + $name = is_array($trigger) ? ($trigger['action'] ?? null) : null; + if (!OrderConfigActions::has($name) || !static::passes($order, $trigger)) { + continue; + } + + $params = is_array($trigger['params'] ?? null) ? $trigger['params'] : []; + + try { + if (static::$runImmediately) { + OrderConfigActions::get($name)->handle($order, $params, $context); + } else { + dispatch(new RunOrderConfigAction($order, $name, $params, $context)); + } + $ran++; + } catch (\Throwable $exception) { + Log::warning('An order config action failed', ['order' => $order->public_id, 'action' => $name, 'error' => $exception->getMessage()]); + } + } + + return $ran; + } +} diff --git a/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php b/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php new file mode 100644 index 000000000..e35343e4e --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/AdhocDispatchPolicy.php @@ -0,0 +1,59 @@ + false, + // A registered strategy name; empty uses the company's default. + 'strategy' => null, + // Seconds a driver has to accept a one-at-a-time offer; empty uses the company's. + 'offer_timeout' => null, + // Metres around the pickup to look for drivers; empty uses the order's or company's. + 'radius' => null, + // When every driver declined or let the offer run out: keep the order open for + // the operator, or cancel it. + 'on_exhausted' => self::KEEP_OPEN, + ]; + } + + public function choices(): array + { + return [ + 'strategy' => array_map(fn ($strategy) => ['value' => $strategy['name'], 'label' => $strategy['label']], AdhocDispatch::describe()), + 'on_exhausted' => [ + ['value' => self::KEEP_OPEN, 'label' => 'Keep the order open for the operator'], + ['value' => self::CANCEL, 'label' => 'Cancel the order'], + ], + ]; + } + + public function rules(): array + { + return [ + 'customer_orders' => ['nullable', 'boolean'], + 'strategy' => ['nullable', 'string', Rule::in(AdhocDispatch::names())], + 'offer_timeout' => ['nullable', 'integer', 'min:' . AdhocDispatch::MIN_OFFER_TIMEOUT, 'max:' . AdhocDispatch::MAX_OFFER_TIMEOUT], + 'radius' => ['nullable', 'integer', 'min:100', 'max:200000'], + 'on_exhausted' => ['nullable', Rule::in([self::KEEP_OPEN, self::CANCEL])], + ]; + } +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php new file mode 100644 index 000000000..4f80d46bf --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerCancellationPolicy.php @@ -0,0 +1,27 @@ + true, + // An activity code: once the order has reached it, the customer can no longer cancel. + // Empty: any time before the order finishes. + 'allowed_until' => null, + ]; + + protected array $choices = ['allowed_until' => 'activity']; + + protected array $rules = [ + 'enabled' => ['nullable', 'boolean'], + 'allowed_until' => ['nullable', 'string', 'max:64'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php new file mode 100644 index 000000000..9f8d6a94f --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerInteractionsPolicy.php @@ -0,0 +1,25 @@ + false, + 'rating' => false, + 'share_tracking' => false, + ]; + + protected array $rules = [ + 'chat' => ['nullable', 'boolean'], + 'rating' => ['nullable', 'boolean'], + 'share_tracking' => ['nullable', 'boolean'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php b/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php new file mode 100644 index 000000000..cc1614df6 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/CustomerOrderingPolicy.php @@ -0,0 +1,33 @@ + [], + // The order must be placed with a service quote. + 'require_quote' => false, + // While an earlier order of this config paid by one of these methods is completed but + // not settled, the customer can't place another. + 'require_settlement' => [], + ]; + + protected array $rules = [ + 'payment_methods' => ['nullable', 'array'], + 'payment_methods.*' => ['string', 'max:32'], + 'require_quote' => ['nullable', 'boolean'], + 'require_settlement' => ['nullable', 'array'], + 'require_settlement.*' => ['string', 'max:32'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php b/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php new file mode 100644 index 000000000..c830e7b30 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/DriverMatchingPolicy.php @@ -0,0 +1,25 @@ + false, + // Drivers whose current order hasn't finished aren't offered another. + 'exclude_busy_drivers' => false, + ]; + + protected array $rules = [ + 'vehicle_type' => ['nullable', 'boolean'], + 'exclude_busy_drivers' => ['nullable', 'boolean'], + ]; +} diff --git a/server/src/Support/OrderConfig/Policies/Policy.php b/server/src/Support/OrderConfig/Policies/Policy.php new file mode 100644 index 000000000..17425c4ca --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/Policy.php @@ -0,0 +1,48 @@ +key; + } + + public function label(): string + { + return $this->label; + } + + public function description(): string + { + return $this->description; + } + + public function defaults(): array + { + return $this->defaults; + } + + public function rules(): array + { + return $this->rules; + } + + public function choices(): array + { + return $this->choices; + } +} diff --git a/server/src/Support/OrderConfig/Policies/PricingPolicy.php b/server/src/Support/OrderConfig/Policies/PricingPolicy.php new file mode 100644 index 000000000..63f8ec0f0 --- /dev/null +++ b/server/src/Support/OrderConfig/Policies/PricingPolicy.php @@ -0,0 +1,26 @@ + false, + // The activity from which distance and time are measured. Empty: from when the order started. + 'metering_starts_at' => null, + ]; + + protected array $choices = ['metering_starts_at' => 'activity']; + + protected array $rules = [ + 'reprice_on_completion' => ['nullable', 'boolean'], + 'metering_starts_at' => ['nullable', 'string', 'max:64'], + ]; +} diff --git a/server/src/Support/OrderConfig/Templates/PassengerTemplate.php b/server/src/Support/OrderConfig/Templates/PassengerTemplate.php new file mode 100644 index 000000000..944fa1aca --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/PassengerTemplate.php @@ -0,0 +1,108 @@ + ['action' => 'notify_customer', 'params' => ['title' => $title, 'message' => $message]]; + + return [ + 'description' => $this->description, + 'tags' => ['passenger', 'on-demand'], + 'entities' => [], + 'meta' => [ + 'lifecycle' => [ + 'initial' => 'created', + 'completed' => 'completed', + 'canceled' => 'canceled', + 'terminal' => ['no_show'], + 'strict_transitions' => true, + ], + ], + 'policies' => [ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => true, 'strategy' => 'sequential', 'offer_timeout' => 20, 'on_exhausted' => 'cancel'], + 'matching' => ['vehicle_type' => true, 'exclude_busy_drivers' => true], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => ['cash', 'card'], 'require_quote' => true, 'require_settlement' => ['card']], + 'cancellation' => ['enabled' => true, 'allowed_until' => 'in_progress'], + 'interactions' => ['chat' => true, 'rating' => true, 'share_tracking' => true], + ], + 'pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress'], + ], + 'triggers' => [ + [ + 'event' => OrderConfigTriggers::DRIVER_APPROACHING, + 'options' => ['target' => 'pickup', 'distance' => 400], + 'when' => [['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => 'started']]]], + ] + $notify('Your driver is almost there', '{driver.first_name} is about a minute away.'), + ['event' => OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED] + $notify('No driver found', 'No drivers are free right now. Try again in a few minutes.'), + [ + 'event' => OrderConfigTriggers::ORDER_CANCELED, + // The customer was already told nobody was found. + 'when' => [['type' => 'and', 'conditions' => [['field' => 'dispatch_outcome', 'operator' => 'notEqual', 'value' => 'no_driver_found']]]], + ] + $notify('Your trip was canceled', "You haven't been charged. You can book again."), + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'close_chat'], + ], + 'flow' => [ + 'created' => static::activity('created', 'Trip requested', 'The customer requested a trip.', ['dispatched']), + 'dispatched' => static::activity('dispatched', 'Finding a driver', 'Looking for a driver nearby.', ['started']), + 'started' => static::activity('started', 'Driver on the way', 'The driver accepted and is on the way to the pickup.', ['arrived'], false, [ + $notify('Your driver is on the way', '{driver.first_name} accepted your trip.'), + ['action' => 'open_chat'], + ]), + 'arrived' => static::activity('arrived', 'Driver has arrived', 'The driver is waiting at the pickup.', ['in_progress', 'no_show'], false, [ + $notify('Your driver has arrived', '{driver.first_name} is waiting at the pickup point.'), + ]), + 'in_progress' => static::activity('in_progress', 'Trip in progress', 'The passenger is on board.', ['completed'], false, [ + $notify('Your trip has started', 'Sit back, you are on your way.'), + ]), + 'completed' => static::activity('completed', 'Trip completed', 'The passenger was dropped off.', [], true, [ + $notify('You have arrived', 'Your trip is complete. See the price in the app.'), + ['action' => 'close_chat'], + // Run when Ledger is installed: bill the final price straight away. + ['action' => 'send_invoice'], + ]), + 'no_show' => static::activity('no_show', 'Passenger didn\'t show', 'The passenger didn\'t come to the pickup.', [], false, [ + ['action' => 'close_chat'], + ]), + ], + ]; + } + + public function customFields(): array + { + return [ + [ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'default_value' => '1', + 'required' => false, + 'editable' => true, + 'validation_rules' => ['nullable', 'integer', 'min:1', 'max:50'], + 'help_text' => 'How many people are travelling.', + 'order' => 0, + ], + ]; + } +} diff --git a/server/src/Support/OrderConfig/Templates/Template.php b/server/src/Support/OrderConfig/Templates/Template.php new file mode 100644 index 000000000..068f51888 --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/Template.php @@ -0,0 +1,65 @@ +key; + } + + public function name(): string + { + return $this->name; + } + + public function description(): string + { + return $this->description; + } + + public function customFields(): array + { + return []; + } + + /** + * A flow activity in the stored format. + * + * @param array $next the codes of the activities that can follow + * @param array $actions triggers to run when an order reaches the activity + * @param array $extra any other activity attributes, such as `require_pod` + */ + protected static function activity(string $code, string $status, string $details, array $next = [], bool $complete = false, array $actions = [], array $extra = []): array + { + return array_replace([ + 'key' => $code, + 'code' => $code, + 'color' => '#1f2937', + 'logic' => [], + 'events' => [], + 'status' => $status, + 'actions' => $actions, + 'details' => $details, + 'options' => [], + 'complete' => $complete, + 'entities' => [], + 'sequence' => 0, + 'activities' => $next, + 'internalId' => (string) Str::uuid(), + 'pod_method' => 'scan', + 'require_pod' => false, + ], $extra); + } +} diff --git a/server/src/Support/OrderConfig/Templates/TransportTemplate.php b/server/src/Support/OrderConfig/Templates/TransportTemplate.php new file mode 100644 index 000000000..acff32231 --- /dev/null +++ b/server/src/Support/OrderConfig/Templates/TransportTemplate.php @@ -0,0 +1,31 @@ + $this->description, + 'tags' => ['transport', 'delivery'], + 'entities' => [], + 'meta' => [], + 'flow' => [ + 'created' => static::activity('created', 'Order Created', 'New order was created.', ['dispatched']), + 'enroute' => static::activity('enroute', 'Driver Enroute', 'Driver is en-route.', ['completed']), + 'started' => static::activity('started', 'Order Started', 'Order has been started', ['enroute']), + 'completed' => static::activity('completed', 'Order Completed', 'Order has been completed.', [], true), + 'dispatched' => static::activity('dispatched', 'Order Dispatched', 'Order has been dispatched.', ['started']), + ], + ]; + } +} diff --git a/server/src/Support/OrderCustomFields.php b/server/src/Support/OrderCustomFields.php new file mode 100644 index 000000000..1ea951f34 --- /dev/null +++ b/server/src/Support/OrderCustomFields.php @@ -0,0 +1,82 @@ +customFields()->get(); + if ($fields->isEmpty()) { + return null; + } + + $data = []; + $rules = []; + foreach ($fields as $field) { + $own = array_filter(is_array($field->validation_rules) ? $field->validation_rules : [], fn ($rule) => is_string($rule) && !in_array($rule, ['required', 'nullable'], true)); + + $data[$field->name] = static::valueFor($field, $values); + $rules[$field->name] = array_values(array_merge([$field->required ? 'required' : 'nullable'], $own)); + } + + $validator = Validator::make($data, $rules, [], $fields->mapWithKeys(fn (CustomField $field) => [$field->name => $field->label ?: $field->name])->all()); + + return $validator->fails() ? $validator->errors()->first() : null; + } + + /** + * Store the values on the order, for fields its config has. + */ + public static function apply(Order $order, array $values): int + { + if ($values === []) { + return 0; + } + + $stored = 0; + foreach ($order->customFields()->get() as $field) { + $value = static::valueFor($field, $values); + if ($value !== null) { + $order->setCustomFieldValue($field, $value); + $stored++; + } + } + + return $stored; + } + + /** + * The value given for the field under its name, its label, or its label in snake case. + */ + protected static function valueFor(CustomField $field, array $values): mixed + { + foreach (array_filter([$field->name, $field->label, $field->label ? Str::snake($field->label) : null]) as $key) { + if (array_key_exists($key, $values)) { + return $values[$key]; + } + } + + return null; + } +} diff --git a/server/src/Support/OrderOffers.php b/server/src/Support/OrderOffers.php index be486bf97..46e352302 100644 --- a/server/src/Support/OrderOffers.php +++ b/server/src/Support/OrderOffers.php @@ -6,6 +6,8 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; use Fleetbase\FleetOps\Models\OrderOffer; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\FleetOps\Support\OrderConfig\Policies\AdhocDispatchPolicy; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\Log; @@ -150,21 +152,43 @@ public static function announceClosed(Order $order, array $driverUuids, string $ } /** - * Nobody is left to offer the order to, so cancel it and say why. + * Nobody is left to offer the order to. The config's `dispatch.offer_exhausted` triggers run, + * and the order is canceled as "No driver found" when its `dispatch.adhoc` policy says so. + * Otherwise it stays open for the operator to assign, and later runs that find nobody again + * do nothing more. */ - public static function noDriverFound(Order $order): void + public static function exhausted(Order $order): void { - $order->cancelWithReason(self::NO_DRIVER_FOUND); + // An order kept open is offered again on each scheduled run; its config hears that + // nobody accepted only the first time. + if ($order->getMeta('dispatch_outcome') === self::NO_DRIVER_FOUND_OUTCOME) { + return; + } + + $order->updateMeta('dispatch_outcome', self::NO_DRIVER_FOUND_OUTCOME); + OrderConfigTriggers::fire($order, OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED); + + if ($order->currentConfig()?->policy('dispatch.adhoc.on_exhausted') === AdhocDispatchPolicy::CANCEL) { + $order->cancelWithReason(self::NO_DRIVER_FOUND); + } } /** - * How offering a canceled adhoc order ended: `no_driver_found` when every driver it was - * offered to declined or let the offer run out. Null otherwise, including when someone - * canceled it while an offer was still open, which withdraws that offer. + * How offering an adhoc order ended: `no_driver_found` when every driver it was offered to + * declined or let the offer run out and no driver has been assigned since. Null otherwise, + * including when someone canceled it while an offer was still open, which withdraws that offer. */ public static function outcome(Order $order): ?string { - if ($order->status !== 'canceled' || !$order->adhoc) { + if (!$order->adhoc || $order->driver_assigned_uuid) { + return null; + } + + if ($order->getMeta('dispatch_outcome') === self::NO_DRIVER_FOUND_OUTCOME) { + return self::NO_DRIVER_FOUND_OUTCOME; + } + + if ($order->status !== 'canceled') { return null; } diff --git a/server/src/Support/OrderRepricing.php b/server/src/Support/OrderRepricing.php new file mode 100644 index 000000000..fee3f10c1 --- /dev/null +++ b/server/src/Support/OrderRepricing.php @@ -0,0 +1,143 @@ +currentConfig(); + if (!$config || !$config->policy('pricing.reprice_on_completion') || $order->status !== $config->getCompletedActivity()?->code) { + return null; + } + + if (data_get($order, 'purchaseRate.meta.repriced')) { + return null; + } + + $rate = data_get($order, 'purchaseRate.serviceQuote.serviceRate'); + if (!$rate instanceof ServiceRate) { + return null; + } + + $meteredFrom = static::meteringStartedAt($order, $config->policy('pricing.metering_starts_at')); + [$distance, $source] = static::distance($order, $meteredFrom); + $duration = max(0, (int) $meteredFrom->diffInSeconds(Carbon::now(), true)); + $stops = collect([$order->payload?->pickup, $order->payload?->dropoff])->filter()->values(); + [$subTotal, $lines] = $rate->quoteFromPreliminaryData([], $stops, $distance, $duration, false, 2); + + $quote = static::quote($order, $rate, (int) $subTotal, $distance, $duration, $lines); + $order->purchaseServiceQuote($quote, [ + 'repriced' => [ + 'distance' => $distance, + 'time' => $duration, + 'distance_source' => $source, + 'metered_from' => $meteredFrom->toISOString(), + 'previous_amount' => data_get($order, 'purchaseRate.serviceQuote.amount'), + ], + ]); + + return $quote; + } + + /** + * When metering began: the first time the order reached the activity, else when it started. + */ + public static function meteringStartedAt(Order $order, ?string $activityCode = null): Carbon + { + $reached = $activityCode && $order->tracking_number_uuid + ? TrackingStatus::where('tracking_number_uuid', $order->tracking_number_uuid)->where('code', TrackingStatus::prepareCode($activityCode))->oldest()->value('created_at') + : null; + + return Carbon::parse($reached ?? $order->started_at ?? $order->created_at ?? Carbon::now()); + } + + /** + * Metres the driver's recorded positions cover since metering began, and where the figure + * came from. With too few positions it falls back to the straight line between the stops. + */ + public static function distance(Order $order, Carbon $since): array + { + $points = Position::where('order_uuid', $order->uuid) + ->where('created_at', '>=', $since) + ->orderBy('created_at') + ->orderBy('id') + ->get() + ->map(fn (Position $position) => $position->coordinates) + ->filter(fn ($point) => Utils::isPoint($point)) + ->values(); + + $metres = 0.0; + for ($i = 1; $i < $points->count(); $i++) { + $metres += Utils::vincentyGreatCircleDistance($points[$i - 1], $points[$i]); + } + if ($metres > 0) { + return [(int) round($metres), 'positions']; + } + + $pickup = $order->payload?->pickup?->location; + $dropoff = $order->payload?->dropoff?->location; + + return Utils::isPoint($pickup) && Utils::isPoint($dropoff) ? [(int) round(Utils::vincentyGreatCircleDistance($pickup, $dropoff)), 'straight_line'] : [0, 'none']; + } + + protected static function label(ServiceRate $rate, string $details, int $index): string + { + if ($index === 0) { + return 'Base'; + } + + return match ($rate->rate_calculation_method) { + 'per_meter' => 'Distance', + 'algo', 'algorithm' => 'Distance and time', + default => $details !== '' ? $details : 'Charge', + }; + } + + protected static function quote(Order $order, ServiceRate $rate, int $amount, int $distance, int $duration, iterable $lines): ServiceQuote + { + $quote = ServiceQuote::create([ + 'request_id' => 'reprice_' . Str::lower(Str::random(12)), + 'company_uuid' => $order->company_uuid, + 'service_rate_uuid' => $rate->uuid, + 'payload_uuid' => $order->payload_uuid, + 'amount' => $amount, + 'currency' => $rate->currency, + 'distance' => $distance, + 'time' => $duration, + ]); + + foreach (collect($lines)->values() as $index => $line) { + ServiceQuoteItem::create([ + 'service_quote_uuid' => $quote->uuid, + 'amount' => (int) data_get($line, 'amount', 0), + 'currency' => $rate->currency, + 'details' => static::label($rate, (string) data_get($line, 'details'), $index), + 'code' => data_get($line, 'code'), + ]); + } + + return $quote; + } +} diff --git a/server/src/Support/Rides/FinalFare.php b/server/src/Support/Rides/FinalFare.php deleted file mode 100644 index 10d53acfa..000000000 --- a/server/src/Support/Rides/FinalFare.php +++ /dev/null @@ -1,144 +0,0 @@ -status !== 'completed' || $order->fare_finalized_at) { - return null; - } - - $rate = data_get($order, 'purchaseRate.serviceQuote.serviceRate'); - if (!$rate instanceof ServiceRate) { - return null; - } - - $startedAt = static::tripStartedAt($order); - [$distance, $source] = static::distance($order, $startedAt); - $duration = max(0, (int) $startedAt->diffInSeconds(Carbon::now(), true)); - $stops = collect([$order->payload?->pickup, $order->payload?->dropoff])->filter()->values(); - [$subTotal, $lines] = $rate->quoteFromPreliminaryData([], $stops, $distance, $duration, false, 2); - $estimate = data_get($order, 'purchaseRate.serviceQuote.amount'); - - $fare = [ - 'final' => true, - 'total' => (int) $subTotal, - 'currency' => $rate->currency, - 'estimate' => is_numeric($estimate) ? (int) $estimate : null, - 'distance_m' => $distance, - 'duration_s' => $duration, - 'distance_source' => $source, - 'lines' => collect($lines)->values()->map(fn ($line, $index) => [ - 'label' => static::label($rate, (string) data_get($line, 'details'), $index), - 'amount' => (int) data_get($line, 'amount', 0), - 'code' => data_get($line, 'code'), - ])->all(), - ]; - - // The order is marked first, so Ledger sees a final fare when the new price arrives. - $order->forceFill(['fare_finalized_at' => now()])->saveQuietly(); - $order->purchaseServiceQuote(static::quote($order, $rate, $fare, $lines)); - - return $fare; - } - - /** - * When the rider got in: the trip's `in_progress` step, else when the driver started. - */ - public static function tripStartedAt(Order $order): Carbon - { - $boarded = $order->tracking_number_uuid - ? TrackingStatus::where('tracking_number_uuid', $order->tracking_number_uuid)->where('code', 'IN_PROGRESS')->oldest()->value('created_at') - : null; - - return Carbon::parse($boarded ?? $order->started_at ?? $order->created_at ?? Carbon::now()); - } - - /** - * Metres the car's recorded positions cover since the trip started, and where the figure - * came from. With too few positions it falls back to the straight line between the stops. - */ - public static function distance(Order $order, Carbon $since): array - { - $points = Position::where('order_uuid', $order->uuid) - ->where('created_at', '>=', $since) - ->orderBy('created_at') - ->orderBy('id') - ->get() - ->map(fn (Position $position) => $position->coordinates) - ->filter(fn ($point) => Utils::isPoint($point)) - ->values(); - - $metres = 0.0; - for ($i = 1; $i < $points->count(); $i++) { - $metres += Utils::vincentyGreatCircleDistance($points[$i - 1], $points[$i]); - } - if ($metres > 0) { - return [(int) round($metres), 'positions']; - } - - $pickup = $order->payload?->pickup?->location; - $dropoff = $order->payload?->dropoff?->location; - - return Utils::isPoint($pickup) && Utils::isPoint($dropoff) ? [(int) round(Utils::vincentyGreatCircleDistance($pickup, $dropoff)), 'straight_line'] : [0, 'none']; - } - - protected static function label(ServiceRate $rate, string $details, int $index): string - { - if ($index === 0) { - return 'Base fare'; - } - - return match ($rate->rate_calculation_method) { - 'per_meter' => 'Distance', - 'algo', 'algorithm' => 'Distance and time', - default => $details !== '' ? $details : 'Fare', - }; - } - - protected static function quote(Order $order, ServiceRate $rate, array $fare, iterable $lines): ServiceQuote - { - $quote = ServiceQuote::create([ - 'request_id' => 'final_' . Str::lower(Str::random(12)), - 'company_uuid' => $order->company_uuid, - 'service_rate_uuid' => $rate->uuid, - 'amount' => $fare['total'], - 'currency' => $fare['currency'], - 'distance' => $fare['distance_m'], - 'time' => $fare['duration_s'], - ]); - - foreach ($fare['lines'] as $line) { - ServiceQuoteItem::create([ - 'service_quote_uuid' => $quote->uuid, - 'amount' => $line['amount'], - 'currency' => $fare['currency'], - 'details' => $line['label'], - 'code' => $line['code'], - ]); - } - - return $quote; - } -} diff --git a/server/src/Support/Rides/RideChat.php b/server/src/Support/Rides/RideChat.php deleted file mode 100644 index 98fc98b97..000000000 --- a/server/src/Support/Rides/RideChat.php +++ /dev/null @@ -1,114 +0,0 @@ -chat_channel_uuid ? ChatChannel::where('uuid', $order->chat_channel_uuid)->first() : null; - if (!$channel) { - // Creating the channel adds its creator, the rider, as a participant. - $channel = ChatChannel::create([ - 'company_uuid' => $order->company_uuid, - 'created_by_uuid' => $riderUser, - 'name' => 'Ride ' . $order->public_id, - 'meta' => ['order_public_id' => $order->public_id, 'kind' => 'group'], - ]); - $order->forceFill(['chat_channel_uuid' => $channel->uuid])->saveQuietly(); - } - - static::participant($channel, $riderUser, 'customer'); - static::participant($channel, $driverUser, 'driver'); - - return $channel; - }); - } - - /** - * Messages oldest first, each marked as the rider's or the driver's. - */ - public static function messages(ChatChannel $channel, string $riderUser): Collection - { - return ChatMessage::where('chat_channel_uuid', $channel->uuid) - ->with('sender') - ->latest() - ->limit(self::MESSAGE_LIMIT) - ->get() - ->reverse() - ->values() - ->map(fn (ChatMessage $message) => [ - 'id' => $message->public_id ?? $message->uuid, - 'from' => data_get($message, 'sender.user_uuid') === $riderUser ? 'rider' : 'driver', - 'text' => (string) $message->content, - 'sent_at' => $message->created_at?->toISOString(), - ]); - } - - /** - * Send a message as the rider, and tell the driver. - */ - public static function send(ChatChannel $channel, string $riderUser, string $text): ChatMessage - { - return static::asUser($riderUser, function () use ($channel, $riderUser, $text) { - $sender = static::participant($channel, $riderUser, 'customer'); - $message = ChatMessage::create([ - 'company_uuid' => $channel->company_uuid, - 'chat_channel_uuid' => $channel->uuid, - 'sender_uuid' => $sender->uuid, - 'content' => $text, - ]); - $message->notifyParticipants(); - - return $message; - }); - } - - /** - * Core's chat logs record who added a participant from the signed-in user, which on a rider - * request is the key's owner rather than the rider, so the rider is signed in for the change. - */ - protected static function asUser(string $userUuid, callable $callback): mixed - { - $previous = session('user'); - session(['user' => $userUuid]); - - try { - return $callback(); - } finally { - session(['user' => $previous]); - } - } - - protected static function participant(ChatChannel $channel, string $userUuid, string $role): ChatParticipant - { - return ChatParticipant::firstOrCreate( - ['chat_channel_uuid' => $channel->uuid, 'user_uuid' => $userUuid], - ['company_uuid' => $channel->company_uuid, 'meta' => ['role' => $role]] - ); - } -} diff --git a/server/src/Support/Rides/RideUpdates.php b/server/src/Support/Rides/RideUpdates.php deleted file mode 100644 index 8db3b98aa..000000000 --- a/server/src/Support/Rides/RideUpdates.php +++ /dev/null @@ -1,81 +0,0 @@ -wasChanged('status')) { - return false; - } - - $kind = OrderOffers::outcome($order) === OrderOffers::NO_DRIVER_FOUND_OUTCOME ? 'no_driver_found' : (string) $order->status; - - return RideUpdate::knows($kind) && static::send($order, $kind); - } - - /** - * The driver of a ride reported a position: tell the rider once when the car is close. - */ - public static function driverMoved(Driver $driver, ?Order $order): bool - { - if (!$order || !static::isRide($order) || $order->status !== 'started') { - return false; - } - - $pickup = $order->getPickupLocation(); - if (!Utils::isPoint($pickup) || !Utils::isPoint($driver->location)) { - return false; - } - - $distance = Utils::vincentyGreatCircleDistance($driver->location, $pickup); - if ($distance > self::ARRIVING_DISTANCE || !Cache::add('fleetops:ride:arriving:' . $order->uuid, 1, now()->addHours(6))) { - return false; - } - - return static::send($order, 'arriving'); - } - - public static function isRide(Order $order): bool - { - return $order->type === 'ride'; - } - - protected static function send(Order $order, string $kind): bool - { - $rider = $order->customer; - if (!$rider || !method_exists($rider, 'notify')) { - return false; - } - - try { - $rider->notify(new RideUpdate($order, $kind)); - } catch (\Throwable $exception) { - Log::warning('Unable to send a ride update', ['order' => $order->public_id, 'error' => $exception->getMessage()]); - - return false; - } - - return true; - } -} diff --git a/server/src/Support/SocketChannels.php b/server/src/Support/SocketChannels.php index c51ffa88d..c5181bcd4 100644 --- a/server/src/Support/SocketChannels.php +++ b/server/src/Support/SocketChannels.php @@ -214,7 +214,7 @@ public static function narrowOrder(SocketPrincipal $principal, Model $order): bo /** * Drivers: a driver only themselves. Never a customer, because the driver's location events - * carry their phone number; riders follow the car through their order instead. + * carry their phone number; customers follow the driver through their order instead. */ public static function narrowDriver(SocketPrincipal $principal, Model $driver): bool { diff --git a/server/src/Support/TrackingPage/TrackingShare.php b/server/src/Support/TrackingPage/TrackingShare.php index 6231e24ab..77a913f0e 100644 --- a/server/src/Support/TrackingPage/TrackingShare.php +++ b/server/src/Support/TrackingPage/TrackingShare.php @@ -6,9 +6,9 @@ use Illuminate\Support\Carbon; /** - * A link a rider sends to someone they trust, so they can follow the trip live without a code. - * The token is `{expiry}.{signature}`, signed with the app key over the order, the rider and the - * expiry, so it only opens that rider's view of that order, and only until it expires. + * A link a customer sends to someone they trust, so they can follow the order live without a + * code. The token is `{expiry}.{signature}`, signed with the app key over the order, the customer + * and the expiry, so it only opens that customer's view of that order, and only until it expires. */ class TrackingShare { diff --git a/server/src/routes.php b/server/src/routes.php index 60185e1a8..ce9f8d020 100644 --- a/server/src/routes.php +++ b/server/src/routes.php @@ -136,7 +136,6 @@ function ($router) { $router->post('orders/{id}/messages', 'CustomerController@sendOrderMessage')->middleware('throttle:30,1'); $router->post('orders/{id}/rating', 'CustomerController@rateOrder'); $router->post('orders/{id}/share', 'CustomerController@shareOrder'); - $router->get('ride-settings', 'CustomerController@rideSettings'); $router->delete('me', 'CustomerController@deleteMe'); }); }); @@ -592,7 +591,13 @@ function ($router, $controller) { $router->match(['get', 'post'], 'export', $controller('export')); } ); - $router->fleetbaseRoutes('order-configs'); + $router->fleetbaseRoutes( + 'order-configs', + function ($router, $controller) { + $router->get('capabilities', $controller('capabilities')); + $router->post('from-template', $controller('createFromTemplate')); + } + ); $router->fleetbaseRoutes('payloads'); $router->fleetbaseRoutes( 'places', diff --git a/server/tests/ApiCustomerControllerContractsTest.php b/server/tests/ApiCustomerControllerContractsTest.php index f0dd9c9fe..8e382b139 100644 --- a/server/tests/ApiCustomerControllerContractsTest.php +++ b/server/tests/ApiCustomerControllerContractsTest.php @@ -79,7 +79,7 @@ class FleetOpsApiCustomerControllerProbe extends CustomerController public array $uuidLookups = []; public array $devices = []; - protected function riderPlaceQuery(Contact $customer): mixed + protected function customerPlaceQuery(Contact $customer): mixed { return null; } @@ -331,17 +331,24 @@ protected function resolveOrderConfig(CreateCustomerOrderRequest $request, strin return $this->orderConfig; } - public bool $unpaidRide = false; - public array $paymentMethods = []; + public bool $unsettledOrder = false; + public array $paymentMethods = []; protected function setPayloadPaymentMethod(string $payloadUuid, string $paymentMethod): void { $this->paymentMethods[] = [$payloadUuid, $paymentMethod]; } - protected function hasUnpaidRide(Contact $customer): bool + public array $enabledOrderConfigs = []; + + protected function hasUnsettledOrder(Contact $customer, OrderConfig $orderConfig): bool + { + return $this->unsettledOrder && (bool) $orderConfig->policy('customer.ordering.require_settlement'); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed { - return $this->unpaidRide; + return $key === 'fleet-ops.customer-enabled-order-configs' ? $this->enabledOrderConfigs : $default; } protected function getUuid(array|string $table, array $where, array $options = []): mixed @@ -1238,7 +1245,7 @@ public function hasDebugModeEnabled() config(['fleetops.customers.verification_bypass_code' => null, 'fleetops.customers.review_accounts' => []]); }); -function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, array $attributes = []): Order +function fleetopsCustomerOrderFor(FleetOpsApiCustomerControllerProbe $controller, array $attributes = []): Order { $order = $controller->order; $order->setRawAttributes(array_merge($order->getAttributes(), $attributes), true); @@ -1266,7 +1273,7 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($controller->requestCode(Request::create('/', 'POST', ['phone' => 'a@b.test']))->getStatusCode())->toBe(400); }); -test('verify code tells a new rider apart only after the code is proven', function () { +test('verify code tells a new customer apart only after the code is proven', function () { $controller = fleetopsApiCustomerController(); $controller->verificationUser = null; $request = fn () => Request::create('/', 'POST', ['identity' => '+15550001111', 'code' => '123456']); @@ -1279,7 +1286,7 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a expect(fleetopsApiCustomerJson($controller->verifyCode($request())))->toBe(['error' => 'Invalid verification code.']); }); -test('a rider cannot change phone without a code for that number', function () { +test('a customer cannot change phone without a code for that number', function () { $controller = fleetopsApiCustomerController(); $controller->activeUser = null; $before = $controller->currentCustomer->phone; @@ -1294,7 +1301,7 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($controller->currentCustomer->phone)->toBe($before); }); -test('a rider cannot take a phone number held by another account', function () { +test('a customer cannot take a phone number held by another account', function () { $controller = fleetopsApiCustomerController(); $controller->activeUser = fleetopsApiCustomerUser(); $controller->activeUser->uuid = 'someone-else'; @@ -1316,9 +1323,9 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($free->smsVerifications[0][1] ?? null)->toBe('fleetops_customer_phone_change'); }); -test('rider order actions treat another rider as not found', function () { +test('customer order actions treat another customer as not found', function () { $controller = fleetopsApiCustomerController(); - fleetopsRiderOrderFor($controller, ['customer_uuid' => 'someone-else', 'status' => 'created']); + fleetopsCustomerOrderFor($controller, ['customer_uuid' => 'someone-else', 'status' => 'created']); $request = Request::create('/', 'POST'); expect($controller->dispatchOrder('order_1')->getStatusCode())->toBe(404) @@ -1328,15 +1335,15 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and($controller->orderEta('order_1', $request)->getStatusCode())->toBe(404); }); -test('a finished order cannot be canceled or dispatched by its rider', function (string $status) { +test('a finished order cannot be canceled or dispatched by its customer', function (string $status) { $controller = fleetopsApiCustomerController(); - fleetopsRiderOrderFor($controller, ['customer_uuid' => $controller->currentCustomer->uuid, 'status' => $status]); + fleetopsCustomerOrderFor($controller, ['customer_uuid' => $controller->currentCustomer->uuid, 'status' => $status]); expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) ->and($controller->dispatchOrder('order_1')->getStatusCode())->toBe(422); })->with(['completed', 'canceled']); -test('rider place routes only touch places the rider owns', function () { +test('customer place routes only touch places the customer owns', function () { $controller = fleetopsApiCustomerController(); $controller->place = new Place(); $controller->place->setRawAttributes(['uuid' => 'p', 'owner_uuid' => 'someone-else'], true); @@ -1367,7 +1374,7 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a expect($source)->toContain("'password' => 'nullable|string|min:8'"); }); -test('an expired fare or another company\'s fare is refused when booking', function (array $attributes) { +test('an expired quote or another company\'s quote is refused when ordering', function (array $attributes) { $controller = fleetopsApiCustomerController(); $controller->serviceQuote->setRawAttributes($attributes, true); @@ -1388,7 +1395,7 @@ function fleetopsRiderOrderFor(FleetOpsApiCustomerControllerProbe $controller, a ->and(Fleetbase\FleetOps\Support\SocketChannels::customerPrincipal(Request::create('/'), null))->toBeNull(); }); -class FleetOpsRiderOrderFake extends FleetOpsApiCustomerOrderFake +class FleetOpsCustomerOwnOrderFake extends FleetOpsApiCustomerOrderFake { public array $faked = []; public array $calls = []; @@ -1439,7 +1446,7 @@ public function tracker(): Fleetbase\FleetOps\Support\OrderTracker } } -class FleetOpsRiderTrackerFake extends Fleetbase\FleetOps\Support\OrderTracker +class FleetOpsCustomerTrackerFake extends Fleetbase\FleetOps\Support\OrderTracker { public function __construct(private bool $fails = false) { @@ -1465,7 +1472,7 @@ private function answer(string $name): array } } -class FleetOpsRiderPlaceFake extends Place +class FleetOpsCustomerSavedPlaceFake extends Place { public array $updates = []; public bool $deleted = false; @@ -1485,18 +1492,18 @@ public function delete() } } -function fleetopsRiderController(array $order = [], array $faked = []): FleetOpsApiCustomerControllerProbe +function fleetopsCustomerOrderController(array $order = [], array $faked = []): FleetOpsApiCustomerControllerProbe { $controller = fleetopsApiCustomerController(); - $rider = new FleetOpsRiderOrderFake(); - $rider->setRawAttributes(array_merge(['uuid' => 'order-uuid', 'customer_uuid' => $controller->currentCustomer->uuid, 'status' => 'created'], $order), true); - $rider->faked = array_merge(['dispatched' => false, 'hasDriverAssigned' => false, 'adhoc' => true, 'driverAssigned' => null, 'vehicleAssigned' => null], $faked); - $controller->order = $rider; + $owned = new FleetOpsCustomerOwnOrderFake(); + $owned->setRawAttributes(array_merge(['uuid' => 'order-uuid', 'customer_uuid' => $controller->currentCustomer->uuid, 'status' => 'created'], $order), true); + $owned->faked = array_merge(['dispatched' => false, 'hasDriverAssigned' => false, 'adhoc' => true, 'driverAssigned' => null, 'vehicleAssigned' => null], $faked); + $controller->order = $owned; return $controller; } -test('every rider route answers 401 without a signed-in rider', function () { +test('every customer route answers 401 without a signed-in customer', function () { $controller = fleetopsApiCustomerController(); $controller->currentCustomer = null; $request = Request::create('/', 'GET'); @@ -1510,7 +1517,7 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($controller->cancelOrder('order_1', $request)->getStatusCode())->toBe(404); }); -test('rider place search only asks for the rider and caps the limit', function () { +test('customer place search only asks for the customer and caps the limit', function () { $controller = fleetopsApiCustomerController(); $controller->searchPlaces(Request::create('/', 'GET', ['query' => 'home', 'limit' => 500, 'latitude' => 1.2, 'longitude' => 103.8])); @@ -1520,9 +1527,9 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($controller->placeQueries[0][2])->toMatchArray(['limit' => 50, 'geo' => true, 'latitude' => 1.2, 'longitude' => 103.8]); }); -test('a rider saves, edits and deletes their own place', function () { +test('a customer saves, edits and deletes their own place', function () { $controller = fleetopsApiCustomerController(); - $controller->place = new FleetOpsRiderPlaceFake(); + $controller->place = new FleetOpsCustomerSavedPlaceFake(); $controller->place->setRawAttributes(['uuid' => 'place-uuid', 'owner_uuid' => $controller->currentCustomer->uuid], true); $saved = $controller->savePlace(Request::create('/', 'POST', ['name' => 'Home', 'latitude' => 1.28, 'longitude' => 103.85, 'street1' => '1 Raffles Place', 'owner_uuid' => 'someone-else'])); @@ -1567,34 +1574,34 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($down->requestPhoneChangeCode($request())->getStatusCode())->toBeGreaterThanOrEqual(400); }); -test('a rider dispatches their own order only when it can go out', function () { - $ready = fleetopsRiderController(); +test('a customer dispatches their own order only when it can go out', function () { + $ready = fleetopsCustomerOrderController(); $ready->dispatchOrder('order_1'); expect($ready->order->calls)->toBe(['dispatch', 'activity']) - ->and(fleetopsRiderController([], ['dispatched' => true])->dispatchOrder('order_1')->getStatusCode())->toBe(422) - ->and(fleetopsRiderController(['status' => 'started'])->dispatchOrder('order_1')->getStatusCode())->toBe(422) - ->and(fleetopsRiderController([], ['adhoc' => false])->dispatchOrder('order_1')->getStatusCode())->toBe(422); + ->and(fleetopsCustomerOrderController([], ['dispatched' => true])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsCustomerOrderController(['status' => 'started'])->dispatchOrder('order_1')->getStatusCode())->toBe(422) + ->and(fleetopsCustomerOrderController([], ['adhoc' => false])->dispatchOrder('order_1')->getStatusCode())->toBe(422); }); -test('a rider cancels their own order, with or without a reason', function () { - $plain = fleetopsRiderController(); +test('a customer cancels their own order, with or without a reason', function () { + $plain = fleetopsCustomerOrderController(); $plain->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' '])); - $reason = fleetopsRiderController(); + $reason = fleetopsCustomerOrderController(); $reason->cancelOrder('order_1', Request::create('/', 'POST', ['reason' => ' Changed my mind '])); expect($plain->order->calls)->toBe(['cancel']) ->and($reason->order->calls)->toBe([['reason', 'Changed my mind']]); }); -test('a rider sees the driver and car but no contact details', function () { +test('a customer sees the driver and vehicle but no contact details', function () { $driver = (object) ['name' => 'Dee Driver', 'photo_url' => 'photo', 'location' => 'here', 'phone' => '+15550009999', 'email' => 'd@example.test', 'vehicle' => null]; $vehicle = (object) ['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']; - $none = fleetopsApiCustomerJson(fleetopsRiderController()->orderDriver('order_1')); - $noCar = fleetopsApiCustomerJson(fleetopsRiderController([], ['driverAssigned' => $driver])->orderDriver('order_1')); - $withCar = fleetopsApiCustomerJson(fleetopsRiderController([], ['driverAssigned' => $driver, 'vehicleAssigned' => $vehicle])->orderDriver('order_1')); + $none = fleetopsApiCustomerJson(fleetopsCustomerOrderController()->orderDriver('order_1')); + $noCar = fleetopsApiCustomerJson(fleetopsCustomerOrderController([], ['driverAssigned' => $driver])->orderDriver('order_1')); + $withCar = fleetopsApiCustomerJson(fleetopsCustomerOrderController([], ['driverAssigned' => $driver, 'vehicleAssigned' => $vehicle])->orderDriver('order_1')); expect($none)->toBe(['driver' => null, 'vehicle' => null]) ->and($noCar['vehicle'])->toBeNull() @@ -1602,11 +1609,11 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($withCar['vehicle'])->toBe(['make' => 'Toyota', 'model' => 'Prius', 'color' => 'Blue', 'plate_number' => 'SGX1']); }); -test('rider tracking answers, and says so when tracking is down', function () { - $working = fleetopsRiderController(); - $working->order->trackerFake = new FleetOpsRiderTrackerFake(); - $broken = fleetopsRiderController(); - $broken->order->trackerFake = new FleetOpsRiderTrackerFake(true); +test('customer tracking answers, and says so when tracking is down', function () { + $working = fleetopsCustomerOrderController(); + $working->order->trackerFake = new FleetOpsCustomerTrackerFake(); + $broken = fleetopsCustomerOrderController(); + $broken->order->trackerFake = new FleetOpsCustomerTrackerFake(true); $request = Request::create('/', 'GET'); expect(fleetopsApiCustomerJson($working->orderTracker('order_1', $request)))->toBe(['answer' => 'tracker']) @@ -1615,27 +1622,30 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($broken->orderEta('order_1', $request)->getStatusCode())->toBe(503); }); -test('an order that does not exist is not found for a rider', function () { +test('an order that does not exist is not found for a customer', function () { $controller = fleetopsApiCustomerController(); $controller->findOrderFails = true; expect($controller->orderDriver('order_missing')->getStatusCode())->toBe(404); }); -test('a ride needs a fare, is adhoc, and its vehicle type comes from the fare, not the rider', function () { - $ride = new OrderConfig(['key' => 'ride', 'customer_orders_adhoc' => true, 'match_vehicle_type' => true]); - $ride->uuid = 'config-ride'; - $noFare = fleetopsApiCustomerController(); - $noFare->orderConfig = $ride; - $noFare->serviceQuote = null; - $booked = fleetopsApiCustomerController(); - $booked->orderConfig = $ride; - $rate = new Fleetbase\FleetOps\Models\ServiceRate(); +test('a config matching drivers by vehicle type needs a quote, makes customer orders adhoc, and takes the vehicle type from the quote', function () { + $onDemand = new OrderConfig(['key' => 'on-demand', 'policies' => [ + 'dispatch' => ['adhoc' => ['customer_orders' => true], 'matching' => ['vehicle_type' => true]], + 'customer' => ['ordering' => ['payment_methods' => ['cash', 'card'], 'require_settlement' => ['card']]], + ]]); + $onDemand->uuid = 'config-on-demand'; + $noQuote = fleetopsApiCustomerController(); + $noQuote->orderConfig = $onDemand; + $noQuote->serviceQuote = null; + $booked = fleetopsApiCustomerController(); + $booked->orderConfig = $onDemand; + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); $rate->setRawAttributes(['service_type' => 'economy', 'service_name' => 'Economy'], true); $booked->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); $booked->serviceQuote->setRelation('serviceRate', $rate); - $refused = $noFare->createOrder(new FleetOpsApiCustomerOrderRequest(['pickup' => ['name' => 'A']])); + $refused = $noQuote->createOrder(new FleetOpsApiCustomerOrderRequest(['pickup' => ['name' => 'A']])); $booked->createOrder(new FleetOpsApiCustomerOrderRequest([ 'service_quote' => 'quote_1', 'pickup' => ['name' => 'A'], @@ -1645,14 +1655,14 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps $byName = fleetopsApiCustomerController(); $byName->createOrder(new FleetOpsApiCustomerOrderRequest(['payload' => 'payload_public', 'payment_method' => 'card'])); - $owing = fleetopsApiCustomerController(); - $owing->orderConfig = $ride; - $owing->unpaidRide = true; + $owing = fleetopsApiCustomerController(); + $owing->orderConfig = $onDemand; + $owing->unsettledOrder = true; $owing->serviceQuote->setRawAttributes(['company_uuid' => 'company-uuid'], true); $blocked = $owing->createOrder(new FleetOpsApiCustomerOrderRequest(['service_quote' => 'quote_1'])); expect($refused->getStatusCode())->toBe(422) - ->and(fleetopsApiCustomerJson($refused))->toBe(['error' => 'Choose a ride option first.']) + ->and(fleetopsApiCustomerJson($refused))->toBe(['error' => 'Choose a service quote for this order first.']) ->and($blocked->getStatusCode())->toBe(402) ->and($owing->createdOrders)->toBe([]) ->and($booked->createdOrders[0]['adhoc'])->toBeTrue() @@ -1663,20 +1673,20 @@ function fleetopsRiderController(array $order = [], array $faked = []): FleetOps ->and($byName->paymentMethods)->toBe([]); }); -test('a ride that ended in a no-show can no longer be canceled', function () { - $controller = fleetopsRiderController(['status' => 'no_show'], ['config' => new OrderConfig(Fleetbase\FleetOps\Support\FleetOps::rideConfigDefaults())]); +test('an order that reached one of its config\'s terminal activities can no longer be canceled', function () { + $controller = fleetopsCustomerOrderController(['status' => 'no_show'], ['config' => new OrderConfig(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::attributes('passenger'))]); expect($controller->cancelOrder('order_1', Request::create('/', 'POST'))->getStatusCode())->toBe(422) ->and($controller->order->calls)->toBe([]); }); -test('a shared ride links to the public tracking page', function () { +test('a shared order links to the public tracking page', function () { config()->set('fleetbase.console.host', 'https://console.test'); $url = fleetopsApiCustomerWithEnvironment('production', function () { $method = new ReflectionMethod(CustomerController::class, 'trackingPageUrl'); - return $method->invoke(new CustomerController(), 'RIDE1', null); + return $method->invoke(new CustomerController(), 'TRK1', null); }); - expect($url)->toContain('track/RIDE1'); + expect($url)->toContain('track/TRK1'); }); diff --git a/server/tests/CompactResourceSerializationTest.php b/server/tests/CompactResourceSerializationTest.php index 6f0ab58d9..f20d6d7ad 100644 --- a/server/tests/CompactResourceSerializationTest.php +++ b/server/tests/CompactResourceSerializationTest.php @@ -2848,7 +2848,7 @@ public function environment(...$environments) ->and(array_key_exists('url', $withoutNumber))->toBeFalse(); }); -test('the rider order resource adds the fare, rating, payment and how dispatch ended', function () { +test('the order resource adds the driver rating, payment status and how adhoc dispatch ended when they apply', function () { $request = fleetopsCompactResourceRequest(false); $rating = fleetopsCompactResourceFixture(['stars' => 5, 'comment' => 'Kind']); $order = fleetopsCompactResourceFixture([ @@ -2859,26 +2859,32 @@ public function environment(...$environments) 'files' => collect(), 'purchaseRate' => null, 'driverRating' => $rating, - 'paid_at' => '2026-11-06 10:00:00', - 'type' => 'ride', + 'transaction' => fleetopsCompactResourceFixture(['settlement_status' => 'paid']), + 'adhoc' => true, + 'type' => 'transport', 'status' => 'completed', 'meta' => [], ], [ - 'fare' => ['final' => true, 'total' => 746], + 'driverRating' => $rating, + 'transaction' => true, 'dispatchOutcome' => null, ]); - $unrated = fleetopsCompactResourceFixture(array_merge($order->toArrayForTest(), ['driverRating' => null]), ['fare' => null, 'dispatchOutcome' => 'no_driver_found']); + $unrated = fleetopsCompactResourceFixture(array_merge($order->toArrayForTest(), ['driverRating' => null]), ['driverRating' => null, 'dispatchOutcome' => 'no_driver_found']); + $plain = fleetopsCompactResourceFixture(array_merge($order->toArrayForTest(), ['adhoc' => false]), ['dispatchOutcome' => null]); - $payload = (new Fleetbase\FleetOps\Http\Resources\v1\RiderOrder($order))->resolve($request); - $other = (new Fleetbase\FleetOps\Http\Resources\v1\RiderOrder($unrated))->resolve($request); + $payload = (new Fleetbase\FleetOps\Http\Resources\v1\Order($order))->resolve($request); + $other = (new Fleetbase\FleetOps\Http\Resources\v1\Order($unrated))->resolve($request); + $neither = (new Fleetbase\FleetOps\Http\Resources\v1\Order($plain))->resolve($request); expect($payload)->toMatchArray([ 'id' => 'fixture_public', - 'fare' => ['final' => true, 'total' => 746], - 'rating' => ['stars' => 5, 'comment' => 'Kind'], - 'payment_method' => 'card', - 'paid_at' => '2026-11-06 10:00:00', + 'driver_rating' => ['stars' => 5, 'comment' => 'Kind'], + 'payment_status' => 'paid', 'dispatch_outcome' => null, ]) - ->and($other)->toMatchArray(['fare' => null, 'rating' => null, 'dispatch_outcome' => 'no_driver_found']); + ->and($payload)->not->toHaveKeys(['fare', 'paid_at']) + ->and($other)->toMatchArray(['driver_rating' => null, 'dispatch_outcome' => 'no_driver_found']) + ->and($other)->not->toHaveKey('payment_status') + // Orders that weren't adhoc, and relations that weren't loaded, add nothing. + ->and($neither)->not->toHaveKeys(['dispatch_outcome', 'driver_rating', 'payment_status']); }); diff --git a/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php new file mode 100644 index 000000000..124eb4a7a --- /dev/null +++ b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php @@ -0,0 +1,1602 @@ +uuid, $reason]; + + return null; + } +} + +/** A point as MySQL stores it (SRID, then WKB), which the spatial models read back. */ +function adhocCfgWkb(float $longitude, float $latitude): string +{ + return pack('V', 0) . pack('C', 1) . pack('V', 1) . pack('e', $longitude) . pack('e', $latitude); +} + +/** [longitude, latitude] of a stored point or of WKT text. */ +function adhocCfgPoint(?string $value): array +{ + if ($value !== null && preg_match('/POINT\(\s*([-0-9.]+)\s+([-0-9.]+)\s*\)/i', $value, $m)) { + return [(float) $m[1], (float) $m[2]]; + } + if ($value === null || strlen($value) < 25) { + return [0.0, 0.0]; + } + $xy = unpack('ex/ey', substr($value, 9, 16)); + + return [$xy['x'], $xy['y']]; +} + +/** The policies the test config starts with: one driver at a time, 15 seconds per offer. */ +function adhocCfgBasePolicies(): array +{ + return ['dispatch' => ['adhoc' => ['strategy' => 'sequential', 'offer_timeout' => 15]]]; +} + +function adhocCfgBoot(): SQLiteConnection +{ + if (!Illuminate\Support\Str::hasMacro('humanize')) { + Illuminate\Support\Str::macro('humanize', fn ($value, $uppercase = true) => str_replace('_', ' ', Illuminate\Support\Str::snake((string) $value))); + } + + $pdo = new PDO('sqlite::memory:'); + $pdo->sqliteCreateFunction('ST_GeomFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_PointFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); + $pdo->sqliteCreateFunction('ST_X', fn ($wkt) => adhocCfgPoint($wkt)[0]); + $pdo->sqliteCreateFunction('ST_Y', fn ($wkt) => adhocCfgPoint($wkt)[1]); + $pdo->sqliteCreateFunction('st_distance_sphere', function ($a, $b) { + [$lng1, $lat1] = adhocCfgPoint($a); + [$lng2, $lat2] = adhocCfgPoint($b); + $rad = M_PI / 180; + $h = sin(($lat2 - $lat1) * $rad / 2) ** 2 + cos($lat1 * $rad) * cos($lat2 * $rad) * sin(($lng2 - $lng1) * $rad / 2) ** 2; + + return 2 * 6371000 * asin(sqrt($h)); + }); + $pdo->sqliteCreateFunction('LOWER', fn ($value) => $value === null ? null : strtolower((string) $value)); + + $connection = new SQLiteConnection($pdo); + $resolver = new ConnectionResolver(['default' => $connection, 'mysql' => $connection]); + $resolver->setDefaultConnection('mysql'); + EloquentModel::setConnectionResolver($resolver); + if (!EloquentModel::getEventDispatcher()) { + EloquentModel::setEventDispatcher(new Illuminate\Events\Dispatcher()); + } + app()->instance('db', new class($connection) { + public function __construct(public SQLiteConnection $c) + { + } + + public function connection($name = null): SQLiteConnection + { + return $this->c; + } + + public function __call($method, $arguments) + { + return $this->c->{$method}(...$arguments); + } + }); + Illuminate\Support\Facades\DB::clearResolvedInstance('db'); + app()->instance('responsecache', new class { + public function __call($method, $arguments) + { + return null; + } + }); + config()->set('activitylog.enabled', false); + config()->set('activitylog.default_auth_driver', 'web'); + app()->bind(Illuminate\Contracts\Config\Repository::class, fn () => config()); + Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); + + app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, new class { + public function send($notifiables, $notification) + { + if (AdhocCfgRecorder::$notified === ['throw']) { + throw new RuntimeException('push failed'); + } + AdhocCfgRecorder::$notified[] = [$notifiables->uuid, $notification::class]; + AdhocCfgRecorder::$sent[] = $notification; + } + + public function sendNow($notifiables, $notification, ?array $channels = null) + { + $this->send($notifiables, $notification); + } + }); + app()->instance('log', new class { + public array $warnings = []; + + public function warning($message, array $context = []) + { + $this->warnings[] = $message; + } + + public function __call($method, $arguments) + { + return null; + } + }); + Illuminate\Support\Facades\Log::clearResolvedInstance('log'); + + $schema = $connection->getSchemaBuilder(); + $tables = [ + 'companies' => ['uuid', 'public_id', 'name', 'options'], + 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'status', 'email', 'phone'], + 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid', 'meta', 'rating_average', 'rating_count'], + 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'type', 'plate_number', 'seating_capacity', 'vendor_uuid', 'photo_uuid', 'avatar_url', 'name', 'internal_id', 'location', 'online', 'speed', 'heading', 'altitude', 'year', 'make', 'model', 'class', 'color', 'call_sign', 'status', 'specs', 'vin_data', 'telematics', 'meta', 'slug', 'vin', 'trim', 'plate_number_type'], + 'orders' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'policies', 'triggers', 'version', 'core_service', 'status', 'type', 'tags'], + 'order_offers' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], + 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta', 'payment_method'], + 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'location', 'meta', 'owner_uuid', 'owner_type'], + 'waypoints' => ['uuid', 'payload_uuid', 'place_uuid', 'order'], + 'entities' => ['uuid', 'payload_uuid', 'name'], + 'tracking_statuses' => ['uuid', 'company_uuid', 'tracking_number_uuid', 'code', 'status'], + 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'status_uuid'], + 'contacts' => ['uuid', '_key', 'public_id', 'company_uuid', 'user_uuid', 'name', 'email', 'phone', 'type', 'photo_uuid', 'meta'], + 'chat_channels' => ['uuid', '_key', 'public_id', 'company_uuid', 'created_by_uuid', 'name', 'slug', 'meta'], + 'chat_participants' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'user_uuid', 'meta'], + 'chat_messages' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'sender_uuid', 'content', 'meta'], + 'chat_attachments' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'chat_message_uuid', 'sender_uuid', 'file_uuid'], + 'chat_logs' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'initiator_uuid', 'event_type', 'content', 'subjects', 'meta', 'status'], + 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name'], + 'files' => ['uuid', 'public_id', 'company_uuid', 'type', 'path', 'disk', 'bucket', 'original_filename', 'content_type', 'file_size', 'meta'], + 'chat_receipts' => ['uuid', 'public_id', 'company_uuid', 'chat_message_uuid', 'participant_uuid', 'read_at'], + 'positions' => ['uuid', '_key', 'public_id', 'company_uuid', 'order_uuid', 'subject_uuid', 'subject_type', 'coordinates', 'heading', 'speed'], + 'service_rates' => ['uuid', 'public_id', 'company_uuid', 'service_name', 'service_type', 'base_fee', 'per_meter_flat_rate_fee', 'per_meter_unit', 'rate_calculation_method', 'algorithm', 'currency', 'has_cod_fee', 'has_peak_hours_fee'], + 'driver_ratings' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'customer_uuid', 'customer_type', 'stars', 'comment'], + 'service_quotes' => ['uuid', '_key', 'distance', 'time', 'public_id', 'company_uuid', 'request_id', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at'], + 'service_quote_items' => ['uuid', '_key', 'public_id', 'service_quote_uuid', 'amount', 'currency', 'details', 'code'], + 'purchase_rates' => ['uuid', '_key', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'service_quote_uuid', 'transaction_uuid', 'payload_uuid', 'status', 'meta'], + 'transactions' => ['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'context_uuid', 'context_type', 'direction', 'type', 'status', 'settlement_status', 'amount', 'currency', 'meta'], + 'custom_fields' => ['uuid', 'public_id', 'company_uuid', 'category_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'for', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'meta', 'description', 'help_text', 'order'], + 'custom_field_values' => ['uuid', 'public_id', 'company_uuid', 'custom_field_uuid', 'subject_uuid', 'subject_type', 'value', 'value_type'], + ]; + foreach ($tables as $table => $columns) { + $schema->create($table, function ($blueprint) use ($columns) { + $blueprint->increments('id'); + foreach ($columns as $column) { + $blueprint->string($column)->nullable(); + } + $blueprint->timestamps(); + $blueprint->timestamp('deleted_at')->nullable(); + }); + } + + session(['company' => 'company-1']); + $connection->table('companies')->insert([['uuid' => 'company-1', 'public_id' => 'company_one', 'name' => 'Acme Cabs'], ['uuid' => 'company-2', 'public_id' => 'company_two', 'name' => 'Other Cabs']]); + $passenger = OrderConfigTemplates::attributes('passenger'); + $connection->table('order_configs')->insert([ + 'uuid' => 'config-adhoc', + 'public_id' => 'order_config_passenger', + 'company_uuid' => 'company-1', + 'name' => $passenger['name'], + 'key' => $passenger['key'], + 'namespace' => $passenger['namespace'], + 'flow' => json_encode($passenger['flow']), + 'meta' => json_encode($passenger['meta']), + 'policies' => json_encode(adhocCfgBasePolicies()), + 'triggers' => json_encode([]), + ]); + $connection->table('places')->insert(['uuid' => 'place-pickup', 'company_uuid' => 'company-1', 'name' => 'Raffles Place', 'location' => adhocCfgWkb(103.8511, 1.2841)]); + $connection->table('payloads')->insert(['uuid' => 'payload-1', 'company_uuid' => 'company-1', 'pickup_uuid' => 'place-pickup']); + $connection->table('vehicles')->insert([ + ['uuid' => 'car-economy', 'company_uuid' => 'company-1', 'type' => 'Economy'], + ['uuid' => 'car-xl', 'company_uuid' => 'company-1', 'type' => 'xl'], + ]); + + OrderConfigTriggers::$runImmediately = true; + AdhocCfgRecorder::$notified = []; + AdhocCfgRecorder::$sent = []; + Fleetbase\TestSupport\DispatchRecorder::$dispatched = []; + AdhocCfgOrder::$canceled = []; + AdhocCfgOrder::$pickupPoint = new Point(1.2841, 103.8511); + + return $connection; +} + +/** Store policies on the test config, over the ones it starts with. */ +function adhocCfgPolicies(SQLiteConnection $connection, array $policies): void +{ + $connection->table('order_configs')->where('uuid', 'config-adhoc')->update(['policies' => json_encode(array_replace_recursive(adhocCfgBasePolicies(), $policies))]); +} + +/** Store the test config's triggers. */ +function adhocCfgTriggers(SQLiteConnection $connection, array $triggers): void +{ + $connection->table('order_configs')->where('uuid', 'config-adhoc')->update(['triggers' => json_encode($triggers)]); +} + +/** Drivers around the pickup at Raffles Place, nearest first: Amara 545 m, Chen 1.2 km, Ben (XL) 210 m. */ +function adhocCfgSeedDrivers(SQLiteConnection $connection): void +{ + $connection->table('drivers')->insert([ + ['uuid' => 'amara', 'public_id' => 'driver_amara', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2890)], + ['uuid' => 'chen', 'public_id' => 'driver_chen', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2950)], + ['uuid' => 'ben', 'public_id' => 'driver_ben', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-xl', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2860)], + ['uuid' => 'far', 'public_id' => 'driver_far', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.9915, 1.3644)], + ['uuid' => 'offline', 'public_id' => 'driver_offline', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 0, 'location' => adhocCfgWkb(103.8511, 1.2845)], + ['uuid' => 'rival', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => adhocCfgWkb(103.8511, 1.2842)], + ]); +} + +function adhocCfgOrder(SQLiteConnection $connection, array $attributes = []): AdhocCfgOrder +{ + $connection->table('orders')->insert(array_merge([ + 'uuid' => 'order-1', + 'public_id' => 'order_one', + 'company_uuid' => 'company-1', + 'order_config_uuid' => 'config-adhoc', + 'payload_uuid' => 'payload-1', + 'status' => 'dispatched', + 'type' => 'passenger', + 'adhoc' => 1, + 'adhoc_distance' => 6000, + 'dispatched' => 1, + 'started' => 0, + 'required_vehicle_type' => 'economy', + ], $attributes)); + + return adhocCfgFresh($attributes['uuid'] ?? 'order-1'); +} + +function adhocCfgFresh(string $uuid = 'order-1'): AdhocCfgOrder +{ + return AdhocCfgOrder::where('uuid', $uuid)->first(); +} + +function adhocCfgDriver(string $uuid): Driver +{ + return Driver::withoutGlobalScopes()->where('uuid', $uuid)->first(); +} + +function adhocCfgStatuses(SQLiteConnection $connection): array +{ + return $connection->table('order_offers')->orderBy('id')->get(['driver_uuid', 'status'])->map(fn ($row) => [$row->driver_uuid, $row->status])->all(); +} + +function adhocCfgSequential(): SequentialStrategy +{ + return new SequentialStrategy(); +} + +test('drivers are matched by company and vehicle type, and busy drivers are left out only under the matching policy', function () { + $connection = adhocCfgBoot(); + $connection->table('users')->insert(['uuid' => 'user-moved', 'company_uuid' => 'company-1']); + $connection->table('orders')->insert([ + ['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => null], + ['uuid' => 'job-done', 'company_uuid' => 'company-1', 'status' => 'completed', 'deleted_at' => null], + ['uuid' => 'job-gone', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => now()], + ['uuid' => 'job-noshow', 'company_uuid' => 'company-1', 'status' => 'no_show', 'deleted_at' => null], + ]); + $connection->table('drivers')->insert([ + ['uuid' => 'free', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'via-user', 'company_uuid' => 'company-9', 'user_uuid' => 'user-moved', 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'other-company', 'company_uuid' => 'company-2', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], + ['uuid' => 'busy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-live'], + ['uuid' => 'finished', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-done'], + ['uuid' => 'stale', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-gone'], + ['uuid' => 'no-show', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-noshow'], + ['uuid' => 'big-car', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-xl', 'current_job_uuid' => null], + ]); + $match = fn (Order $order) => DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $order)->orderBy('id')->pluck('uuid')->all(); + + // An order without a config of its own has no matching policy: busy drivers aren't left out. + $unconfigured = new Order(); + $unconfigured->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' ECONOMY '], true); + $anyClass = new Order(); + $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' '], true); + + expect($match($unconfigured))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show']) + ->and($match($anyClass))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show', 'big-car']) + ->and(DriverMatching::vehicleClass($anyClass))->toBeNull() + ->and(DriverMatching::vehicleClass($unconfigured))->toBe('ECONOMY'); + + // The config's policy is off by default. + $configured = new Order(); + $configured->setRawAttributes(['company_uuid' => 'company-1', 'order_config_uuid' => 'config-adhoc', 'required_vehicle_type' => 'economy'], true); + expect($match($configured))->toBe(['free', 'via-user', 'busy', 'finished', 'stale', 'no-show']); + + // With it on, a driver on an unfinished order is left out. An order at one of the company + // configs' terminal activities (no_show here) doesn't keep its driver busy. + adhocCfgPolicies($connection, ['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]]); + $configured = new Order(); + $configured->setRawAttributes(['company_uuid' => 'company-1', 'order_config_uuid' => 'config-adhoc', 'required_vehicle_type' => 'economy'], true); + + expect($match($configured))->toBe(['free', 'via-user', 'finished', 'stale', 'no-show']) + ->and(DriverMatching::freeJobStatuses('company-1'))->toBe(['completed', 'canceled', 'no_show']) + ->and(DriverMatching::freeJobStatuses('company-2'))->toBe(['completed', 'canceled']) + ->and(DriverMatching::freeJobStatuses(null))->toBe(['completed', 'canceled']); +}); + +test('one at a time: the order goes to the nearest free driver of its type first', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + + Carbon::setTestNow('2026-11-06 09:00:00'); + adhocCfgSequential()->dispatch($order); + Carbon::setTestNow(); + $offer = OrderOffers::pending($order); + + expect(adhocCfgSequential()->name())->toBe('sequential') + ->and($offer->driver_uuid)->toBe('amara') + ->and($offer->distance)->toBeGreaterThan(500)->toBeLessThan(600) + ->and($offer->expires_at->toDateTimeString())->toBe('2026-11-06 09:00:15') + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class]]) + ->and(Fleetbase\TestSupport\DispatchRecorder::$dispatched)->toBe([['job' => ExpireOrderOffer::class, 'arguments' => [$offer->uuid]]]) + ->and($offer->order->uuid)->toBe('order-1') + ->and($offer->driver->uuid)->toBe('amara'); + + // Dispatching again keeps the open offer instead of offering it twice. + adhocCfgSequential()->dispatch($order); + expect(adhocCfgStatuses($connection))->toBe([['amara', 'pending']]); +}); + +test('one at a time: declining moves the order on, and only the offered driver may accept', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + + expect(adhocCfgSequential()->accept($order, adhocCfgDriver('chen')))->toBeFalse() + ->and(adhocCfgSequential()->decline($order, adhocCfgDriver('chen')))->toBeFalse() + ->and(adhocCfgSequential()->decline($order, adhocCfgDriver('amara')))->toBeTrue() + ->and(OrderOffers::pending($order)->driver_uuid)->toBe('chen') + ->and(adhocCfgSequential()->accept($order, adhocCfgDriver('amara')))->toBeFalse() + ->and(adhocCfgSequential()->accept($order, adhocCfgDriver('chen')))->toBeTrue() + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'accepted']]); +}); + +test('one at a time: an offer that ran out cannot be accepted and moves on once', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + $offer = OrderOffers::pending($order); + + expect(adhocCfgSequential()->expire($offer))->toBeFalse(); + + Carbon::setTestNow(now()->addSeconds(30)); + $acceptedLate = adhocCfgSequential()->accept($order, adhocCfgDriver('amara')); + $first = (new ExpireOrderOffer($offer->uuid))->handle(); + $again = (new ExpireOrderOffer($offer->uuid))->handle(); + $missing = (new ExpireOrderOffer('no-such-offer'))->handle(); + Carbon::setTestNow(); + + expect($acceptedLate)->toBeFalse() + ->and($first)->toBeTrue() + ->and($again)->toBeFalse() + ->and($missing)->toBeFalse() + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]); +}); + +test('one at a time: the scheduled check starts lost offers and moves stuck ones on', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + + expect(adhocCfgSequential()->redispatch($order))->toBe(1) + ->and(adhocCfgSequential()->redispatch($order))->toBe(0); + + Carbon::setTestNow(now()->addMinute()); + expect(adhocCfgSequential()->redispatch($order))->toBe(1); + Carbon::setTestNow(); + + $connection->table('order_offers')->update(['status' => 'declined']); + expect(adhocCfgSequential()->redispatch($order))->toBe(0) + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'declined']]); +}); + +test('one at a time: when nobody is left the order stays open by default, marked no driver found, and the exhausted triggers run', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgTriggers($connection, [ + ['event' => OrderConfigTriggers::DISPATCH_OFFER_EXHAUSTED, 'action' => 'set_meta', 'params' => ['key' => 'exhausted_seen', 'value' => 'yes']], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'set_meta', 'params' => ['key' => 'canceled_seen', 'value' => 'yes']], + ]); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + adhocCfgSequential()->decline($order, adhocCfgDriver('amara')); + adhocCfgSequential()->decline($order, adhocCfgDriver('chen')); + $open = adhocCfgFresh(); + + expect(AdhocCfgOrder::$canceled)->toBe([]) + ->and($open->status)->toBe('dispatched') + ->and($open->getMeta('dispatch_outcome'))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and($open->getMeta('exhausted_seen'))->toBe('yes') + ->and($open->getMeta('canceled_seen'))->toBeNull() + ->and(OrderOffers::outcome($open))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and($open->dispatchOutcome())->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::pending($open))->toBeNull(); + + // A later scheduled run that finds nobody again doesn't fire the triggers a second time. + $open->updateMeta('exhausted_seen', 'cleared'); + OrderOffers::exhausted($open); + expect(adhocCfgFresh()->getMeta('exhausted_seen'))->toBe('cleared'); + + // Once the operator assigns a driver it is no longer an order nobody took. + $connection->table('orders')->where('uuid', 'order-1')->update(['driver_assigned_uuid' => 'ben']); + expect(OrderOffers::outcome(adhocCfgFresh()))->toBeNull(); +}); + +test('one at a time: when nobody is left an order whose policy says cancel is canceled as no driver found', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgPolicies($connection, ['dispatch' => ['adhoc' => ['on_exhausted' => 'cancel']]]); + $order = adhocCfgOrder($connection); + adhocCfgSequential()->dispatch($order); + adhocCfgSequential()->decline($order, adhocCfgDriver('amara')); + adhocCfgSequential()->decline($order, adhocCfgDriver('chen')); + + // The cancel itself is recorded by the test order; mark it canceled as the real one would. + $connection->table('orders')->where('uuid', 'order-1')->update(['status' => 'canceled']); + + expect(AdhocCfgOrder::$canceled)->toBe([['order-1', OrderOffers::NO_DRIVER_FOUND]]) + ->and(OrderOffers::outcome(adhocCfgFresh()))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::pending($order))->toBeNull(); + + // Without the meta, a canceled order's offers tell: all declined or expired is no driver found, + // while one canceled with an offer still open (withdrawn) wasn't for want of a driver. + $declined = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'canceled']); + $withdrew = adhocCfgOrder($connection, ['uuid' => 'order-3', 'public_id' => 'order_three', 'status' => 'canceled']); + $connection->table('order_offers')->insert([ + ['uuid' => 'f-2a', 'order_uuid' => 'order-2', 'driver_uuid' => 'amara', 'status' => 'declined'], + ['uuid' => 'f-2b', 'order_uuid' => 'order-2', 'driver_uuid' => 'chen', 'status' => 'expired'], + ['uuid' => 'f-3a', 'order_uuid' => 'order-3', 'driver_uuid' => 'amara', 'status' => 'declined'], + ['uuid' => 'f-3b', 'order_uuid' => 'order-3', 'driver_uuid' => 'chen', 'status' => 'withdrawn'], + ]); + $notAdhoc = new Order(); + $notAdhoc->setRawAttributes(['uuid' => 'order-2', 'status' => 'canceled', 'adhoc' => 0], true); + $live = adhocCfgOrder($connection, ['uuid' => 'order-4', 'public_id' => 'order_four']); + + expect(OrderOffers::outcome($declined))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(OrderOffers::outcome($withdrew))->toBeNull() + ->and(OrderOffers::outcome($notAdhoc))->toBeNull() + ->and(OrderOffers::outcome($live))->toBeNull(); +}); + +test('one at a time: an order without a usable pickup finds no driver and stays open by default', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + AdhocCfgOrder::$pickupPoint = null; + + adhocCfgSequential()->dispatch(adhocCfgOrder($connection)); + + expect(AdhocCfgOrder::$canceled)->toBe([]) + ->and(adhocCfgFresh()->getMeta('dispatch_outcome'))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) + ->and(adhocCfgStatuses($connection))->toBe([]); + + adhocCfgPolicies($connection, ['dispatch' => ['adhoc' => ['on_exhausted' => 'cancel']]]); + adhocCfgSequential()->dispatch(adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two'])); + expect(AdhocCfgOrder::$canceled)->toBe([['order-2', OrderOffers::NO_DRIVER_FOUND]]); +}); + +test('one at a time: started, assigned or finished orders are not offered again', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + + $started = adhocCfgOrder($connection, ['uuid' => 'o-started', 'started' => 1]); + $assigned = adhocCfgOrder($connection, ['uuid' => 'o-assigned', 'driver_assigned_uuid' => 'amara']); + $canceled = adhocCfgOrder($connection, ['uuid' => 'o-canceled', 'status' => 'canceled']); + + expect(adhocCfgSequential()->offerNext($started))->toBeNull() + ->and(adhocCfgSequential()->offerNext($assigned))->toBeNull() + ->and(adhocCfgSequential()->offerNext($canceled))->toBeNull() + ->and(adhocCfgStatuses($connection))->toBe([]) + ->and(AdhocCfgOrder::$canceled)->toBe([]); +}); + +test('one at a time: a failed push still leaves the offer open', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + AdhocCfgRecorder::$notified = ['throw']; + + adhocCfgSequential()->dispatch($order); + + expect(OrderOffers::pending($order)->driver_uuid)->toBe('amara') + ->and(app('log')->warnings)->toContain('Unable to send an order offer'); +}); + +test('at once: every nearby driver of the type is offered the order, and the first to accept gets it', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast']); + $broadcast = new BroadcastStrategy(); + + $broadcast->dispatch($order); + + expect($broadcast->name())->toBe('broadcast') + ->and(adhocCfgStatuses($connection))->toBe([['amara', 'pending'], ['chen', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class], ['chen', OrderPing::class]]) + ->and($broadcast->accept($order, adhocCfgDriver('ben')))->toBeTrue(); + + OrderOffers::claimed($order, adhocCfgDriver('chen')); + expect(adhocCfgStatuses($connection))->toBe([['amara', 'withdrawn'], ['chen', 'accepted']]); +}); + +test('at once: a driver who declines is not offered the order again', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast', 'required_vehicle_type' => null]); + $broadcast = new BroadcastStrategy(); + $broadcast->dispatch($order); + + // Ben declines his offer; Far, never offered, declines from the list of nearby orders. + expect($broadcast->decline($order, adhocCfgDriver('ben')))->toBeTrue() + ->and($broadcast->decline($order, adhocCfgDriver('far')))->toBeTrue() + ->and($broadcast->decline($order, adhocCfgDriver('far')))->toBeTrue(); + + Carbon::setTestNow('2026-11-06 10:00:00'); + $offered = $broadcast->redispatch($order); + Carbon::setTestNow(); + + expect($offered)->toBe(2) + ->and(OrderOffers::declinedDrivers($order))->toBe(['ben', 'far']) + ->and($connection->table('order_offers')->where('status', 'pending')->orderBy('id')->pluck('driver_uuid')->all())->toBe(['amara', 'chen']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); +}); + +test('at once: no pickup means nobody to offer, and a failed push skips only that driver', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $broadcast = new BroadcastStrategy(); + + AdhocCfgOrder::$pickupPoint = null; + expect($broadcast->redispatch(adhocCfgOrder($connection, ['uuid' => 'o-nowhere'])))->toBe(0); + + AdhocCfgOrder::$pickupPoint = new Point(1.2841, 103.8511); + AdhocCfgRecorder::$notified = ['throw']; + expect($broadcast->redispatch(adhocCfgOrder($connection)))->toBe(2); +}); + +test('which strategy an order uses: its own, its config\'s adhoc policy, its company\'s, then one at a time', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast']); + $fromConfig = adhocCfgOrder($connection, ['uuid' => 'o-config']); + $configName = AdhocDispatch::nameFor($fromConfig); + $configWait = AdhocDispatch::offerTimeout($fromConfig); + // Written straight to the table, past the model's normalizing, as an old or hand-edited row could be. + $connection->table('order_configs')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'nonsense', 'offer_timeout' => null]]])]); + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 500]])]); + $fromCompany = adhocCfgFresh('o-config')->load('company'); + $connection->table('companies')->update(['options' => null]); + $fallback = adhocCfgFresh('o-config'); + // An order without a config of its own has no policies, so goes straight to the company's. + $unconfigured = adhocCfgOrder($connection, ['uuid' => 'o-none', 'order_config_uuid' => null]); + + expect(AdhocDispatch::nameFor($order))->toBe('broadcast') + ->and(AdhocDispatch::for($order))->toBeInstanceOf(BroadcastStrategy::class) + ->and($configName)->toBe('sequential') + ->and($configWait)->toBe(15) + ->and(AdhocDispatch::nameFor($fromCompany))->toBe('broadcast') + ->and(AdhocDispatch::offerTimeout($fromCompany))->toBe(120) + ->and(AdhocDispatch::nameFor($fallback))->toBe(AdhocDispatch::DEFAULT) + ->and(AdhocDispatch::offerTimeout($fallback))->toBe(20) + ->and(AdhocDispatch::nameFor($unconfigured))->toBe(AdhocDispatch::DEFAULT) + ->and(AdhocDispatch::DEFAULT)->toBe('sequential'); + + $connection->table('order_configs')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['offer_timeout' => 2]]])]); + expect(AdhocDispatch::offerTimeout(adhocCfgFresh('o-config')))->toBe(10); +}); + +test('more strategies can be registered by name', function () { + $nearestOnly = new class extends SequentialStrategy { + public function name(): string + { + return 'nearest-only'; + } + }; + AdhocDispatch::register('nearest-only', $nearestOnly::class); + + expect(AdhocDispatch::names())->toContain('broadcast', 'sequential', 'nearest-only') + ->and(AdhocDispatch::has('nearest-only'))->toBeTrue() + ->and(AdhocDispatch::has(null))->toBeFalse() + ->and(fn () => AdhocDispatch::register('broken', stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('offers record each driver once, and a decline from a driver who was never offered the order', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + $amara = adhocCfgDriver('amara'); + + $first = OrderOffers::record($order, $amara); + $again = OrderOffers::record($order, $amara); + OrderOffers::recordDecline($order, adhocCfgDriver('ben')); + + expect($again->uuid)->toBe($first->uuid) + ->and($first->expires_at)->toBeNull() + ->and(OrderOffers::offeredDrivers($order))->toBe(['amara', 'ben']) + ->and(OrderOffers::acceptPending($order, $amara))->toBeTrue() + ->and(OrderOffers::withdraw($order))->toBe(0); +}); + +test('the passenger config is a strict flow with a no-show ending, offered one driver at a time', function () { + $attributes = OrderConfigTemplates::attributes('passenger'); + $config = new OrderConfig($attributes); + + expect($attributes['key'])->toBe('passenger') + ->and(array_keys($attributes['flow']))->toBe(['created', 'dispatched', 'started', 'arrived', 'in_progress', 'completed', 'no_show']) + ->and($config->policy('dispatch.adhoc.strategy'))->toBe('sequential') + ->and($config->policy('dispatch.adhoc.customer_orders'))->toBeTrue() + ->and($config->policy('dispatch.matching.vehicle_type'))->toBeTrue() + ->and($config->hasStrictTransitions())->toBeTrue() + ->and($config->canTransition('arrived', 'no_show'))->toBeTrue() + ->and($config->canTransition('arrived', 'completed'))->toBeFalse() + ->and($config->canTransition('in_progress', 'completed'))->toBeTrue() + ->and($config->isTerminalActivityCode('no_show'))->toBeTrue() + ->and($config->getStartedActivity()->get('status'))->toBe('Driver on the way'); +}); + +class AdhocCfgCreateCommand extends CreateOrderConfig +{ + public array $lines = []; + public array $tables = []; + public ?string $key = null; + public array $opts = []; + + public function option($key = null) + { + return $this->opts[$key] ?? null; + } + + public function argument($key = null) + { + return $this->key; + } + + public function info($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function error($string, $verbosity = null) + { + $this->lines[] = $string; + } + + public function table($headers, $rows, $tableStyle = 'default', array $columnStyles = []) + { + $this->tables[] = [$headers, $rows]; + } +} + +test('the create order config command lists templates and makes a company\'s config once, or a named one', function () { + $connection = adhocCfgBoot(); + $connection->table('order_configs')->delete(); + $run = function (?string $key, array $opts = []) { + $command = new AdhocCfgCreateCommand(); + $command->key = $key; + $command->opts = $opts; + + return [$command->handle(), $command]; + }; + + [$listed, $list] = $run('passenger', ['list' => true]); + [$bare, $bareList] = $run(null); + [$unknown, $nope] = $run('limousine', ['company' => 'company-1']); + [$noCompany, $none] = $run('passenger'); + [$missing, $missed] = $run('passenger', ['company' => 'company_missing']); + [$made, $madeCommand] = $run('passenger', ['company' => 'company_one']); + [$again, $againCmd] = $run('passenger', ['company' => 'company-1']); + [$named, $namedCmd] = $run('passenger', ['company' => 'company-1', 'name' => ' Airport Transfers ']); + [$transport, $plainly] = $run('transport', ['company' => 'company-1']); + + $system = $connection->table('order_configs')->where('namespace', 'system:order-config:passenger')->get(); + $airport = $connection->table('order_configs')->where('key', 'airport-transfers')->first(); + $fields = $connection->table('custom_fields')->orderBy('id')->get(); + $plain = $connection->table('order_configs')->where('key', 'transport')->value('uuid'); + + expect([$listed, $bare, $unknown, $noCompany, $missing, $made, $again, $named, $transport])->toBe([0, 0, 1, 1, 1, 0, 0, 0, 0]) + ->and($list->tables[0][0])->toBe(['Key', 'Name', 'Description']) + ->and(array_column($list->tables[0][1], 'key'))->toBe(['transport', 'passenger']) + ->and($bareList->tables)->toHaveCount(1) + ->and($nope->lines[0])->toBe('No order config template named limousine. Run with --list to see them.') + ->and($none->lines[0])->toBe('Give the company with --company.') + ->and($missed->lines[0])->toBe('No company found for company_missing.') + ->and($madeCommand->lines[0])->toStartWith('Created order config Passenger')->toEndWith('for Acme Cabs.') + ->and($againCmd->lines[0])->toStartWith('Found order config Passenger') + ->and($namedCmd->lines[0])->toStartWith('Created order config Airport Transfers') + ->and($system)->toHaveCount(1) + ->and($system[0]->key)->toBe('passenger') + ->and(json_decode($system[0]->policies, true)['dispatch']['adhoc']['strategy'])->toBe('sequential') + ->and(json_decode($system[0]->triggers, true))->toHaveCount(4) + ->and($airport->namespace)->toBe('acme-cabs:order-config:airport-transfers') + ->and((int) $airport->core_service)->toBe(0) + ->and(json_decode($airport->policies, true))->toBe(json_decode($system[0]->policies, true)) + // The passenger template's custom field is made with each new config, and only then. + ->and($fields->pluck('name')->all())->toBe(['passengers', 'passengers']) + ->and($fields->pluck('subject_uuid')->all())->toBe([$system[0]->uuid, $airport->uuid]) + ->and($fields->pluck('company_uuid')->unique()->all())->toBe(['company-1']) + ->and($plain)->not->toBeNull() + ->and($connection->table('custom_fields')->where('subject_uuid', $plain)->count())->toBe(0); +}); + +test('a dispatched adhoc order is offered by its strategy, and a busy driver is offered it while the matching policy is off', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgOrder($connection, ['tracking_number_uuid' => 'tn-1']); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); + + (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(adhocCfgFresh())); + + expect(adhocCfgStatuses($connection))->toBe([['amara', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['amara', OrderPing::class]]); +}); + +test('a dispatched adhoc order skips a busy driver when its config excludes busy drivers', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + adhocCfgPolicies($connection, ['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]]); + adhocCfgOrder($connection, ['tracking_number_uuid' => 'tn-1']); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); + $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); + + (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(adhocCfgFresh())); + + expect(adhocCfgStatuses($connection))->toBe([['chen', 'pending']]) + ->and(AdhocCfgRecorder::$notified)->toBe([['chen', OrderPing::class]]); +}); + +test('the scheduled adhoc command asks each order\'s strategy', function () { + $connection = adhocCfgBoot(); + $lookup = new ReflectionMethod(Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, 'strategyFor'); + $command = new Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders(); + + expect($lookup->invoke($command, adhocCfgOrder($connection, ['adhoc_strategy' => 'broadcast'])))->toBeInstanceOf(BroadcastStrategy::class) + ->and($lookup->invoke($command, adhocCfgOrder($connection, ['uuid' => 'o-2'])))->toBeInstanceOf(SequentialStrategy::class); +}); + +test('quotes carry each service type\'s seating capacity and how soon its nearest free driver could arrive', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $connection->table('vehicles')->where('uuid', 'car-economy')->update(['seating_capacity' => 4]); + $connection->table('vehicles')->insert(['uuid' => 'car-economy-2', 'company_uuid' => 'company-1', 'type' => 'economy', 'seating_capacity' => 5]); + + $controller = new class extends Fleetbase\FleetOps\Http\Controllers\Api\v1\ServiceQuoteController { + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + public function from(?Point $point): void + { + $this->availabilityFrom = $point; + } + }; + $quote = function (string $class) { + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['service_type' => $class], true); + $quote = new Fleetbase\FleetOps\Models\ServiceQuote(); + $quote->setRawAttributes(['company_uuid' => 'company-1'], true); + $quote->setRelation('serviceRate', $rate); + + return $quote; + }; + + $economy = $quote('economy'); + $limo = $quote('limo'); + $controller->from(new Point(1.2841, 103.8511)); + $controller->helper('serviceQuoteResourceCollection', [$economy, $limo]); + + $asked = Illuminate\Http\Request::create('/', 'GET', ['availability' => 1]); + $notAsked = Illuminate\Http\Request::create('/', 'GET'); + + expect($economy->availability)->toBe(['seating_capacity' => 5, 'pickup_eta' => 138]) + ->and($limo->availability)->toBe(['seating_capacity' => null, 'pickup_eta' => null]) + ->and($controller->helper('availabilityPoint', $asked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeInstanceOf(Point::class) + ->and($controller->helper('availabilityPoint', $asked, 'place_pickup'))->toBeNull() + ->and($controller->helper('availabilityPoint', $notAsked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeNull(); + + // Without a pickup, quotes are returned as they are. + $plain = $quote('economy'); + $controller->from(null); + $controller->helper('serviceQuoteResourceCollection', [$plain]); + expect($plain->availability)->toBeNull(); +}); + +/** A completed order by customer Sam with driver Chen, from Raffles Place to Bugis. */ +function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): AdhocCfgOrder +{ + adhocCfgSeedDrivers($connection); + $connection->table('users')->insert([ + ['uuid' => 'user-sam', 'public_id' => 'user_sam', 'company_uuid' => 'company-1', 'name' => 'Sam Lee', 'type' => 'customer', 'email' => 'sam@customer.test', 'phone' => '+15550190301'], + ['uuid' => 'user-chen', 'public_id' => 'user_chen', 'company_uuid' => 'company-1', 'name' => 'Chen Test', 'type' => 'driver', 'email' => 'chen@cabs.test', 'phone' => '+15550190203'], + ]); + $connection->table('drivers')->where('uuid', 'chen')->update(['user_uuid' => 'user-chen']); + $connection->table('contacts')->insert(['uuid' => 'contact-sam', 'public_id' => 'contact_sam', 'company_uuid' => 'company-1', 'user_uuid' => 'user-sam', 'name' => 'Sam Lee', 'email' => 'sam@customer.test', 'phone' => '+15550190301', 'type' => 'customer']); + $connection->table('places')->insert(['uuid' => 'place-dropoff', 'company_uuid' => 'company-1', 'name' => 'Bugis', 'location' => adhocCfgWkb(103.8452, 1.3005)]); + $connection->table('payloads')->where('uuid', 'payload-1')->update(['dropoff_uuid' => 'place-dropoff']); + $connection->table('service_rates')->insert(['uuid' => 'rate-economy', 'company_uuid' => 'company-1', 'service_name' => 'Economy', 'service_type' => 'economy', 'base_fee' => 300, 'rate_calculation_method' => 'algo', 'algorithm' => 'max(200, {distance_km} * 120 + {time_min} * 20)', 'currency' => 'USD']); + $connection->table('service_quotes')->insert(['uuid' => 'quote-booked', 'company_uuid' => 'company-1', 'service_rate_uuid' => 'rate-economy', 'amount' => 533, 'currency' => 'USD']); + $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'TRK1', 'owner_uuid' => 'order-1']); + $connection->table('purchase_rates')->insert(['uuid' => 'purchase-booked', 'company_uuid' => 'company-1', 'service_quote_uuid' => 'quote-booked', 'payload_uuid' => 'payload-1', 'status' => 'created']); + + return adhocCfgOrder($connection, array_merge([ + 'status' => 'completed', + 'started' => 1, + 'started_at' => '2026-11-06 09:00:00', + 'driver_assigned_uuid' => 'chen', + 'customer_uuid' => 'contact-sam', + 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', + 'purchase_rate_uuid' => 'purchase-booked', + 'tracking_number_uuid' => 'tn-1', + ], $order)); +} + +test('the order chat opens once a driver is assigned, with just the customer and driver in it, and closes', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + + expect(OrderChat::open($order))->toBeNull() + ->and(OrderChat::find($order))->toBeNull() + ->and(OrderChat::close($order))->toBeFalse(); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $order = adhocCfgFresh(); + $channel = OrderChat::open($order); + $again = OrderChat::open(adhocCfgFresh()); + + expect($channel->meta)->toBe(['order_public_id' => 'order_one', 'kind' => 'group']) + ->and($again->uuid)->toBe($channel->uuid) + ->and(OrderChat::find(adhocCfgFresh())->uuid)->toBe($channel->uuid) + ->and($connection->table('chat_channels')->count())->toBe(1) + ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('chat_channel_uuid'))->toBe($channel->uuid); + + $sent = OrderChat::send($channel, 'user-sam', 'By the lobby'); + $chen = $connection->table('chat_participants')->where('user_uuid', 'user-chen')->value('uuid'); + $connection->table('chat_messages')->insert(['uuid' => 'm-2', 'company_uuid' => 'company-1', 'chat_channel_uuid' => $channel->uuid, 'sender_uuid' => $chen, 'content' => 'Two minutes', 'created_at' => now()->addMinute()]); + + $messages = OrderChat::messages($channel, 'user-sam'); + expect($messages->map(fn ($message) => [$message['from'], $message['text']])->all())->toBe([['customer', 'By the lobby'], ['driver', 'Two minutes']]) + ->and($messages[0]['id'])->toBe($sent->public_id ?? $sent->uuid) + ->and(OrderChat::isClosed(adhocCfgFresh()))->toBeFalse(); + + // A finished order's chat is closed by its config's terminal activities, and closing it marks the channel. + $connection->table('orders')->update(['status' => 'no_show']); + expect(OrderChat::isClosed(adhocCfgFresh()))->toBeTrue(); + $connection->table('orders')->update(['status' => 'started']); + expect(OrderChat::close(adhocCfgFresh()))->toBeTrue() + ->and(OrderChat::isClosed(adhocCfgFresh()))->toBeTrue() + ->and(json_decode($connection->table('chat_channels')->value('meta'), true))->toHaveKey('closed_at'); +}); + +test('a customer rates their driver once, and the driver keeps an average', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + $connection->table('driver_ratings')->insert(['uuid' => 'r-old', 'order_uuid' => 'order-old', 'driver_uuid' => 'chen', 'stars' => 4]); + + $first = DriverRatings::rate($order, 9, ' Great '); + $second = DriverRatings::rate(adhocCfgFresh(), 1); + $driver = adhocCfgDriver('chen'); + $rating = Fleetbase\FleetOps\Models\DriverRating::where('order_uuid', 'order-1')->first(); + + expect($first)->toBeTrue() + ->and($second)->toBeFalse() + ->and([$rating->stars, $rating->comment, $rating->customer_uuid])->toBe([5, 'Great', 'contact-sam']) + ->and($rating->order->uuid)->toBe('order-1') + ->and($rating->driver->uuid)->toBe('chen') + ->and($order->driverRating->stars)->toBe(5) + ->and([$driver->rating_average, $driver->rating_count])->toBe([4.5, 2]); + + // A driver whose ratings were all removed has no average. + $connection->table('driver_ratings')->update(['deleted_at' => now()]); + DriverRatings::refresh('chen'); + expect([adhocCfgDriver('chen')->rating_average, adhocCfgDriver('chen')->rating_count])->toBe([null, 0]); +}); + +test('two ratings racing for one order keep the first', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + // The other request's rating lands between the check and the insert; the unique index refuses this one. + $connection->statement("CREATE TRIGGER rating_race BEFORE INSERT ON driver_ratings BEGIN SELECT RAISE(ABORT, 'UNIQUE constraint failed: driver_ratings.order_uuid'); END"); + + expect(DriverRatings::rate($order, 5))->toBeFalse() + ->and(adhocCfgDriver('chen')->rating_count)->toBeNull(); +}); + +test('a share link opens only its customer\'s view of its order, until it expires', function () { + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-1', 'company_uuid' => 'company-1'], true); + $sam = new Fleetbase\FleetOps\Models\Contact(); + $sam->setRawAttributes(['uuid' => 'contact-sam'], true); + $other = new Fleetbase\FleetOps\Models\Contact(); + $other->setRawAttributes(['uuid' => 'contact-other'], true); + + $scope = Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $sam); + $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam'); + $expired = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam', Carbon::now()->subMinute()); + $valid = fn ($token, $scope) => Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::valid($token, $scope); + + expect($valid($token, $scope))->toBeTrue() + ->and($valid($token, Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $other)))->toBeFalse() + ->and($valid($expired, $scope))->toBeFalse() + ->and($valid(substr($token, 0, -1) . (str_ends_with($token, '0') ? '1' : '0'), $scope))->toBeFalse() + ->and($valid('not-a-token', $scope))->toBeFalse() + ->and($valid(['array'], $scope))->toBeFalse() + ->and($valid($token, null))->toBeFalse(); +}); + +test('an order update push carries its title, message and type to the device channels', function () { + $order = new Order(); + $order->setRawAttributes(['public_id' => 'order_one'], true); + + $update = new OrderUpdate($order, 'Your driver has arrived', 'Chen is waiting.', 'order_arrived'); + $default = new OrderUpdate($order, 'Title', 'Message'); + + expect([$update->title, $update->message])->toBe(['Your driver has arrived', 'Chen is waiting.']) + ->and($update->data)->toBe(['id' => 'order_one', 'type' => 'order_arrived']) + ->and($default->data)->toBe(['id' => 'order_one', 'type' => 'order_update']) + ->and($update->via(null))->toBe([NotificationChannels\Fcm\FcmChannel::class, NotificationChannels\Apn\ApnChannel::class]); +}); + +test('the notify actions push to the order\'s customer and driver, with placeholders filled in', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'arrived']); + $context = ['event' => 'order.activity', 'activity' => ['code' => 'arrived', 'status' => 'Driver has arrived', 'details' => 'The driver is waiting at the pickup.']]; + + (new NotifyCustomer())->handle($order, ['title' => '{driver.first_name} is here', 'message' => 'Order {order.id} ({order.tracking_number}) for {customer.name}: {order.status}. {nope}'], $context); + (new NotifyCustomer())->handle($order, [], $context); + (new NotifyCustomer())->handle($order, [], ['event' => 'order.completed']); + (new NotifyDriver())->handle($order, ['title' => 'Customer {customer.name} is waiting'], ['event' => OrderConfigTriggers::DRIVER_APPROACHING]); + + $orphan = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'customer_uuid' => null, 'driver_assigned_uuid' => null]); + (new NotifyCustomer())->handle($orphan, ['title' => 'Nobody hears this'], $context); + (new NotifyDriver())->handle($orphan, ['title' => 'Nobody hears this'], $context); + + $sent = AdhocCfgRecorder::$sent; + expect(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class], ['contact-sam', OrderUpdate::class], ['chen', OrderUpdate::class]]) + ->and([$sent[0]->title, $sent[0]->message, $sent[0]->data['type']])->toBe(['Chen is here', 'Order order_one (TRK1) for Sam Lee: arrived.', 'order_arrived']) + // Without a title or message of its own, the activity's status and details are used. + ->and([$sent[1]->title, $sent[1]->message])->toBe(['Driver has arrived', 'The driver is waiting at the pickup.']) + ->and([$sent[2]->title, $sent[2]->message, $sent[2]->data['type']])->toBe(['Customer Sam Lee is waiting', '', 'order_driver_approaching']) + ->and(NotifyCustomer::eventType([]))->toBe('order_update'); +}); + +test('reaching an activity runs its actions, and completing or canceling an order fires the config\'s triggers', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgTriggers($connection, $passenger['triggers']); + $order = adhocCfgSeedOrder($connection, ['status' => 'started']); + $observer = new Fleetbase\FleetOps\Observers\OrderObserver(); + + $order->status = 'arrived'; + $order->save(); + $observer->updated($order); + + expect(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message, AdhocCfgRecorder::$sent[0]->data['type']])->toBe(['Your driver has arrived', 'Chen is waiting at the pickup point.', 'order_arrived']); + + // Nothing runs when the status didn't change. + $observer->updated(adhocCfgFresh()); + expect(AdhocCfgRecorder::$notified)->toHaveCount(1); + + // Canceling fires order.canceled: the customer is told, unless nobody was found for the order. + $order->status = 'canceled'; + $order->save(); + $observer->updated($order); + expect(AdhocCfgRecorder::$sent)->toHaveCount(2) + ->and(AdhocCfgRecorder::$sent[1]->title)->toBe('Your trip was canceled') + ->and(AdhocCfgRecorder::$sent[1]->data['type'])->toBe('order_order_canceled'); + + $quiet = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'dispatched', 'customer_uuid' => 'contact-sam', 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', 'meta' => json_encode(['dispatch_outcome' => 'no_driver_found'])]); + $quiet->status = 'canceled'; + $quiet->save(); + $observer->updated($quiet); + expect(AdhocCfgRecorder::$sent)->toHaveCount(2); + + // An order without a config of its own runs no triggers. + $plain = adhocCfgOrder($connection, ['uuid' => 'order-3', 'public_id' => 'order_three', 'status' => 'started', 'order_config_uuid' => null, 'customer_uuid' => 'contact-sam', 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact']); + $plain->status = 'arrived'; + $plain->save(); + $observer->updated($plain); + + // A push that fails is logged and doesn't break the update. + AdhocCfgRecorder::$notified = ['throw']; + $connection->table('orders')->where('uuid', 'order-1')->update(['status' => 'arrived']); + $order = adhocCfgFresh(); + $order->status = 'in_progress'; + $order->save(); + $observer->updated($order); + + expect(AdhocCfgRecorder::$sent)->toHaveCount(2) + ->and(app('log')->warnings)->toContain('An order config action failed'); +}); + +test('the customer is told once when the driver is about to reach the pickup, and only while the trigger\'s conditions pass', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgTriggers($connection, [ + ...$passenger['triggers'], + ['event' => OrderConfigTriggers::DRIVER_APPROACHING, 'options' => ['target' => 'dropoff', 'distance' => 300], 'action' => 'set_meta', 'params' => ['key' => 'near_dropoff', 'value' => 'yes']], + ]); + adhocCfgSeedOrder($connection, ['status' => 'arrived', 'driver_assigned_uuid' => 'ben']); + $connection->table('drivers')->where('uuid', 'far')->update(['location' => adhocCfgWkb(103.8452, 1.3010)]); + $connection->table('users')->insert(['uuid' => 'user-ben', 'company_uuid' => 'company-1', 'name' => 'Ben Tan', 'type' => 'driver']); + $connection->table('drivers')->where('uuid', 'ben')->update(['user_uuid' => 'user-ben']); + $near = adhocCfgDriver('ben'); + $far = adhocCfgDriver('chen'); + $nowhere = new Driver(); + + // Arrived already: the pickup trigger's `when` (status is started) doesn't pass, and isn't used up. + $arrived = adhocCfgFresh(); + expect(OrderConfigTriggers::driverMoved($near, null))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($near, $arrived))->toBe(0); + + $connection->table('orders')->update(['status' => 'started']); + $started = adhocCfgFresh(); + expect(OrderConfigTriggers::driverMoved($far, $started))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($nowhere, $started))->toBe(0) + ->and(OrderConfigTriggers::driverMoved($near, $started))->toBe(1) + ->and(OrderConfigTriggers::driverMoved($near, adhocCfgFresh()))->toBe(0) + ->and(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message, AdhocCfgRecorder::$sent[0]->data['type']])->toBe(['Your driver is almost there', 'Ben is about a minute away.', 'order_driver_approaching']); + + // Each target is its own once: coming close to the drop-off fires that trigger, once. + $atDropoff = adhocCfgDriver('far'); + expect(OrderConfigTriggers::driverMoved($atDropoff, adhocCfgFresh()))->toBe(1) + ->and(OrderConfigTriggers::driverMoved($atDropoff, adhocCfgFresh()))->toBe(0) + ->and(adhocCfgFresh()->getMeta('near_dropoff'))->toBe('yes'); + + // An order without a config of its own has no triggers. + $plain = adhocCfgOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_two', 'status' => 'started', 'order_config_uuid' => null]); + expect(OrderConfigTriggers::driverMoved($near, $plain))->toBe(0); +}); + +test('the queued action job reads the order again and runs a registered action', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgOrder($connection); + + $ran = (new RunOrderConfigAction($order, 'set_meta', ['key' => 'flag', 'value' => 'on']))->handle(); + $unknown = (new RunOrderConfigAction($order, 'send_invoice'))->handle(); + $connection->table('orders')->delete(); + $gone = (new RunOrderConfigAction($order, 'set_meta', ['key' => 'flag', 'value' => 'off']))->handle(); + + expect($ran)->toBeTrue() + ->and($unknown)->toBeFalse() + ->and($gone)->toBeFalse() + ->and((new RunOrderConfigAction($order, 'set_meta'))->orderUuid)->toBe('order-1'); +}); + +/** Positions the driver reported: one before metering began, then 1.0 km and 1.05 km. */ +function adhocCfgSeedPositions(SQLiteConnection $connection): void +{ + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); + $connection->table('positions')->insert([ + ['uuid' => 'p0', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2700), 'created_at' => '2026-11-06 09:04:00'], + ['uuid' => 'p1', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2841), 'created_at' => '2026-11-06 09:05:10'], + ['uuid' => 'p2', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8511, 1.2931), 'created_at' => '2026-11-06 09:09:00'], + ['uuid' => 'p3', 'order_uuid' => 'order-1', 'coordinates' => adhocCfgWkb(103.8452, 1.3005), 'created_at' => '2026-11-06 09:14:00'], + ]); +} + +test('a completed order is priced again from the distance its driver covered and the time since metering began', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress']]); + $order = adhocCfgSeedOrder($connection); + adhocCfgSeedPositions($connection); + + Carbon::setTestNow('2026-11-06 09:15:00'); + $quote = OrderRepricing::settle($order); + Carbon::setTestNow(); + + $purchaseUuid = $connection->table('orders')->where('uuid', 'order-1')->value('purchase_rate_uuid'); + $purchase = Fleetbase\FleetOps\Models\PurchaseRate::where('uuid', $purchaseUuid)->first(); + $repriced = data_get($purchase->meta, 'repriced'); + + // About 1.0 km plus 1.05 km over 10 minutes: base 300, then 2.05 × 120 + 10 × 20 = 746 cents. + expect($quote)->toBeInstanceOf(Fleetbase\FleetOps\Models\ServiceQuote::class) + ->and((int) $quote->amount)->toBeGreaterThan(740)->toBeLessThan(750) + ->and((int) $quote->distance)->toBeGreaterThan(2000)->toBeLessThan(2100) + ->and((int) $quote->time)->toBe(600) + ->and($quote->service_rate_uuid)->toBe('rate-economy') + ->and($purchaseUuid)->not->toBe('purchase-booked') + ->and($purchase->service_quote_uuid)->toBe($quote->uuid) + ->and($repriced['distance'])->toBe((int) $quote->distance) + ->and($repriced['time'])->toBe(600) + ->and($repriced['distance_source'])->toBe('positions') + ->and(Carbon::parse($repriced['metered_from'])->toDateTimeString())->toBe('2026-11-06 09:05:00') + ->and($repriced['previous_amount'])->toEqual(533) + ->and($connection->table('service_quote_items')->orderBy('id')->pluck('details')->all())->toBe(['Base', 'Distance and time']); + + // Priced once. + expect(OrderRepricing::settle(adhocCfgFresh()))->toBeNull(); +}); + +test('repricing waits for the pricing policy, a completed order with a rate, and a config of its own', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + + // The policy is off by default. + expect(OrderRepricing::settle($order))->toBeNull() + ->and($connection->table('service_quotes')->count())->toBe(1); + + adhocCfgPolicies($connection, ['pricing' => ['reprice_on_completion' => true]]); + expect(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-live', 'status' => 'started', 'purchase_rate_uuid' => 'purchase-booked'])))->toBeNull() + ->and(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-unpriced', 'status' => 'completed', 'purchase_rate_uuid' => null])))->toBeNull() + ->and(OrderRepricing::settle(adhocCfgOrder($connection, ['uuid' => 'o-plain', 'status' => 'completed', 'order_config_uuid' => null, 'purchase_rate_uuid' => 'purchase-booked'])))->toBeNull() + ->and($connection->table('service_quotes')->count())->toBe(1); +}); + +test('without positions the distance is the straight line, and metering starts at the activity, else when the order started', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection); + $order->started_at = null; + + [$metres, $source] = OrderRepricing::distance($order, Carbon::parse('2026-11-06 09:00:00')); + $connection->table('payloads')->update(['dropoff_uuid' => null]); + [$none, $nothing] = OrderRepricing::distance(adhocCfgFresh(), Carbon::now()); + + $fromStart = OrderRepricing::meteringStartedAt(adhocCfgFresh(), 'in_progress'); + $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); + $fromActivity = OrderRepricing::meteringStartedAt(adhocCfgFresh(), 'in_progress'); + $noActivity = OrderRepricing::meteringStartedAt(adhocCfgFresh()); + + $label = new ReflectionMethod(OrderRepricing::class, 'label'); + $rate = new Fleetbase\FleetOps\Models\ServiceRate(); + $rate->setRawAttributes(['rate_calculation_method' => 'per_meter'], true); + $other = new Fleetbase\FleetOps\Models\ServiceRate(); + $other->setRawAttributes(['rate_calculation_method' => 'fixed_meter'], true); + + expect($source)->toBe('straight_line') + ->and($metres)->toBeGreaterThan(1900)->toBeLessThan(2000) + ->and([$none, $nothing])->toBe([0, 'none']) + ->and($fromStart->toDateTimeString())->toBe('2026-11-06 09:00:00') + ->and($fromActivity->toDateTimeString())->toBe('2026-11-06 09:05:00') + ->and($noActivity->toDateTimeString())->toBe('2026-11-06 09:00:00') + ->and([$label->invoke(null, $rate, 'Base Fee', 0), $label->invoke(null, $rate, 'Service Fee', 1), $label->invoke(null, $other, 'Peak', 2), $label->invoke(null, $other, '', 3)])->toBe(['Base', 'Distance', 'Peak', 'Charge']); +}); + +test('completing an order through the observer prices it again before its completed actions run', function () { + $connection = adhocCfgBoot(); + $passenger = OrderConfigTemplates::attributes('passenger'); + adhocCfgPolicies($connection, $passenger['policies']); + $order = adhocCfgSeedOrder($connection, ['status' => 'in_progress']); + + $order->status = 'completed'; + $order->save(); + (new Fleetbase\FleetOps\Observers\OrderObserver())->updated($order); + + $purchase = Fleetbase\FleetOps\Models\PurchaseRate::where('uuid', $connection->table('orders')->value('purchase_rate_uuid'))->first(); + + expect($purchase->uuid)->not->toBe('purchase-booked') + ->and(data_get($purchase->meta, 'repriced.distance_source'))->toBe('straight_line') + ->and(AdhocCfgRecorder::$notified)->toBe([['contact-sam', OrderUpdate::class]]) + ->and(AdhocCfgRecorder::$sent[0]->title)->toBe('You have arrived'); +}); + +class AdhocCfgCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController +{ + public ?string $customerUuid = 'contact-sam'; + public array $revoked = []; + public array $settings = []; + + protected function currentCustomer(): ?Fleetbase\FleetOps\Models\Contact + { + return $this->customerUuid ? Fleetbase\FleetOps\Models\Contact::where('uuid', $this->customerUuid)->first() : null; + } + + protected function findOrderOrFail(string $id): Order + { + return AdhocCfgOrder::where('public_id', $id)->firstOrFail(); + } + + protected function deleteUserTokens(Fleetbase\Models\User $user): void + { + $this->revoked[] = $user->uuid; + } + + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } + + protected function trackingPageUrl(string $number, ?string $companyUuid): string + { + return 'https://console.test/~/track/' . $number . ($companyUuid === 'company-1' ? '' : '?org=other'); + } + + protected function lookupCompanySetting(string $key, mixed $default = null): mixed + { + return $this->settings[$key] ?? $default; + } + + protected function resolveOrderConfig(Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest $request, string $companyUuid): ?OrderConfig + { + return OrderConfig::where('uuid', 'config-adhoc')->first(); + } + + protected function resolveServiceQuote(Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest $request): mixed + { + return Fleetbase\FleetOps\Models\ServiceQuote::where('uuid', 'quote-booked')->first(); + } +} + +function adhocCfgJson($response): array +{ + return $response->getData(true); +} + +test('chat, rating and sharing are refused with 403 while the config\'s customer interactions are off', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $controller = new AdhocCfgCustomerController(); + $post = fn (array $input) => Illuminate\Http\Request::create('/', 'POST', $input); + + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(403) + ->and($controller->sendOrderMessage('order_one', $post(['text' => 'Hi']))->getStatusCode())->toBe(403) + ->and($controller->rateOrder('order_one', $post(['stars' => 5]))->getStatusCode())->toBe(403) + ->and($controller->shareOrder('order_one')->getStatusCode())->toBe(403) + ->and(adhocCfgJson($controller->shareOrder('order_one'))['error'])->toBe('Sharing tracking is not available for this order.') + // Someone else's order, or none, is not found before the policy is read. + ->and($controller->orderMessages('order_missing')->getStatusCode())->toBe(404); + + $controller->customerUuid = null; + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(404); + + // Each interaction is its own setting. + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['rating' => true]]]); + $controller = new AdhocCfgCustomerController(); + expect($controller->orderMessages('order_one')->getStatusCode())->toBe(403) + ->and($controller->rateOrder('order_one', $post(['stars' => 5]))->getStatusCode())->toBe(422); +}); + +test('the customer chats with the driver of their own order only, as themselves', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['chat' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); + $controller = new AdhocCfgCustomerController(); + $send = fn (string $text, string $id = 'order_one') => $controller->sendOrderMessage($id, Illuminate\Http\Request::create('/', 'POST', ['text' => $text])); + + expect($controller->orderMessages('order_missing')->getStatusCode())->toBe(404) + ->and(adhocCfgJson($controller->orderMessages('order_one')))->toBe([]) + ->and($send('Hi', 'order_missing')->getStatusCode())->toBe(404) + ->and($send(' ')->getStatusCode())->toBe(422) + ->and($send(str_repeat('x', 2001))->getStatusCode())->toBe(422) + ->and(adhocCfgJson($send('Hi'))['error'])->toBe('You can message the driver once one is assigned.'); + + $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); + $sent = $send('By the lobby'); + + expect($sent->getStatusCode())->toBe(201) + ->and(adhocCfgJson($sent))->toMatchArray(['from' => 'customer', 'text' => 'By the lobby']) + ->and(array_column(adhocCfgJson($controller->orderMessages('order_one')), 'text'))->toBe(['By the lobby']); + + $connection->table('orders')->update(['status' => 'completed']); + expect(adhocCfgJson($send('Thanks'))['error'])->toBe('This conversation has ended.'); +}); + +test('the customer rates a completed order once, from 1 to 5 stars', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['rating' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'in_progress']); + $controller = new AdhocCfgCustomerController(); + $rate = fn ($stars, string $id = 'order_one') => $controller->rateOrder($id, Illuminate\Http\Request::create('/', 'POST', ['stars' => $stars, 'comment' => 'Kind'])); + + expect($rate(5, 'order_missing')->getStatusCode())->toBe(404) + ->and($rate(0)->getStatusCode())->toBe(422) + ->and($rate(2.5)->getStatusCode())->toBe(422) + ->and($rate('lots')->getStatusCode())->toBe(422) + ->and(adhocCfgJson($rate(5))['error'])->toBe('Only a completed order can be rated.'); + + $connection->table('orders')->update(['status' => 'completed']); + expect(adhocCfgJson($rate(4)))->toBe(['status' => 'rated']) + ->and($rate(1)->getStatusCode())->toBe(409); +}); + +test('the customer shares an order in progress, but not one that has ended or has no tracking number', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['interactions' => ['share_tracking' => true]]]); + adhocCfgSeedOrder($connection, ['status' => 'started']); + config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); + $controller = new AdhocCfgCustomerController(); + + $shared = adhocCfgJson($controller->shareOrder('order_one')); + expect($controller->shareOrder('order_missing')->getStatusCode())->toBe(404) + ->and($shared['url'])->toContain('/~/track/TRK1') + ->and($shared['url'])->toMatch('/[?&]share=\d+\.[a-f0-9]{64}$/') + ->and($shared)->toHaveKey('expires_at'); + + $connection->table('orders')->update(['status' => 'no_show']); + expect($controller->shareOrder('order_one')->getStatusCode())->toBe(422); + + $connection->table('orders')->update(['status' => 'started', 'tracking_number_uuid' => null]); + expect($controller->shareOrder('order_one')->getStatusCode())->toBe(422); +}); + +test('customers may cancel until the config\'s cancellation policy says, and order configs the company enabled for them', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $controller = new AdhocCfgCustomerController(); + $config = fn () => OrderConfig::where('uuid', 'config-adhoc')->first(); + $mayCancel = fn () => $controller->helper('customerMayCancel', adhocCfgFresh()); + + // By default customers cancel any time before the order finishes. + $before = $mayCancel(); + $connection->table('orders')->update(['status' => 'in_progress']); + $inProgress = $mayCancel(); + $connection->table('orders')->update(['status' => 'no_show']); + $ended = $mayCancel(); + + adhocCfgPolicies($connection, ['customer' => ['cancellation' => ['allowed_until' => 'in_progress']]]); + $connection->table('orders')->update(['status' => 'arrived']); + $arrived = $mayCancel(); + $connection->table('orders')->update(['status' => 'in_progress']); + $limited = $mayCancel(); + + adhocCfgPolicies($connection, ['customer' => ['cancellation' => ['enabled' => false]]]); + $connection->table('orders')->update(['status' => 'started']); + $disabled = $mayCancel(); + + expect([$before, $inProgress, $ended, $arrived, $limited, $disabled])->toBe([true, true, false, true, false, false]) + ->and($controller->helper('customersMayOrder', $config()))->toBeTrue(); + + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['config-other']]; + $refused = $controller->helper('customersMayOrder', $config()); + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['order_config_passenger']]; + expect($refused)->toBeFalse() + ->and($controller->helper('customersMayOrder', $config()))->toBeTrue(); +}); + +test('a customer deletes their account, but not while an order is in progress by its config', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + $connection->table('places')->insert(['uuid' => 'place-home', 'company_uuid' => 'company-1', 'name' => 'Home', 'owner_uuid' => 'contact-sam']); + $controller = new AdhocCfgCustomerController(); + + $refused = $controller->deleteMe(); + expect($refused->getStatusCode())->toBe(422) + ->and(adhocCfgJson($refused)['error'])->toContain('You have orders in progress'); + + // The config's terminal activity (no_show) ends the order, though it isn't completed or canceled. + $connection->table('orders')->update(['status' => 'no_show']); + expect(adhocCfgJson($controller->deleteMe()))->toBe(['status' => 'deleted']) + ->and($controller->revoked)->toBe(['user-sam']) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->first())->toMatchArray(['name' => 'Deleted customer', 'email' => null, 'phone' => null]) + ->and($connection->table('contacts')->where('uuid', 'contact-sam')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('places')->where('uuid', 'place-home')->value('deleted_at'))->not->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->first())->toMatchArray(['name' => 'Deleted customer', 'phone' => null, 'email' => 'deleted-user-sam@deleted.invalid']) + ->and($connection->table('orders')->where('uuid', 'order-1')->value('deleted_at'))->toBeNull(); + + $controller->customerUuid = null; + expect($controller->deleteMe()->getStatusCode())->toBe(401); +}); + +test('an order that was never dispatched does not hold up deleting the account', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'created', 'dispatched' => 0]); + + expect(adhocCfgJson((new AdhocCfgCustomerController())->deleteMe()))->toBe(['status' => 'deleted']); +}); + +test('a customer with another company keeps their user when one account is deleted', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection); + $connection->table('contacts')->insert(['uuid' => 'contact-sam-2', 'company_uuid' => 'company-2', 'user_uuid' => 'user-sam', 'name' => 'Sam Lee', 'type' => 'customer']); + $nobody = new AdhocCfgCustomerController(); + $connection->table('contacts')->insert(['uuid' => 'contact-guest', 'company_uuid' => 'company-1', 'name' => 'Guest', 'type' => 'customer']); + $nobody->customerUuid = 'contact-guest'; + + (new AdhocCfgCustomerController())->deleteMe(); + $nobody->deleteMe(); + + expect($connection->table('users')->where('uuid', 'user-sam')->value('deleted_at'))->toBeNull() + ->and($connection->table('users')->where('uuid', 'user-sam')->value('name'))->toBe('Sam Lee') + ->and($nobody->revoked)->toBe([]) + ->and($connection->table('contacts')->where('uuid', 'contact-guest')->value('deleted_at'))->not->toBeNull(); +}); + +test('an unsettled order paid by a method the ordering policy names blocks the next order with 402, whatever its type', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['payment_methods' => ['cash', 'card'], 'require_settlement' => ['card']]]]); + adhocCfgSeedOrder($connection, ['transaction_uuid' => 'txn-1', 'type' => 'anything']); + $connection->table('transactions')->insert(['uuid' => 'txn-1', 'company_uuid' => 'company-1', 'amount' => 746, 'currency' => 'USD', 'settlement_status' => 'pending']); + $connection->table('payloads')->update(['payment_method' => 'card']); + $controller = new AdhocCfgCustomerController(); + $sam = Fleetbase\FleetOps\Models\Contact::where('uuid', 'contact-sam')->first(); + $unsettled = fn () => $controller->helper('hasUnsettledOrder', $sam, OrderConfig::where('uuid', 'config-adhoc')->first()); + + $blocked = $unsettled(); + $response = $controller->createOrder(new Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest(['payment_method' => 'card'])); + + $connection->table('transactions')->update(['settlement_status' => 'paid']); + $paid = $unsettled(); + $connection->table('transactions')->update(['settlement_status' => 'pending', 'amount' => 0]); + $free = $unsettled(); + $connection->table('transactions')->update(['amount' => 746]); + $connection->table('payloads')->update(['payment_method' => 'cash']); + $cash = $unsettled(); + $connection->table('payloads')->update(['payment_method' => 'card']); + $connection->table('orders')->update(['status' => 'started']); + $notCompleted = $unsettled(); + $connection->table('orders')->update(['status' => 'completed']); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['require_settlement' => []]]]); + $policyOff = $unsettled(); + + expect([$blocked, $paid, $free, $cash, $notCompleted, $policyOff])->toBe([true, false, false, false, false, false]) + ->and($response->getStatusCode())->toBe(402) + ->and(adhocCfgJson($response)['error'])->toBe('Settle your previous order before placing another.'); +}); + +test('a driver listing nearby orders sees only the adhoc orders they could take', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $connection->table('orders')->insert([ + ['uuid' => 'o-held', 'public_id' => 'order_held', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-adhoc', 'adhoc_strategy' => null], + ['uuid' => 'o-other', 'public_id' => 'order_other', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-adhoc', 'adhoc_strategy' => null], + ['uuid' => 'o-lapsed', 'public_id' => 'order_lapsed', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'sequential'], + ['uuid' => 'o-open', 'public_id' => 'order_open', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-refused', 'public_id' => 'order_refused', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], + ['uuid' => 'o-default', 'public_id' => 'order_default', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ['uuid' => 'o-planned', 'public_id' => 'order_planned', 'company_uuid' => 'company-1', 'adhoc' => 0, 'order_config_uuid' => null, 'adhoc_strategy' => null], + ]); + $connection->table('orders')->insert(['uuid' => 'o-taken', 'public_id' => 'order_taken', 'company_uuid' => 'company-1', 'adhoc' => 1, 'driver_assigned_uuid' => 'chen']); + $connection->table('order_offers')->insert([ + ['uuid' => 'f1', 'order_uuid' => 'o-held', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f2', 'order_uuid' => 'o-other', 'driver_uuid' => 'chen', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], + ['uuid' => 'f3', 'order_uuid' => 'o-lapsed', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2020-01-01 00:00:00'], + ['uuid' => 'f4', 'order_uuid' => 'o-refused', 'driver_uuid' => 'amara', 'status' => 'declined', 'expires_at' => null], + ]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + $listed = fn ($company) => Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::apply(Order::query()->withoutGlobalScopes(), 'amara', $company)->orderBy('id')->pluck('public_id')->all(); + + // One at a time by default: Amara sees her own open offer, the open order she didn't decline, + // planned orders, and an order someone already took. + expect($listed($company))->toBe(['order_held', 'order_open', 'order_planned', 'order_taken']); + + // With the company defaulting to everyone at once, unset orders show too; orders whose config's + // adhoc policy says one at a time still don't. + $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast']])]); + $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); + expect($listed($company))->toBe(['order_held', 'order_open', 'order_default', 'order_planned', 'order_taken']); + + // Each order carries Amara's open offer, or none. + $orders = Order::withoutGlobalScopes()->whereIn('uuid', ['o-held', 'o-open'])->orderBy('id')->get(); + Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::attach($orders, 'amara'); + expect($orders[0]->adhocOffer->uuid)->toBe('f1') + ->and($orders[1]->adhocOffer)->toBeNull() + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present($orders[0]->adhocOffer))->toBe(['status' => 'pending', 'expires_at' => '2099-01-01T00:00:00.000000Z']) + ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present(null))->toBeNull(); +}); + +test('only a strategy that lists openly shows orders without an offer, and a driver is found by public id', function () { + adhocCfgBoot(); + adhocCfgSeedDrivers(Illuminate\Support\Facades\DB::connection()); + $helper = new ReflectionMethod(Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController::class, 'nearbyDriverUuid'); + $ask = fn ($nearby) => $helper->invoke(new Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController(), Illuminate\Http\Request::create('/', 'GET', ['nearby' => $nearby])); + + expect(AdhocDispatch::openlyListed())->toBe(['broadcast']) + ->and((new BroadcastStrategy())->listsOpenly())->toBeTrue() + ->and((new SequentialStrategy())->listsOpenly())->toBeFalse() + ->and($ask('driver_amara'))->toBe('amara') + ->and($ask('driver_rival'))->toBeNull() + ->and($ask('1.28,103.85'))->toBeNull() + ->and($ask(null))->toBeNull(); +}); + +test('drivers hear when their offer closes, and a broadcast failure is only logged', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedDrivers($connection); + $order = adhocCfgOrder($connection); + AdhocCfgRecorder::$events = []; + + adhocCfgSequential()->dispatch($order); + $offer = OrderOffers::pending($order); + Carbon::setTestNow(now()->addMinute()); + adhocCfgSequential()->expire($offer); + Carbon::setTestNow(); + OrderOffers::withdraw($order); + $closed = array_values(array_filter(AdhocCfgRecorder::$events, fn ($event) => $event instanceof Fleetbase\FleetOps\Events\OrderOfferClosed)); + + expect(array_map(fn ($event) => $event->data, $closed))->toBe([['id' => 'order_one', 'status' => 'expired'], ['id' => 'order_one', 'status' => 'withdrawn']]) + ->and($closed[0]->broadcastAs())->toBe('order.offer_closed') + ->and(array_map(fn ($channel) => $channel->name, $closed[0]->broadcastOn()))->toBe(['driver.driver_amara', 'driver.amara']) + ->and($closed[1]->broadcastWith())->toMatchArray(['event' => 'order.offer_closed', 'data' => ['id' => 'order_one', 'status' => 'withdrawn']]); + + AdhocCfgRecorder::$failEvents = true; + OrderOffers::announceClosed($order, ['chen'], 'withdrawn'); + AdhocCfgRecorder::$failEvents = false; + expect(app('log')->warnings)->toContain('Unable to broadcast order.offer_closed'); +}); + +test('saving an order config drops an unknown strategy from its policies and keeps its offer time in range', function () { + $connection = adhocCfgBoot(); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + $stored = fn () => json_decode($connection->table('order_configs')->value('policies'), true); + + $config->forceFill(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'lottery', 'offer_timeout' => 900]], 'custom' => ['kept' => true]]])->save(); + expect($stored())->toBe(['dispatch' => ['adhoc' => ['strategy' => null, 'offer_timeout' => 120]], 'custom' => ['kept' => true]]); + + $config->forceFill(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => null]]]])->save(); + expect($stored())->toBe(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => null]]]) + ->and(OrderConfig::where('uuid', 'config-adhoc')->first()->policy('dispatch.adhoc.strategy'))->toBe('broadcast'); +}); + +test('strategies describe themselves for people choosing one', function () { + expect(AdhocDispatch::describe())->toContain( + ['name' => 'broadcast', 'label' => 'Everyone nearby at once', 'description' => (new BroadcastStrategy())->description()], + ['name' => 'sequential', 'label' => 'One driver at a time', 'description' => (new SequentialStrategy())->description()], + ); +}); + +test('a customer order keeps how it will be paid on its payload, and tells how dispatch ended', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'canceled', 'driver_assigned_uuid' => null]); + $connection->table('order_offers')->insert(['uuid' => 'f-x', 'order_uuid' => 'order-1', 'driver_uuid' => 'amara', 'status' => 'declined']); + + (new AdhocCfgCustomerController())->helper('setPayloadPaymentMethod', 'payload-1', 'card'); + + expect($connection->table('payloads')->where('uuid', 'payload-1')->value('payment_method'))->toBe('card') + ->and($order->dispatchOutcome())->toBe('no_driver_found') + ->and($order->chatChannel)->toBeNull(); +}); diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index 1a1331f84..59e65aa74 100644 --- a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php +++ b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php @@ -890,7 +890,7 @@ protected function createFileFromBase64(string $contents, string $path): mixed $search = new ReflectionMethod(CustomerController::class, 'runPlaceSearch'); $geocode = new ReflectionMethod(CustomerController::class, 'geocodePlaces'); $resource = new ReflectionMethod(CustomerController::class, 'placeResource'); - $owned = new ReflectionMethod(CustomerController::class, 'riderPlaceQuery'); + $owned = new ReflectionMethod(CustomerController::class, 'customerPlaceQuery'); $customer = new Contact(); $customer->setRawAttributes(['uuid' => 'rider-1'], true); diff --git a/server/tests/Feature/Http/Api/OrderConfigControllerTest.php b/server/tests/Feature/Http/Api/OrderConfigControllerTest.php index 9fbf13956..b715f2a42 100644 --- a/server/tests/Feature/Http/Api/OrderConfigControllerTest.php +++ b/server/tests/Feature/Http/Api/OrderConfigControllerTest.php @@ -51,7 +51,16 @@ public function __call($method, $arguments) $schema = $connection->getSchemaBuilder(); $schema->create('order_configs', function ($table) { $table->increments('id'); - foreach (['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'flow', 'meta', 'entities', 'version'] as $column) { + foreach (['uuid', 'public_id', 'company_uuid', 'name', 'key', 'namespace', 'flow', 'meta', 'policies', 'triggers', 'entities', 'version'] as $column) { + $table->string($column)->nullable(); + } + $table->timestamps(); + $table->timestamp('deleted_at')->nullable(); + }); + // Order config resources carry the config's custom fields, which customer apps ask for. + $schema->create('custom_fields', function ($table) { + $table->increments('id'); + foreach (['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'help_text', 'order'] as $column) { $table->string($column)->nullable(); } $table->timestamps(); @@ -82,8 +91,11 @@ public function __call($method, $arguments) expect($probe->callProtected('findOrderConfigOrFail', 'order_config_test'))->toBeInstanceOf(OrderConfig::class); expect(fn () => $probe->callProtected('findOrderConfigOrFail', 'missing'))->toThrow(ModelNotFoundException::class); + $connection->table('custom_fields')->insert(['uuid' => 'field-1', 'company_uuid' => 'company-1', 'subject_uuid' => '44444444-4444-4444-8444-444444444444', 'subject_type' => OrderConfig::class, 'name' => 'passengers', 'label' => 'Passengers', 'order' => 0]); $config = OrderConfig::where('key', 'transport')->first(); expect($probe->callProtected('orderConfigResource', $config))->toBeInstanceOf(OrderConfigResource::class) + ->and($config->relationLoaded('customFields'))->toBeTrue() + ->and($config->customFields->pluck('name')->all())->toBe(['passengers']) ->and($probe->callProtected('orderConfigCollection', [[$config]])) ->toBeInstanceOf(Illuminate\Http\Resources\Json\ResourceCollection::class); diff --git a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php index d4c35749c..bc831317e 100644 --- a/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerStartActivityTest.php @@ -156,7 +156,7 @@ public function __call($method, $arguments) 'waypoints' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'place_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'order', 'type', '_key', '_import_id'], 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'status', 'type', 'email', 'phone', 'password', 'slug', 'username', 'meta', '_key'], - 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'policies', 'triggers', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', '_key'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'region', 'location', 'status_uuid', 'owner_uuid', 'owner_type', 'qr_code', 'barcode', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'proof_uuid', 'status', 'details', 'location', 'code', 'complete', '_key'], 'entities' => ['uuid', 'public_id', 'company_uuid', 'payload_uuid', 'destination_uuid', 'tracking_number_uuid', 'customer_uuid', 'customer_type', 'name', 'type', 'meta', 'internal_id', 'qr_code', 'barcode', 'photo_uuid', '_key', '_import_id'], @@ -663,19 +663,21 @@ public function __call($method, $arguments) expect($connection->table('tracking_statuses')->where('tracking_number_uuid', 'tn-entity-1')->count())->toBeGreaterThanOrEqual(1); }); +/** An adhoc order on a config made from the passenger template: offered one driver at a time, with strict transitions. */ function fleetopsOrderStartRide(SQLiteConnection $connection, array $order = []): void { - $defaults = Fleetbase\FleetOps\Support\FleetOps::rideConfigDefaults(); + $defaults = Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::attributes('passenger'); + // Triggers would queue pushes; these tests are about accepting and declining. $connection->table('order_configs')->insert([ - 'uuid' => 'config-ride', - 'company_uuid' => 'company-1', - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - 'flow' => json_encode($defaults['flow']), - 'meta' => json_encode($defaults['meta']), - 'adhoc_strategy' => $defaults['adhoc_strategy'], + 'uuid' => 'config-ride', + 'company_uuid' => 'company-1', + 'key' => 'passenger', + 'namespace' => 'system:order-config:passenger', + 'flow' => json_encode(array_map(fn ($activity) => array_replace($activity, ['actions' => []]), $defaults['flow'])), + 'meta' => json_encode($defaults['meta']), + 'policies' => json_encode($defaults['policies']), ]); - fleetopsOrderStartSeedOrder($connection, array_merge(['order_config_uuid' => 'config-ride', 'type' => 'ride', 'adhoc' => 1, 'status' => 'dispatched', 'dispatched' => 1, 'dispatched_at' => '2026-11-06 09:00:00'], $order)); + fleetopsOrderStartSeedOrder($connection, array_merge(['order_config_uuid' => 'config-ride', 'type' => 'passenger', 'adhoc' => 1, 'status' => 'dispatched', 'dispatched' => 1, 'dispatched_at' => '2026-11-06 09:00:00'], $order)); $connection->table('drivers')->where('uuid', 'driver-1')->update(['online' => 1]); $connection->table('tracking_statuses')->insert(['uuid' => 'ts-dispatched', 'company_uuid' => 'company-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED', 'status' => 'Finding a driver']); // Declining looks for the next driver, nearest first. @@ -733,7 +735,7 @@ function fleetopsOrderStartOffer(SQLiteConnection $connection, string $driverUui test('of two drivers accepting the same adhoc order only the first gets it', function () { $connection = fleetopsOrderStartBoot(); fleetopsOrderStartRide($connection); - $connection->table('order_configs')->where('uuid', 'config-ride')->update(['adhoc_strategy' => 'broadcast']); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]])]); // Someone else claimed it after this request loaded the order. $connection->table('orders')->update(['driver_assigned_uuid' => 'driver-2']); @@ -755,7 +757,7 @@ public function claim(Order $order, string $driver) test('the driver already holding an adhoc order passes, and a canceled order refuses everyone', function () { $connection = fleetopsOrderStartBoot(); fleetopsOrderStartRide($connection, ['driver_assigned_uuid' => 'driver-1']); - $connection->table('order_configs')->where('uuid', 'config-ride')->update(['adhoc_strategy' => 'broadcast']); + $connection->table('order_configs')->where('uuid', 'config-ride')->update(['policies' => json_encode(['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]])]); $controller = new OrderController(); $held = $controller->startOrder('order_start', Request::create('/x', 'POST', ['assign' => 'driver_one'])); diff --git a/server/tests/Feature/RidesTest.php b/server/tests/Feature/RidesTest.php deleted file mode 100644 index 1577d07d9..000000000 --- a/server/tests/Feature/RidesTest.php +++ /dev/null @@ -1,1230 +0,0 @@ -uuid, $reason]; - - return null; - } -} - -/** A point as MySQL stores it (SRID, then WKB), which the spatial models read back. */ -function rideOffersWkb(float $longitude, float $latitude): string -{ - return pack('V', 0) . pack('C', 1) . pack('V', 1) . pack('e', $longitude) . pack('e', $latitude); -} - -/** [longitude, latitude] of a stored point or of WKT text. */ -function rideOffersPoint(?string $value): array -{ - if ($value !== null && preg_match('/POINT\(\s*([-0-9.]+)\s+([-0-9.]+)\s*\)/i', $value, $m)) { - return [(float) $m[1], (float) $m[2]]; - } - if ($value === null || strlen($value) < 25) { - return [0.0, 0.0]; - } - $xy = unpack('ex/ey', substr($value, 9, 16)); - - return [$xy['x'], $xy['y']]; -} - -function rideOffersBoot(): SQLiteConnection -{ - if (!Illuminate\Support\Str::hasMacro('humanize')) { - Illuminate\Support\Str::macro('humanize', fn ($value, $uppercase = true) => str_replace('_', ' ', Illuminate\Support\Str::snake((string) $value))); - } - - $pdo = new PDO('sqlite::memory:'); - $pdo->sqliteCreateFunction('ST_GeomFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); - $pdo->sqliteCreateFunction('ST_PointFromText', fn ($wkt, $srid = 0, $axis = null) => $wkt); - $pdo->sqliteCreateFunction('ST_X', fn ($wkt) => rideOffersPoint($wkt)[0]); - $pdo->sqliteCreateFunction('ST_Y', fn ($wkt) => rideOffersPoint($wkt)[1]); - $pdo->sqliteCreateFunction('st_distance_sphere', function ($a, $b) { - [$lng1, $lat1] = rideOffersPoint($a); - [$lng2, $lat2] = rideOffersPoint($b); - $rad = M_PI / 180; - $h = sin(($lat2 - $lat1) * $rad / 2) ** 2 + cos($lat1 * $rad) * cos($lat2 * $rad) * sin(($lng2 - $lng1) * $rad / 2) ** 2; - - return 2 * 6371000 * asin(sqrt($h)); - }); - $pdo->sqliteCreateFunction('LOWER', fn ($value) => $value === null ? null : strtolower((string) $value)); - - $connection = new SQLiteConnection($pdo); - $resolver = new ConnectionResolver(['default' => $connection, 'mysql' => $connection]); - $resolver->setDefaultConnection('mysql'); - EloquentModel::setConnectionResolver($resolver); - if (!EloquentModel::getEventDispatcher()) { - EloquentModel::setEventDispatcher(new Illuminate\Events\Dispatcher()); - } - app()->instance('db', new class($connection) { - public function __construct(public SQLiteConnection $c) - { - } - - public function connection($name = null): SQLiteConnection - { - return $this->c; - } - - public function __call($method, $arguments) - { - return $this->c->{$method}(...$arguments); - } - }); - Illuminate\Support\Facades\DB::clearResolvedInstance('db'); - app()->instance('responsecache', new class { - public function __call($method, $arguments) - { - return null; - } - }); - config()->set('activitylog.enabled', false); - config()->set('activitylog.default_auth_driver', 'web'); - app()->bind(Illuminate\Contracts\Config\Repository::class, fn () => config()); - - app()->instance(Illuminate\Contracts\Notifications\Dispatcher::class, new class { - public function send($notifiables, $notification) - { - if (RideOffersRecorder::$notified === ['throw']) { - throw new RuntimeException('push failed'); - } - RideOffersRecorder::$notified[] = [$notifiables->uuid, $notification::class]; - } - - public function sendNow($notifiables, $notification, ?array $channels = null) - { - $this->send($notifiables, $notification); - } - }); - app()->instance('log', new class { - public array $warnings = []; - - public function warning($message, array $context = []) - { - $this->warnings[] = $message; - } - - public function __call($method, $arguments) - { - return null; - } - }); - Illuminate\Support\Facades\Log::clearResolvedInstance('log'); - - $schema = $connection->getSchemaBuilder(); - $tables = [ - 'companies' => ['uuid', 'public_id', 'name', 'options'], - 'users' => ['uuid', 'public_id', 'company_uuid', 'name', 'type', 'status', 'email', 'phone'], - 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'vehicle_uuid', 'status', 'online', 'location', 'current_job_uuid', 'meta', 'rating_average', 'rating_count'], - 'vehicles' => ['uuid', 'public_id', 'company_uuid', 'type', 'plate_number', 'seating_capacity', 'vendor_uuid', 'photo_uuid', 'avatar_url', 'name', 'internal_id', 'location', 'online', 'speed', 'heading', 'altitude', 'year', 'make', 'model', 'class', 'color', 'call_sign', 'status', 'specs', 'vin_data', 'telematics', 'meta', 'slug', 'vin', 'trim', 'plate_number_type'], - 'orders' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'required_vehicle_type', 'chat_channel_uuid', 'fare_finalized_at', 'paid_at', 'tracking_number_uuid', 'dispatched_at', 'started_at', 'customer_uuid', 'customer_type', 'purchase_rate_uuid', 'transaction_uuid', 'order_config_uuid', 'payload_uuid', 'driver_assigned_uuid', 'status', 'type', 'adhoc', 'adhoc_distance', 'dispatched', 'started', 'meta'], - 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'adhoc_strategy', 'adhoc_offer_timeout', 'customer_orders_adhoc', 'match_vehicle_type', 'name', 'key', 'namespace', 'description', 'flow', 'entities', 'meta', 'version', 'core_service', 'status', 'type', 'tags'], - 'order_offers' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'status', 'distance', 'expires_at', 'responded_at'], - 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta', 'payment_method'], - 'places' => ['uuid', 'public_id', 'company_uuid', 'name', 'location', 'meta', 'owner_uuid', 'owner_type'], - 'waypoints' => ['uuid', 'payload_uuid', 'place_uuid', 'order'], - 'entities' => ['uuid', 'payload_uuid', 'name'], - 'tracking_statuses' => ['uuid', 'company_uuid', 'tracking_number_uuid', 'code', 'status'], - 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'status_uuid'], - 'contacts' => ['uuid', '_key', 'public_id', 'company_uuid', 'user_uuid', 'name', 'email', 'phone', 'type', 'photo_uuid', 'meta'], - 'chat_channels' => ['uuid', '_key', 'public_id', 'company_uuid', 'created_by_uuid', 'name', 'slug', 'meta'], - 'chat_participants' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'user_uuid', 'meta'], - 'chat_messages' => ['uuid', '_key', 'public_id', 'company_uuid', 'chat_channel_uuid', 'sender_uuid', 'content', 'meta'], - 'chat_attachments' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'chat_message_uuid', 'sender_uuid', 'file_uuid'], - 'chat_logs' => ['uuid', 'public_id', 'company_uuid', 'chat_channel_uuid', 'initiator_uuid', 'event_type', 'content', 'subjects', 'meta', 'status'], - 'vendors' => ['uuid', 'public_id', 'company_uuid', 'name'], - 'files' => ['uuid', 'public_id', 'company_uuid', 'type', 'path', 'disk', 'bucket', 'original_filename', 'content_type', 'file_size', 'meta'], - 'chat_receipts' => ['uuid', 'public_id', 'company_uuid', 'chat_message_uuid', 'participant_uuid', 'read_at'], - 'positions' => ['uuid', '_key', 'public_id', 'company_uuid', 'order_uuid', 'subject_uuid', 'subject_type', 'coordinates', 'heading', 'speed'], - 'service_rates' => ['uuid', 'public_id', 'company_uuid', 'service_name', 'service_type', 'base_fee', 'per_meter_flat_rate_fee', 'per_meter_unit', 'rate_calculation_method', 'algorithm', 'currency', 'has_cod_fee', 'has_peak_hours_fee'], - 'driver_ratings' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'customer_uuid', 'customer_type', 'stars', 'comment'], - 'service_quotes' => ['uuid', '_key', 'distance', 'time', 'public_id', 'company_uuid', 'request_id', 'service_rate_uuid', 'payload_uuid', 'amount', 'currency', 'meta', 'expired_at'], - 'service_quote_items' => ['uuid', '_key', 'public_id', 'service_quote_uuid', 'amount', 'currency', 'details', 'code'], - 'purchase_rates' => ['uuid', '_key', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'service_quote_uuid', 'transaction_uuid', 'payload_uuid', 'status', 'meta'], - ]; - foreach ($tables as $table => $columns) { - $schema->create($table, function ($blueprint) use ($columns) { - $blueprint->increments('id'); - foreach ($columns as $column) { - $blueprint->string($column)->nullable(); - } - $blueprint->timestamps(); - $blueprint->timestamp('deleted_at')->nullable(); - }); - } - - session(['company' => 'company-1']); - $connection->table('companies')->insert([['uuid' => 'company-1', 'public_id' => 'company_one', 'name' => 'Acme Cabs'], ['uuid' => 'company-2', 'public_id' => 'company_two', 'name' => 'Other Cabs']]); - $connection->table('order_configs')->insert([ - 'uuid' => 'config-ride', - 'company_uuid' => 'company-1', - 'key' => 'ride', - 'namespace' => 'system:order-config:ride', - 'flow' => json_encode(FleetOps::rideConfigDefaults()['flow']), - 'adhoc_strategy' => 'sequential', - 'adhoc_offer_timeout' => 15, - ]); - $connection->table('places')->insert(['uuid' => 'place-pickup', 'company_uuid' => 'company-1', 'name' => 'Raffles Place', 'location' => rideOffersWkb(103.8511, 1.2841)]); - $connection->table('payloads')->insert(['uuid' => 'payload-1', 'company_uuid' => 'company-1', 'pickup_uuid' => 'place-pickup']); - $connection->table('vehicles')->insert([ - ['uuid' => 'car-economy', 'company_uuid' => 'company-1', 'type' => 'Economy'], - ['uuid' => 'car-xl', 'company_uuid' => 'company-1', 'type' => 'xl'], - ]); - - RideOffersRecorder::$notified = []; - Fleetbase\TestSupport\DispatchRecorder::$dispatched = []; - RideOffersOrder::$canceled = []; - RideOffersOrder::$pickupPoint = new Point(1.2841, 103.8511); - - return $connection; -} - -/** Drivers around the pickup at Raffles Place, nearest first: Amara 545 m, Chen 1.2 km, Ben (XL) 210 m. */ -function rideOffersSeedDrivers(SQLiteConnection $connection): void -{ - $connection->table('drivers')->insert([ - ['uuid' => 'amara', 'public_id' => 'driver_amara', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2890)], - ['uuid' => 'chen', 'public_id' => 'driver_chen', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2950)], - ['uuid' => 'ben', 'public_id' => 'driver_ben', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-xl', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2860)], - ['uuid' => 'far', 'public_id' => 'driver_far', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.9915, 1.3644)], - ['uuid' => 'offline', 'public_id' => 'driver_offline', 'company_uuid' => 'company-1', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 0, 'location' => rideOffersWkb(103.8511, 1.2845)], - ['uuid' => 'rival', 'public_id' => 'driver_rival', 'company_uuid' => 'company-2', 'vehicle_uuid' => 'car-economy', 'status' => 'available', 'online' => 1, 'location' => rideOffersWkb(103.8511, 1.2842)], - ]); -} - -function rideOffersOrder(SQLiteConnection $connection, array $attributes = []): RideOffersOrder -{ - $connection->table('orders')->insert(array_merge([ - 'uuid' => 'order-1', - 'public_id' => 'order_ride', - 'company_uuid' => 'company-1', - 'order_config_uuid' => 'config-ride', - 'payload_uuid' => 'payload-1', - 'status' => 'dispatched', - 'type' => 'ride', - 'adhoc' => 1, - 'adhoc_distance' => 6000, - 'dispatched' => 1, - 'started' => 0, - 'required_vehicle_type' => 'economy', - ], $attributes)); - - return RideOffersOrder::where('uuid', $attributes['uuid'] ?? 'order-1')->first(); -} - -function rideOffersDriver(string $uuid): Driver -{ - return Driver::withoutGlobalScopes()->where('uuid', $uuid)->first(); -} - -function rideOffersStatuses(SQLiteConnection $connection): array -{ - return $connection->table('order_offers')->orderBy('id')->get(['driver_uuid', 'status'])->map(fn ($row) => [$row->driver_uuid, $row->status])->all(); -} - -test('drivers are matched by company, free from other jobs and of the vehicle type the order needs', function () { - $connection = rideOffersBoot(); - $connection->table('users')->insert(['uuid' => 'user-moved', 'company_uuid' => 'company-1']); - $connection->table('orders')->insert([ - ['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => null], - ['uuid' => 'job-done', 'company_uuid' => 'company-1', 'status' => 'completed', 'deleted_at' => null], - ['uuid' => 'job-gone', 'company_uuid' => 'company-1', 'status' => 'started', 'deleted_at' => now()], - ]); - $connection->table('drivers')->insert([ - ['uuid' => 'free', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], - ['uuid' => 'via-user', 'company_uuid' => 'company-9', 'user_uuid' => 'user-moved', 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], - ['uuid' => 'other-company', 'company_uuid' => 'company-2', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => null], - ['uuid' => 'busy', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-live'], - ['uuid' => 'finished', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-done'], - ['uuid' => 'stale', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-economy', 'current_job_uuid' => 'job-gone'], - ['uuid' => 'big-car', 'company_uuid' => 'company-1', 'user_uuid' => null, 'vehicle_uuid' => 'car-xl', 'current_job_uuid' => null], - ]); - - $order = new Order(); - $order->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' ECONOMY '], true); - $matched = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $order)->orderBy('id')->pluck('uuid')->all(); - - $anyClass = new Order(); - $anyClass->setRawAttributes(['company_uuid' => 'company-1', 'required_vehicle_type' => ' '], true); - $everyClass = DriverMatching::forOrder(Driver::query()->withoutGlobalScopes(), $anyClass)->orderBy('id')->pluck('uuid')->all(); - - expect($matched)->toBe(['free', 'via-user', 'finished', 'stale']) - ->and($everyClass)->toBe(['free', 'via-user', 'finished', 'stale', 'big-car']) - ->and(DriverMatching::vehicleClass($anyClass))->toBeNull() - ->and(DriverMatching::vehicleClass($order))->toBe('ECONOMY'); -}); - -function sequential(): SequentialStrategy -{ - return new SequentialStrategy(); -} - -test('one at a time: the order goes to the nearest free driver of its type first', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - - Carbon::setTestNow('2026-11-06 09:00:00'); - sequential()->dispatch($order); - Carbon::setTestNow(); - $offer = OrderOffers::pending($order); - - expect(sequential()->name())->toBe('sequential') - ->and($offer->driver_uuid)->toBe('amara') - ->and($offer->distance)->toBeGreaterThan(500)->toBeLessThan(600) - ->and($offer->expires_at->toDateTimeString())->toBe('2026-11-06 09:00:15') - ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class]]) - ->and(Fleetbase\TestSupport\DispatchRecorder::$dispatched)->toBe([['job' => ExpireOrderOffer::class, 'arguments' => [$offer->uuid]]]) - ->and($offer->order->uuid)->toBe('order-1') - ->and($offer->driver->uuid)->toBe('amara'); - - // Dispatching again keeps the open offer instead of offering it twice. - sequential()->dispatch($order); - expect(rideOffersStatuses($connection))->toBe([['amara', 'pending']]); -}); - -test('one at a time: declining moves the order on, and only the offered driver may accept', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - sequential()->dispatch($order); - - expect(sequential()->accept($order, rideOffersDriver('chen')))->toBeFalse() - ->and(sequential()->decline($order, rideOffersDriver('chen')))->toBeFalse() - ->and(sequential()->decline($order, rideOffersDriver('amara')))->toBeTrue() - ->and(OrderOffers::pending($order)->driver_uuid)->toBe('chen') - ->and(sequential()->accept($order, rideOffersDriver('amara')))->toBeFalse() - ->and(sequential()->accept($order, rideOffersDriver('chen')))->toBeTrue() - ->and(rideOffersStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'accepted']]); -}); - -test('one at a time: an offer that ran out cannot be accepted and moves on once', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - sequential()->dispatch($order); - $offer = OrderOffers::pending($order); - - expect(sequential()->expire($offer))->toBeFalse(); - - Carbon::setTestNow(now()->addSeconds(30)); - $acceptedLate = sequential()->accept($order, rideOffersDriver('amara')); - $first = (new ExpireOrderOffer($offer->uuid))->handle(); - $again = (new ExpireOrderOffer($offer->uuid))->handle(); - $missing = (new ExpireOrderOffer('no-such-offer'))->handle(); - Carbon::setTestNow(); - - expect($acceptedLate)->toBeFalse() - ->and($first)->toBeTrue() - ->and($again)->toBeFalse() - ->and($missing)->toBeFalse() - ->and(rideOffersStatuses($connection))->toBe([['amara', 'expired'], ['chen', 'pending']]); -}); - -test('one at a time: the scheduled check starts lost offers and moves stuck ones on', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - - expect(sequential()->redispatch($order))->toBe(1) - ->and(sequential()->redispatch($order))->toBe(0); - - Carbon::setTestNow(now()->addMinute()); - expect(sequential()->redispatch($order))->toBe(1); - Carbon::setTestNow(); - - $connection->table('order_offers')->update(['status' => 'declined']); - expect(sequential()->redispatch($order))->toBe(0) - ->and(rideOffersStatuses($connection))->toBe([['amara', 'declined'], ['chen', 'declined']]); -}); - -test('one at a time: when nobody is left the order is canceled as no driver found', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - sequential()->dispatch($order); - sequential()->decline($order, rideOffersDriver('amara')); - sequential()->decline($order, rideOffersDriver('chen')); - - // The cancel itself is recorded by the test order; mark it canceled as the real one would. - $connection->table('orders')->where('uuid', 'order-1')->update(['status' => 'canceled']); - $canceled = RideOffersOrder::where('uuid', 'order-1')->first(); - - expect(RideOffersOrder::$canceled)->toBe([['order-1', OrderOffers::NO_DRIVER_FOUND]]) - ->and(OrderOffers::outcome($canceled))->toBe(OrderOffers::NO_DRIVER_FOUND_OUTCOME) - ->and(OrderOffers::pending($order))->toBeNull(); - - // Canceled while an offer was open, it wasn't for want of a driver. - $connection->table('order_offers')->where('driver_uuid', 'chen')->update(['status' => 'withdrawn']); - $notAdhoc = new Order(); - $notAdhoc->setRawAttributes(['uuid' => 'order-1', 'status' => 'canceled', 'adhoc' => 0], true); - expect(OrderOffers::outcome(RideOffersOrder::where('uuid', 'order-1')->first()))->toBeNull() - ->and(OrderOffers::outcome($notAdhoc))->toBeNull() - ->and(OrderOffers::outcome($order))->toBeNull(); -}); - -test('one at a time: an order without a usable pickup finds no driver', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - RideOffersOrder::$pickupPoint = null; - - sequential()->dispatch(rideOffersOrder($connection)); - - expect(RideOffersOrder::$canceled)->toHaveCount(1); -}); - -test('one at a time: started, assigned or finished orders are not offered again', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - - $started = rideOffersOrder($connection, ['uuid' => 'o-started', 'started' => 1]); - $assigned = rideOffersOrder($connection, ['uuid' => 'o-assigned', 'driver_assigned_uuid' => 'amara']); - $canceled = rideOffersOrder($connection, ['uuid' => 'o-canceled', 'status' => 'canceled']); - - expect(sequential()->offerNext($started))->toBeNull() - ->and(sequential()->offerNext($assigned))->toBeNull() - ->and(sequential()->offerNext($canceled))->toBeNull() - ->and(rideOffersStatuses($connection))->toBe([]) - ->and(RideOffersOrder::$canceled)->toBe([]); -}); - -test('one at a time: a failed push still leaves the offer open', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - RideOffersRecorder::$notified = ['throw']; - - sequential()->dispatch($order); - - expect(OrderOffers::pending($order)->driver_uuid)->toBe('amara') - ->and(app('log')->warnings)->toContain('Unable to send an order offer'); -}); - -test('at once: every nearby driver of the type is offered the order, and the first to accept gets it', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast']); - $broadcast = new BroadcastStrategy(); - - $broadcast->dispatch($order); - - expect($broadcast->name())->toBe('broadcast') - ->and(rideOffersStatuses($connection))->toBe([['amara', 'pending'], ['chen', 'pending']]) - ->and(RideOffersRecorder::$notified)->toBe([['amara', OrderPing::class], ['chen', OrderPing::class]]) - ->and($broadcast->accept($order, rideOffersDriver('ben')))->toBeTrue(); - - OrderOffers::claimed($order, rideOffersDriver('chen')); - expect(rideOffersStatuses($connection))->toBe([['amara', 'withdrawn'], ['chen', 'accepted']]); -}); - -test('at once: a driver who declines is not offered the order again', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast', 'required_vehicle_type' => null]); - $broadcast = new BroadcastStrategy(); - $broadcast->dispatch($order); - - // Ben declines his offer; Far, never offered, declines from the list of nearby orders. - expect($broadcast->decline($order, rideOffersDriver('ben')))->toBeTrue() - ->and($broadcast->decline($order, rideOffersDriver('far')))->toBeTrue() - ->and($broadcast->decline($order, rideOffersDriver('far')))->toBeTrue(); - - Carbon::setTestNow('2026-11-06 10:00:00'); - $offered = $broadcast->redispatch($order); - Carbon::setTestNow(); - - expect($offered)->toBe(2) - ->and(OrderOffers::declinedDrivers($order))->toBe(['ben', 'far']) - ->and($connection->table('order_offers')->where('status', 'pending')->orderBy('id')->pluck('driver_uuid')->all())->toBe(['amara', 'chen']) - ->and($connection->table('orders')->where('uuid', 'order-1')->value('dispatched_at'))->toBe('2026-11-06 10:00:00'); -}); - -test('at once: no pickup means nobody to offer, and a failed push skips only that driver', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $broadcast = new BroadcastStrategy(); - - RideOffersOrder::$pickupPoint = null; - expect($broadcast->redispatch(rideOffersOrder($connection, ['uuid' => 'o-nowhere'])))->toBe(0); - - RideOffersOrder::$pickupPoint = new Point(1.2841, 103.8511); - RideOffersRecorder::$notified = ['throw']; - expect($broadcast->redispatch(rideOffersOrder($connection)))->toBe(2); -}); - -test('which strategy an order uses: its own, its config\'s, its company\'s, then one at a time', function () { - $connection = rideOffersBoot(); - $order = rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast']); - $fromConfig = rideOffersOrder($connection, ['uuid' => 'o-config']); - $configName = AdhocDispatch::nameFor($fromConfig); - $configWait = AdhocDispatch::offerTimeout($fromConfig); - $connection->table('order_configs')->update(['adhoc_strategy' => 'nonsense', 'adhoc_offer_timeout' => null]); - $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => 500]])]); - $fromCompany = RideOffersOrder::where('uuid', 'o-config')->first()->load('company'); - $connection->table('companies')->update(['options' => null]); - $fallback = RideOffersOrder::where('uuid', 'o-config')->first(); - - expect(AdhocDispatch::nameFor($order))->toBe('broadcast') - ->and(AdhocDispatch::for($order))->toBeInstanceOf(BroadcastStrategy::class) - ->and($configName)->toBe('sequential') - ->and($configWait)->toBe(15) - ->and(AdhocDispatch::nameFor($fromCompany))->toBe('broadcast') - ->and(AdhocDispatch::offerTimeout($fromCompany))->toBe(120) - ->and(AdhocDispatch::nameFor($fallback))->toBe(AdhocDispatch::DEFAULT) - ->and(AdhocDispatch::offerTimeout($fallback))->toBe(20) - ->and(AdhocDispatch::DEFAULT)->toBe('sequential'); - - $connection->table('order_configs')->update(['adhoc_offer_timeout' => 2]); - expect(AdhocDispatch::offerTimeout(RideOffersOrder::where('uuid', 'o-config')->first()))->toBe(10); -}); - -test('more strategies can be registered by name', function () { - $nearestOnly = new class extends SequentialStrategy { - public function name(): string - { - return 'nearest-only'; - } - }; - AdhocDispatch::register('nearest-only', $nearestOnly::class); - - expect(AdhocDispatch::names())->toContain('broadcast', 'sequential', 'nearest-only') - ->and(AdhocDispatch::has('nearest-only'))->toBeTrue() - ->and(AdhocDispatch::has(null))->toBeFalse() - ->and(fn () => AdhocDispatch::register('broken', stdClass::class))->toThrow(InvalidArgumentException::class); -}); - -test('offers record each driver once, and a decline from a driver who was never offered the order', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - $amara = rideOffersDriver('amara'); - - $first = OrderOffers::record($order, $amara); - $again = OrderOffers::record($order, $amara); - OrderOffers::recordDecline($order, rideOffersDriver('ben')); - - expect($again->uuid)->toBe($first->uuid) - ->and($first->expires_at)->toBeNull() - ->and(OrderOffers::offeredDrivers($order))->toBe(['amara', 'ben']) - ->and(OrderOffers::acceptPending($order, $amara))->toBeTrue() - ->and(OrderOffers::withdraw($order))->toBe(0); -}); - -test('the ride config is a strict flow with a no-show ending, offered one driver at a time', function () { - $defaults = FleetOps::rideConfigDefaults(); - $config = new OrderConfig($defaults); - - expect($defaults['key'])->toBe('ride') - ->and(array_keys($defaults['flow']))->toBe(['created', 'dispatched', 'started', 'arrived', 'in_progress', 'completed', 'no_show']) - ->and($config->adhoc_strategy)->toBe('sequential') - ->and($config->customer_orders_adhoc)->toBeTrue() - ->and($config->match_vehicle_type)->toBeTrue() - ->and($config->hasStrictTransitions())->toBeTrue() - ->and($config->canTransition('arrived', 'no_show'))->toBeTrue() - ->and($config->canTransition('arrived', 'completed'))->toBeFalse() - ->and($config->canTransition('in_progress', 'completed'))->toBeTrue() - ->and($config->isTerminalActivityCode('no_show'))->toBeTrue() - ->and($config->getStartedActivity()->get('status'))->toBe('Driver on the way'); -}); - -test('the create ride config command makes the config once per company', function () { - $connection = rideOffersBoot(); - $connection->table('order_configs')->delete(); - - $command = new class extends CreateRideConfig { - public array $lines = []; - public string $id = ''; - public array $opts = []; - - public function option($key = null) - { - return $this->opts[$key] ?? null; - } - - public function argument($key = null) - { - return $this->id; - } - - public function info($string, $verbosity = null) - { - $this->lines[] = $string; - } - - public function error($string, $verbosity = null) - { - $this->lines[] = $string; - } - }; - - $command->id = 'company_missing'; - $missing = $command->handle(); - $command->id = 'company_one'; - $made = $command->handle(); - $command->id = 'company-1'; - $command->opts = ['emergency-number' => '995', 'support-phone' => ' ', 'support-email' => 'help@cabs.test']; - $again = $command->handle(); - - expect($missing)->toBe(1) - ->and($made)->toBe(0) - ->and($again)->toBe(0) - ->and($command->lines[0])->toBe('No company found for company_missing.') - ->and($command->lines[1])->toContain('is ready for Acme Cabs.') - ->and($connection->table('order_configs')->where('key', 'ride')->count())->toBe(1) - ->and(json_decode($connection->table('order_configs')->where('key', 'ride')->value('meta'), true)['rider'])->toBe(['emergency_number' => '995', 'support_email' => 'help@cabs.test']); -}); - -test('a dispatched adhoc order is offered by its strategy, and a busy driver is left out', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - rideOffersOrder($connection, ['tracking_number_uuid' => 'tn-1']); - $connection->table('tracking_statuses')->insert(['uuid' => 'ts-1', 'tracking_number_uuid' => 'tn-1', 'code' => 'DISPATCHED']); - $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'RIDE1', 'owner_uuid' => 'order-1']); - $connection->table('orders')->insert(['uuid' => 'job-live', 'company_uuid' => 'company-1', 'status' => 'started']); - $connection->table('drivers')->where('uuid', 'amara')->update(['current_job_uuid' => 'job-live']); - - (new Fleetbase\FleetOps\Listeners\HandleOrderDispatched())->handle(new Fleetbase\FleetOps\Events\OrderDispatched(RideOffersOrder::where('uuid', 'order-1')->first())); - - expect(rideOffersStatuses($connection))->toBe([['chen', 'pending']]) - ->and(RideOffersRecorder::$notified)->toBe([['chen', OrderPing::class]]); -}); - -test('the scheduled adhoc command asks each order\'s strategy', function () { - $connection = rideOffersBoot(); - $lookup = new ReflectionMethod(Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders::class, 'strategyFor'); - $command = new Fleetbase\FleetOps\Console\Commands\DispatchAdhocOrders(); - - expect($lookup->invoke($command, rideOffersOrder($connection, ['adhoc_strategy' => 'broadcast'])))->toBeInstanceOf(BroadcastStrategy::class) - ->and($lookup->invoke($command, rideOffersOrder($connection, ['uuid' => 'o-2'])))->toBeInstanceOf(SequentialStrategy::class); -}); - -test('fares carry each class\'s seats and how soon its nearest free car could arrive', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $connection->table('vehicles')->where('uuid', 'car-economy')->update(['seating_capacity' => 4]); - $connection->table('vehicles')->insert(['uuid' => 'car-economy-2', 'company_uuid' => 'company-1', 'type' => 'economy', 'seating_capacity' => 5]); - - $controller = new class extends Fleetbase\FleetOps\Http\Controllers\Api\v1\ServiceQuoteController { - public function helper(string $method, ...$arguments): mixed - { - return $this->{$method}(...$arguments); - } - - public function from(?Point $point): void - { - $this->availabilityFrom = $point; - } - }; - $quote = function (string $class) { - $rate = new Fleetbase\FleetOps\Models\ServiceRate(); - $rate->setRawAttributes(['service_type' => $class], true); - $quote = new Fleetbase\FleetOps\Models\ServiceQuote(); - $quote->setRawAttributes(['company_uuid' => 'company-1'], true); - $quote->setRelation('serviceRate', $rate); - - return $quote; - }; - - $economy = $quote('economy'); - $limo = $quote('limo'); - $controller->from(new Point(1.2841, 103.8511)); - $controller->helper('serviceQuoteResourceCollection', [$economy, $limo]); - - $asked = Illuminate\Http\Request::create('/', 'GET', ['availability' => 1]); - $notAsked = Illuminate\Http\Request::create('/', 'GET'); - - expect($economy->availability)->toBe(['seats' => 5, 'pickup_eta' => 138]) - ->and($limo->availability)->toBe(['seats' => null, 'pickup_eta' => null]) - ->and($controller->helper('availabilityPoint', $asked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeInstanceOf(Point::class) - ->and($controller->helper('availabilityPoint', $asked, 'place_pickup'))->toBeNull() - ->and($controller->helper('availabilityPoint', $notAsked, ['latitude' => 1.28, 'longitude' => 103.85]))->toBeNull(); - - // Without a pickup, quotes are returned as they are. - $plain = $quote('economy'); - $controller->from(null); - $controller->helper('serviceQuoteResourceCollection', [$plain]); - expect($plain->availability)->toBeNull(); -}); - -/** A finished ride by rider Sam with driver Chen, from Raffles Place to Bugis. */ -function ridesSeedTrip(SQLiteConnection $connection, array $order = []): RideOffersOrder -{ - rideOffersSeedDrivers($connection); - $connection->table('users')->insert([ - ['uuid' => 'user-sam', 'public_id' => 'user_sam', 'company_uuid' => 'company-1', 'name' => 'Sam Rider', 'type' => 'customer', 'email' => 'sam@rider.test', 'phone' => '+15550190301'], - ['uuid' => 'user-chen', 'public_id' => 'user_chen', 'company_uuid' => 'company-1', 'name' => 'Chen Test', 'type' => 'driver', 'email' => 'chen@cabs.test', 'phone' => '+15550190203'], - ]); - $connection->table('drivers')->where('uuid', 'chen')->update(['user_uuid' => 'user-chen']); - $connection->table('contacts')->insert(['uuid' => 'contact-sam', 'public_id' => 'contact_sam', 'company_uuid' => 'company-1', 'user_uuid' => 'user-sam', 'name' => 'Sam Rider', 'email' => 'sam@rider.test', 'phone' => '+15550190301', 'type' => 'customer']); - $connection->table('places')->insert(['uuid' => 'place-dropoff', 'company_uuid' => 'company-1', 'name' => 'Bugis', 'location' => rideOffersWkb(103.8452, 1.3005)]); - $connection->table('payloads')->where('uuid', 'payload-1')->update(['dropoff_uuid' => 'place-dropoff']); - $connection->table('service_rates')->insert(['uuid' => 'rate-economy', 'company_uuid' => 'company-1', 'service_name' => 'Economy', 'service_type' => 'economy', 'base_fee' => 300, 'rate_calculation_method' => 'algo', 'algorithm' => 'max(200, {distance_km} * 120 + {time_min} * 20)', 'currency' => 'USD']); - $connection->table('service_quotes')->insert(['uuid' => 'quote-booked', 'company_uuid' => 'company-1', 'service_rate_uuid' => 'rate-economy', 'amount' => 533, 'currency' => 'USD']); - $connection->table('tracking_numbers')->insert(['uuid' => 'tn-1', 'company_uuid' => 'company-1', 'tracking_number' => 'RIDE1', 'owner_uuid' => 'order-1']); - $connection->table('purchase_rates')->insert(['uuid' => 'purchase-booked', 'company_uuid' => 'company-1', 'service_quote_uuid' => 'quote-booked', 'payload_uuid' => 'payload-1', 'status' => 'created']); - - return rideOffersOrder($connection, array_merge([ - 'status' => 'completed', - 'started' => 1, - 'started_at' => '2026-11-06 09:00:00', - 'driver_assigned_uuid' => 'chen', - 'customer_uuid' => 'contact-sam', - 'customer_type' => 'Fleetbase\\FleetOps\\Models\\Contact', - 'purchase_rate_uuid' => 'purchase-booked', - 'tracking_number_uuid' => 'tn-1', - ], $order)); -} - -test('the ride chat opens once a driver accepts, with just the rider and driver in it', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); - - expect(Fleetbase\FleetOps\Support\Rides\RideChat::channel($order))->toBeNull(); - - $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); - $order = RideOffersOrder::where('uuid', 'order-1')->first(); - $channel = Fleetbase\FleetOps\Support\Rides\RideChat::channel($order); - $again = Fleetbase\FleetOps\Support\Rides\RideChat::channel(RideOffersOrder::where('uuid', 'order-1')->first()); - - expect($channel->meta)->toBe(['order_public_id' => 'order_ride', 'kind' => 'group']) - ->and($again->uuid)->toBe($channel->uuid) - ->and($connection->table('chat_channels')->count())->toBe(1) - ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']) - ->and($connection->table('orders')->where('uuid', 'order-1')->value('chat_channel_uuid'))->toBe($channel->uuid); - - $sent = Fleetbase\FleetOps\Support\Rides\RideChat::send($channel, 'user-sam', 'By the lobby'); - $chen = $connection->table('chat_participants')->where('user_uuid', 'user-chen')->value('uuid'); - $connection->table('chat_messages')->insert(['uuid' => 'm-2', 'company_uuid' => 'company-1', 'chat_channel_uuid' => $channel->uuid, 'sender_uuid' => $chen, 'content' => 'Two minutes', 'created_at' => now()->addMinute()]); - - $messages = Fleetbase\FleetOps\Support\Rides\RideChat::messages($channel, 'user-sam'); - expect($messages->map(fn ($message) => [$message['from'], $message['text']])->all())->toBe([['rider', 'By the lobby'], ['driver', 'Two minutes']]) - ->and($messages[0]['id'])->toBe($sent->public_id ?? $sent->uuid); -}); - -test('a rider rates their driver once, and the driver keeps an average', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection); - $connection->table('driver_ratings')->insert(['uuid' => 'r-old', 'order_uuid' => 'order-old', 'driver_uuid' => 'chen', 'stars' => 4]); - - $first = Fleetbase\FleetOps\Support\Rides\DriverRatings::rate($order, 9, ' Great '); - $second = Fleetbase\FleetOps\Support\Rides\DriverRatings::rate(RideOffersOrder::where('uuid', 'order-1')->first(), 1); - $driver = rideOffersDriver('chen'); - $rating = Fleetbase\FleetOps\Models\DriverRating::where('order_uuid', 'order-1')->first(); - - expect($first)->toBeTrue() - ->and($second)->toBeFalse() - ->and([$rating->stars, $rating->comment, $rating->customer_uuid])->toBe([5, 'Great', 'contact-sam']) - ->and($rating->order->uuid)->toBe('order-1') - ->and($rating->driver->uuid)->toBe('chen') - ->and($order->driverRating->stars)->toBe(5) - ->and([$driver->rating_average, $driver->rating_count])->toBe([4.5, 2]); - - // A driver whose ratings were all removed has no average. - $connection->table('driver_ratings')->update(['deleted_at' => now()]); - Fleetbase\FleetOps\Support\Rides\DriverRatings::refresh('chen'); - expect([rideOffersDriver('chen')->rating_average, rideOffersDriver('chen')->rating_count])->toBe([null, 0]); -}); - -test('two ratings racing for one order keep the first', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection); - // The other request's rating lands between the check and the insert; the unique index refuses this one. - $connection->statement("CREATE TRIGGER rating_race BEFORE INSERT ON driver_ratings BEGIN SELECT RAISE(ABORT, 'UNIQUE constraint failed: driver_ratings.order_uuid'); END"); - - expect(Fleetbase\FleetOps\Support\Rides\DriverRatings::rate($order, 5))->toBeFalse() - ->and(rideOffersDriver('chen')->rating_count)->toBeNull(); -}); - -test('a share link opens only its rider\'s view of its order, until it expires', function () { - config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); - $order = new Order(); - $order->setRawAttributes(['uuid' => 'order-1', 'company_uuid' => 'company-1'], true); - $sam = new Fleetbase\FleetOps\Models\Contact(); - $sam->setRawAttributes(['uuid' => 'contact-sam'], true); - $other = new Fleetbase\FleetOps\Models\Contact(); - $other->setRawAttributes(['uuid' => 'contact-other'], true); - - $scope = Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $sam); - $token = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam'); - $expired = Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::token('order-1', 'contact-sam', Carbon::now()->subMinute()); - $valid = fn ($token, $scope) => Fleetbase\FleetOps\Support\TrackingPage\TrackingShare::valid($token, $scope); - - expect($valid($token, $scope))->toBeTrue() - ->and($valid($token, Fleetbase\FleetOps\Support\TrackingScope::forCustomer($order, $other)))->toBeFalse() - ->and($valid($expired, $scope))->toBeFalse() - ->and($valid(substr($token, 0, -1) . (str_ends_with($token, '0') ? '1' : '0'), $scope))->toBeFalse() - ->and($valid('not-a-token', $scope))->toBeFalse() - ->and($valid(['array'], $scope))->toBeFalse() - ->and($valid($token, null))->toBeFalse(); -}); - -test('ride pushes say what happened, by name, to the rider only', function () { - $order = new Order(); - $order->setRawAttributes(['public_id' => 'order_ride'], true); - $driver = new Driver(); - $driver->setRawAttributes(['uuid' => 'chen'], true); - $driver->setRelation('user', null); - $order->setRelation('driverAssigned', new class extends Driver { - public function getNameAttribute() - { - return 'Chen Test'; - } - }); - - $arrived = new Fleetbase\FleetOps\Notifications\RideUpdate($order, 'arrived'); - $nobody = new Fleetbase\FleetOps\Notifications\RideUpdate((new Order())->setRawAttributes(['public_id' => 'order_x'], true), 'started'); - - expect($arrived->title)->toBe('Your driver has arrived') - ->and($arrived->message)->toBe('Chen is waiting at the pickup point.') - ->and($arrived->data)->toBe(['id' => 'order_ride', 'type' => 'ride_arrived']) - ->and($arrived->via(null))->toBe([NotificationChannels\Fcm\FcmChannel::class, NotificationChannels\Apn\ApnChannel::class]) - ->and($nobody->message)->toBe('Your driver accepted your ride.') - ->and(Fleetbase\FleetOps\Notifications\RideUpdate::knows('in_progress'))->toBeTrue() - ->and(Fleetbase\FleetOps\Notifications\RideUpdate::knows('dispatched'))->toBeFalse(); -}); - -test('each step of a ride reaches the rider, and the car about to arrive is told once', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection, ['status' => 'started']); - $updates = Fleetbase\FleetOps\Support\Rides\RideUpdates::class; - Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); - - // Status changes - $order->status = 'arrived'; - $order->save(); - $quiet = RideOffersOrder::where('uuid', 'order-1')->first(); - $notRide = new Order(); - $notRide->setRawAttributes(['type' => 'transport'], true); - expect($updates::statusChanged($order))->toBeTrue() - ->and($updates::statusChanged($quiet))->toBeFalse() - ->and($updates::statusChanged($notRide))->toBeFalse() - ->and(RideOffersRecorder::$notified)->toBe([['contact-sam', Fleetbase\FleetOps\Notifications\RideUpdate::class]]); - - $connection->table('order_offers')->insert(['uuid' => 'f-out', 'order_uuid' => 'order-1', 'driver_uuid' => 'amara', 'status' => 'expired']); - $order->status = 'canceled'; - $order->save(); - $updates::statusChanged($order); - $order->status = 'dispatched'; - $order->save(); - expect($updates::statusChanged($order))->toBeFalse() - ->and(RideOffersRecorder::$notified)->toHaveCount(2); - - // Arriving soon: only a started ride, only near the pickup, only once. - $started = RideOffersOrder::where('uuid', 'order-1')->first(); - $started->status = 'started'; - $near = rideOffersDriver('ben'); - $far = rideOffersDriver('chen'); - $nowhere = new Driver(); - expect($updates::driverMoved($near, null))->toBeFalse() - ->and($updates::driverMoved($near, $quiet->setRawAttributes(array_merge($quiet->getAttributes(), ['status' => 'arrived']))))->toBeFalse() - ->and($updates::driverMoved($far, $started))->toBeFalse() - ->and($updates::driverMoved($nowhere, $started))->toBeFalse() - ->and($updates::driverMoved($near, $started))->toBeTrue() - ->and($updates::driverMoved($near, $started))->toBeFalse(); - - // A rider who can't be reached, and a push that fails, don't break anything. - $orphan = rideOffersOrder($connection, ['uuid' => 'order-2', 'public_id' => 'order_2', 'status' => 'started', 'customer_uuid' => null]); - $orphan->status = 'arrived'; - $orphan->save(); - RideOffersRecorder::$notified = ['throw']; - $order->status = 'in_progress'; - $order->save(); - expect($updates::statusChanged($orphan))->toBeFalse() - ->and($updates::statusChanged($order))->toBeFalse() - ->and(app('log')->warnings)->toContain('Unable to send a ride update'); -}); - -test('a finished ride is priced from the distance its car covered and the trip time', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection); - $connection->table('tracking_statuses')->insert(['uuid' => 'ts-board', 'tracking_number_uuid' => 'tn-1', 'code' => 'IN_PROGRESS', 'created_at' => '2026-11-06 09:05:00']); - $connection->table('positions')->insert([ - ['uuid' => 'p0', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2700), 'created_at' => '2026-11-06 09:04:00'], - ['uuid' => 'p1', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2841), 'created_at' => '2026-11-06 09:05:10'], - ['uuid' => 'p2', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8511, 1.2931), 'created_at' => '2026-11-06 09:09:00'], - ['uuid' => 'p3', 'order_uuid' => 'order-1', 'coordinates' => rideOffersWkb(103.8452, 1.3005), 'created_at' => '2026-11-06 09:14:00'], - ]); - - Carbon::setTestNow('2026-11-06 09:15:00'); - $fare = Fleetbase\FleetOps\Support\Rides\FinalFare::settle($order); - Carbon::setTestNow(); - - // About 1.0 km plus 1.05 km over 10 minutes: base 300, then 2.05 × 120 + 10 × 20 = 746 cents. - expect($fare['final'])->toBeTrue() - ->and($fare['distance_source'])->toBe('positions') - ->and($fare['distance_m'])->toBeGreaterThan(2000)->toBeLessThan(2100) - ->and($fare['duration_s'])->toBe(600) - ->and($fare['estimate'])->toBe(533) - ->and($fare['total'])->toBeGreaterThan(740)->toBeLessThan(750) - ->and(array_column($fare['lines'], 'label'))->toBe(['Base fare', 'Distance and time']) - ->and($connection->table('orders')->where('uuid', 'order-1')->value('fare_finalized_at'))->not->toBeNull() - ->and(RideOffersOrder::where('uuid', 'order-1')->first()->fare())->toMatchArray(['final' => true, 'total' => $fare['total'], 'currency' => 'USD', 'estimate' => 533, 'distance' => $fare['distance_m'], 'time' => 600, 'service' => 'Economy']) - ->and($connection->table('service_quotes')->where('uuid', '!=', 'quote-booked')->value('amount'))->toBe((string) $fare['total']) - ->and($connection->table('service_quote_items')->count())->toBe(2) - ->and($connection->table('orders')->value('purchase_rate_uuid'))->not->toBe('purchase-booked'); - - // Priced once. - expect(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(RideOffersOrder::where('uuid', 'order-1')->first()))->toBeNull(); -}); - -test('a ride without positions is priced on the straight line, and other orders are left alone', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection); - $order->started_at = null; - - [$metres, $source] = Fleetbase\FleetOps\Support\Rides\FinalFare::distance($order, Carbon::parse('2026-11-06 09:00:00')); - $connection->table('payloads')->update(['dropoff_uuid' => null]); - [$none, $nothing] = Fleetbase\FleetOps\Support\Rides\FinalFare::distance(RideOffersOrder::where('uuid', 'order-1')->first(), Carbon::now()); - - $started = Fleetbase\FleetOps\Support\Rides\FinalFare::tripStartedAt(RideOffersOrder::where('uuid', 'order-1')->first()); - $unrated = ridesSeedOtherRate($connection); - - expect($source)->toBe('straight_line') - ->and($metres)->toBeGreaterThan(1900)->toBeLessThan(2000) - ->and([$none, $nothing])->toBe([0, 'none']) - ->and($started->toDateTimeString())->toBe('2026-11-06 09:00:00') - ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-live', 'status' => 'started', 'meta' => json_encode([])])))->toBeNull() - ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-transport', 'type' => 'transport', 'status' => 'completed'])))->toBeNull() - ->and(Fleetbase\FleetOps\Support\Rides\FinalFare::settle(rideOffersOrder($connection, ['uuid' => 'o-unpriced', 'status' => 'completed', 'purchase_rate_uuid' => null])))->toBeNull() - ->and($unrated)->toBe(['Base fare', 'Distance', 'Peak']); -}); - -/** The line labels a finished ride gets on a per-km rate, and on a rate named some other way. */ -function ridesSeedOtherRate(SQLiteConnection $connection): array -{ - $label = new ReflectionMethod(Fleetbase\FleetOps\Support\Rides\FinalFare::class, 'label'); - $rate = new Fleetbase\FleetOps\Models\ServiceRate(); - $rate->setRawAttributes(['rate_calculation_method' => 'per_meter'], true); - $other = new Fleetbase\FleetOps\Models\ServiceRate(); - $other->setRawAttributes(['rate_calculation_method' => 'fixed_meter'], true); - - return [$label->invoke(null, $rate, 'Base Fee', 0), $label->invoke(null, $rate, 'Service Fee', 1), $label->invoke(null, $other, 'Peak', 2)]; -} - -class RidesCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController -{ - public ?string $customerUuid = 'contact-sam'; - public array $revoked = []; - - protected function currentCustomer(): ?Fleetbase\FleetOps\Models\Contact - { - return $this->customerUuid ? Fleetbase\FleetOps\Models\Contact::where('uuid', $this->customerUuid)->first() : null; - } - - protected function findOrderOrFail(string $id): Order - { - return RideOffersOrder::where('public_id', $id)->firstOrFail(); - } - - protected function deleteUserTokens(Fleetbase\Models\User $user): void - { - $this->revoked[] = $user->uuid; - } - - public function helper(string $method, ...$arguments): mixed - { - return $this->{$method}(...$arguments); - } - - protected function trackingPageUrl(string $number, ?string $companyUuid): string - { - return 'https://console.test/~/track/' . $number . ($companyUuid === 'company-1' ? '' : '?org=other'); - } -} - -function ridesJson($response): array -{ - return $response->getData(true); -} - -test('the rider chats with the driver of their own ride only, as themselves', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection, ['status' => 'started', 'driver_assigned_uuid' => null]); - $controller = new RidesCustomerController(); - $send = fn (string $text, string $id = 'order_ride') => $controller->sendOrderMessage($id, Illuminate\Http\Request::create('/', 'POST', ['text' => $text])); - - expect($controller->orderMessages('order_missing')->getStatusCode())->toBe(404) - ->and(ridesJson($controller->orderMessages('order_ride')))->toBe([]) - ->and($send('Hi', 'order_missing')->getStatusCode())->toBe(404) - ->and($send(' ')->getStatusCode())->toBe(422) - ->and($send(str_repeat('x', 2001))->getStatusCode())->toBe(422) - ->and(ridesJson($send('Hi'))['error'])->toContain('once they accept'); - - $connection->table('orders')->update(['driver_assigned_uuid' => 'chen']); - $sent = $send('By the lobby'); - - expect($sent->getStatusCode())->toBe(201) - ->and(ridesJson($sent))->toMatchArray(['from' => 'rider', 'text' => 'By the lobby']) - ->and(array_column(ridesJson($controller->orderMessages('order_ride')), 'text'))->toBe(['By the lobby']); - - $connection->table('orders')->update(['status' => 'completed']); - expect(ridesJson($send('Thanks'))['error'])->toBe('This ride has ended.'); -}); - -test('the rider rates a finished ride once, from 1 to 5 stars', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection, ['status' => 'in_progress']); - $controller = new RidesCustomerController(); - $rate = fn ($stars, string $id = 'order_ride') => $controller->rateOrder($id, Illuminate\Http\Request::create('/', 'POST', ['stars' => $stars, 'comment' => 'Kind'])); - - expect($rate(5, 'order_missing')->getStatusCode())->toBe(404) - ->and($rate(0)->getStatusCode())->toBe(422) - ->and($rate(2.5)->getStatusCode())->toBe(422) - ->and($rate('lots')->getStatusCode())->toBe(422) - ->and(ridesJson($rate(5))['error'])->toBe('Only a finished ride can be rated.'); - - $connection->table('orders')->update(['status' => 'completed']); - expect(ridesJson($rate(4)))->toBe(['status' => 'rated']) - ->and($rate(1)->getStatusCode())->toBe(409); -}); - -test('the rider shares a ride in progress, and reads the operator settings', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection, ['status' => 'started']); - config()->set('app.key', 'base64:' . base64_encode(str_repeat('k', 32))); - config()->set('fleetbase.console.host', 'https://console.test'); - $controller = new RidesCustomerController(); - - $shared = ridesJson($controller->shareOrder('order_ride')); - expect($controller->shareOrder('order_missing')->getStatusCode())->toBe(404) - ->and($shared['url'])->toContain('/~/track/RIDE1') - ->and($shared['url'])->toMatch('/[?&]share=\d+\.[a-f0-9]{64}$/'); - - $connection->table('orders')->update(['tracking_number_uuid' => null]); - expect($controller->shareOrder('order_ride')->getStatusCode())->toBe(422) - ->and(ridesJson($controller->rideSettings()))->toBe(['emergency_number' => null, 'support' => ['phone' => null, 'email' => null]]); - - $connection->table('order_configs')->update(['meta' => json_encode(['rider' => ['emergency_number' => '995', 'support_email' => 'help@cabs.test']])]); - expect(ridesJson($controller->rideSettings()))->toBe(['emergency_number' => '995', 'support' => ['phone' => null, 'email' => 'help@cabs.test']]); -}); - -test('a rider deletes their account, but not in the middle of a ride', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection, ['status' => 'started']); - $connection->table('places')->insert(['uuid' => 'place-home', 'company_uuid' => 'company-1', 'name' => 'Home', 'owner_uuid' => 'contact-sam']); - $controller = new RidesCustomerController(); - - expect(ridesJson($controller->deleteMe())['error'])->toContain('Finish or cancel your ride'); - - $connection->table('orders')->update(['status' => 'completed']); - expect(ridesJson($controller->deleteMe()))->toBe(['status' => 'deleted']) - ->and($controller->revoked)->toBe(['user-sam']) - ->and($connection->table('contacts')->where('uuid', 'contact-sam')->first())->toMatchArray(['name' => 'Deleted rider', 'email' => null, 'phone' => null]) - ->and($connection->table('contacts')->where('uuid', 'contact-sam')->value('deleted_at'))->not->toBeNull() - ->and($connection->table('places')->where('uuid', 'place-home')->value('deleted_at'))->not->toBeNull() - ->and($connection->table('users')->where('uuid', 'user-sam')->first())->toMatchArray(['name' => 'Deleted rider', 'phone' => null, 'email' => 'deleted-user-sam@deleted.invalid']) - ->and($connection->table('orders')->where('uuid', 'order-1')->value('deleted_at'))->toBeNull(); - - $controller->customerUuid = null; - expect($controller->deleteMe()->getStatusCode())->toBe(401); -}); - -test('a rider with another company keeps their user when one account is deleted', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection); - $connection->table('contacts')->insert(['uuid' => 'contact-sam-2', 'company_uuid' => 'company-2', 'user_uuid' => 'user-sam', 'name' => 'Sam Rider', 'type' => 'customer']); - $nobody = new RidesCustomerController(); - $connection->table('contacts')->insert(['uuid' => 'contact-guest', 'company_uuid' => 'company-1', 'name' => 'Guest', 'type' => 'customer']); - $nobody->customerUuid = 'contact-guest'; - - (new RidesCustomerController())->deleteMe(); - $nobody->deleteMe(); - - expect($connection->table('users')->where('uuid', 'user-sam')->value('deleted_at'))->toBeNull() - ->and($connection->table('users')->where('uuid', 'user-sam')->value('name'))->toBe('Sam Rider') - ->and($nobody->revoked)->toBe([]) - ->and($connection->table('contacts')->where('uuid', 'contact-guest')->value('deleted_at'))->not->toBeNull(); -}); - -test('an unpaid card trip blocks the next booking, and cash never does', function () { - $connection = rideOffersBoot(); - ridesSeedTrip($connection, ['fare_finalized_at' => '2026-11-06 09:15:00']); - $connection->table('payloads')->update(['payment_method' => 'card']); - $controller = new RidesCustomerController(); - $sam = Fleetbase\FleetOps\Models\Contact::where('uuid', 'contact-sam')->first(); - - $unpaid = $controller->helper('hasUnpaidRide', $sam); - $order = RideOffersOrder::where('uuid', 'order-1')->first(); - $marked = [$order->markPaid(), $order->markPaid()]; - $paid = $controller->helper('hasUnpaidRide', $sam); - $connection->table('orders')->update(['paid_at' => null]); - $connection->table('payloads')->update(['payment_method' => 'cash']); - $cash = $controller->helper('hasUnpaidRide', $sam); - - expect([$unpaid, $paid, $cash])->toBe([true, false, false]) - ->and($marked)->toBe([true, false]); -}); - -test('when a ride is completed the rider is told and the ride is priced', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection, ['status' => 'in_progress']); - Illuminate\Support\Facades\Cache::swap(new Illuminate\Cache\Repository(new Illuminate\Cache\ArrayStore())); - - $order->status = 'completed'; - $order->save(); - (new Fleetbase\FleetOps\Observers\OrderObserver())->updated($order); - - expect($connection->table('orders')->value('fare_finalized_at'))->not->toBeNull() - ->and(RideOffersRecorder::$notified)->toBe([['contact-sam', Fleetbase\FleetOps\Notifications\RideUpdate::class]]); -}); - -test('a driver listing nearby orders sees only the adhoc orders they could take', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $connection->table('orders')->insert([ - ['uuid' => 'o-held', 'public_id' => 'order_held', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-ride', 'adhoc_strategy' => null], - ['uuid' => 'o-other', 'public_id' => 'order_other', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => 'config-ride', 'adhoc_strategy' => null], - ['uuid' => 'o-lapsed', 'public_id' => 'order_lapsed', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'sequential'], - ['uuid' => 'o-open', 'public_id' => 'order_open', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], - ['uuid' => 'o-refused', 'public_id' => 'order_refused', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => 'broadcast'], - ['uuid' => 'o-default', 'public_id' => 'order_default', 'company_uuid' => 'company-1', 'adhoc' => 1, 'order_config_uuid' => null, 'adhoc_strategy' => null], - ['uuid' => 'o-planned', 'public_id' => 'order_planned', 'company_uuid' => 'company-1', 'adhoc' => 0, 'order_config_uuid' => null, 'adhoc_strategy' => null], - ]); - $connection->table('orders')->insert(['uuid' => 'o-taken', 'public_id' => 'order_taken', 'company_uuid' => 'company-1', 'adhoc' => 1, 'driver_assigned_uuid' => 'chen']); - $connection->table('order_offers')->insert([ - ['uuid' => 'f1', 'order_uuid' => 'o-held', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], - ['uuid' => 'f2', 'order_uuid' => 'o-other', 'driver_uuid' => 'chen', 'status' => 'pending', 'expires_at' => '2099-01-01 00:00:00'], - ['uuid' => 'f3', 'order_uuid' => 'o-lapsed', 'driver_uuid' => 'amara', 'status' => 'pending', 'expires_at' => '2020-01-01 00:00:00'], - ['uuid' => 'f4', 'order_uuid' => 'o-refused', 'driver_uuid' => 'amara', 'status' => 'declined', 'expires_at' => null], - ]); - $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); - $listed = fn ($company) => Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::apply(Order::query()->withoutGlobalScopes(), 'amara', $company)->orderBy('id')->pluck('public_id')->all(); - - // One at a time by default: Amara sees her own open offer, the open order she didn't decline, - // planned orders, and an order someone already took. - expect($listed($company))->toBe(['order_held', 'order_open', 'order_planned', 'order_taken']); - - // With the company defaulting to everyone at once, unset orders show too. - $connection->table('companies')->where('uuid', 'company-1')->update(['options' => json_encode(['fleetops' => ['adhoc_strategy' => 'broadcast']])]); - $company = Fleetbase\Models\Company::where('uuid', 'company-1')->first(); - expect($listed($company))->toBe(['order_held', 'order_open', 'order_default', 'order_planned', 'order_taken']); - - // Each order carries Amara's open offer, or none. - $orders = Order::withoutGlobalScopes()->whereIn('uuid', ['o-held', 'o-open'])->orderBy('id')->get(); - Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::attach($orders, 'amara'); - expect($orders[0]->adhocOffer->uuid)->toBe('f1') - ->and($orders[1]->adhocOffer)->toBeNull() - ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present($orders[0]->adhocOffer))->toBe(['status' => 'pending', 'expires_at' => '2099-01-01T00:00:00.000000Z']) - ->and(Fleetbase\FleetOps\Support\AdhocDispatch\AdhocOfferListing::present(null))->toBeNull(); -}); - -test('only a strategy that lists openly shows orders without an offer, and a driver is found by public id', function () { - rideOffersBoot(); - rideOffersSeedDrivers(Illuminate\Support\Facades\DB::connection()); - $helper = new ReflectionMethod(Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController::class, 'nearbyDriverUuid'); - $ask = fn ($nearby) => $helper->invoke(new Fleetbase\FleetOps\Http\Controllers\Api\v1\OrderController(), Illuminate\Http\Request::create('/', 'GET', ['nearby' => $nearby])); - - expect(AdhocDispatch::openlyListed())->toBe(['broadcast']) - ->and((new BroadcastStrategy())->listsOpenly())->toBeTrue() - ->and((new SequentialStrategy())->listsOpenly())->toBeFalse() - ->and($ask('driver_amara'))->toBe('amara') - ->and($ask('driver_rival'))->toBeNull() - ->and($ask('1.28,103.85'))->toBeNull() - ->and($ask(null))->toBeNull(); -}); - -test('drivers hear when their offer closes, and a broadcast failure is only logged', function () { - $connection = rideOffersBoot(); - rideOffersSeedDrivers($connection); - $order = rideOffersOrder($connection); - RideOffersRecorder::$events = []; - - sequential()->dispatch($order); - $offer = OrderOffers::pending($order); - Carbon::setTestNow(now()->addMinute()); - sequential()->expire($offer); - Carbon::setTestNow(); - OrderOffers::withdraw($order); - $closed = array_values(array_filter(RideOffersRecorder::$events, fn ($event) => $event instanceof Fleetbase\FleetOps\Events\OrderOfferClosed)); - - expect(array_map(fn ($event) => $event->data, $closed))->toBe([['id' => 'order_ride', 'status' => 'expired'], ['id' => 'order_ride', 'status' => 'withdrawn']]) - ->and($closed[0]->broadcastAs())->toBe('order.offer_closed') - ->and(array_map(fn ($channel) => $channel->name, $closed[0]->broadcastOn()))->toBe(['driver.driver_amara', 'driver.amara']) - ->and($closed[1]->broadcastWith())->toMatchArray(['event' => 'order.offer_closed', 'data' => ['id' => 'order_ride', 'status' => 'withdrawn']]); - - RideOffersRecorder::$failEvents = true; - OrderOffers::announceClosed($order, ['chen'], 'withdrawn'); - RideOffersRecorder::$failEvents = false; - expect(app('log')->warnings)->toContain('Unable to broadcast order.offer_closed'); -}); - -test('an order config drops an unknown strategy and keeps its offer time in range', function () { - $connection = rideOffersBoot(); - $config = OrderConfig::where('uuid', 'config-ride')->first(); - - $config->forceFill(['adhoc_strategy' => 'lottery', 'adhoc_offer_timeout' => 900])->save(); - expect($connection->table('order_configs')->value('adhoc_strategy'))->toBeNull() - ->and((int) $connection->table('order_configs')->value('adhoc_offer_timeout'))->toBe(120); - - $config->forceFill(['adhoc_strategy' => 'broadcast', 'adhoc_offer_timeout' => null])->save(); - expect($connection->table('order_configs')->value('adhoc_strategy'))->toBe('broadcast') - ->and($connection->table('order_configs')->value('adhoc_offer_timeout'))->toBeNull(); -}); - -test('strategies describe themselves for people choosing one', function () { - expect(AdhocDispatch::describe())->toContain( - ['name' => 'broadcast', 'label' => 'Everyone nearby at once', 'description' => (new BroadcastStrategy())->description()], - ['name' => 'sequential', 'label' => 'One driver at a time', 'description' => (new SequentialStrategy())->description()], - ); -}); - -test('a rider order keeps how it will be paid on its payload, and tells how dispatch ended', function () { - $connection = rideOffersBoot(); - $order = ridesSeedTrip($connection, ['status' => 'canceled']); - $connection->table('order_offers')->insert(['uuid' => 'f-x', 'order_uuid' => 'order-1', 'driver_uuid' => 'amara', 'status' => 'declined']); - - (new RidesCustomerController())->helper('setPayloadPaymentMethod', 'payload-1', 'card'); - - expect($connection->table('payloads')->where('uuid', 'payload-1')->value('payment_method'))->toBe('card') - ->and($order->dispatchOutcome())->toBe('no_driver_found') - ->and($order->chatChannel)->toBeNull(); -}); diff --git a/server/tests/FleetOpsSupportContractsTest.php b/server/tests/FleetOpsSupportContractsTest.php index 2ef8b2c1a..659df6cb1 100644 --- a/server/tests/FleetOpsSupportContractsTest.php +++ b/server/tests/FleetOpsSupportContractsTest.php @@ -2,15 +2,13 @@ use Fleetbase\FleetOps\Models\Place; use Fleetbase\FleetOps\Support\FleetOps; +use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; use Fleetbase\FleetOps\Support\Geocoding; use Illuminate\Support\Str; function fleetopsTransportConfigDefaults(): array { - $reflection = new ReflectionMethod(FleetOps::class, 'transportConfigDefaults'); - $reflection->setAccessible(true); - - return $reflection->invoke(null); + return OrderConfigTemplates::attributes('transport'); } class FleetOpsGeocodingResultFake diff --git a/server/tests/FlowResourceTest.php b/server/tests/FlowResourceTest.php index c189198a3..85d60dc61 100644 --- a/server/tests/FlowResourceTest.php +++ b/server/tests/FlowResourceTest.php @@ -144,9 +144,12 @@ function flowFixture(): array ->and((new Condition(['field' => 'status', 'operator' => 'notEqual', 'value' => 'completed']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'priority', 'operator' => 'greaterThan', 'value' => 2]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'priority', 'operator' => 'lessThanOrEqual', 'value' => 3]))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'deliver fragile parcel today']))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'deliver fragile parcel']))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'notes', 'operator' => 'endsWith', 'value' => 'today deliver fragile parcel']))->eval($order))->toBeTrue(); + // The field holds the value: notes contain, begin with or end with it. + ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'Fragile']))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'notes', 'operator' => 'contains', 'value' => 'deliver fragile parcel today']))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'deliver']))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'notes', 'operator' => 'beginsWith', 'value' => 'parcel']))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'notes', 'operator' => 'endsWith', 'value' => 'parcel']))->eval($order))->toBeTrue(); expect(fn () => (new Condition(['field' => 'status', 'operator' => 'between', 'value' => []]))->eval($order)) ->toThrow(Exception::class, 'Unknown operator: between'); @@ -154,12 +157,22 @@ function flowFixture(): array // Remaining operator arms: existence, array membership, boolean logic // and the strict lower-than comparison expect((new Condition(['field' => 'status', 'operator' => 'exists', 'value' => null]))->eval($order))->toBeTrue() - ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => ['ready']]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => ['ready', 'held']]))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => 'held, ready']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => ['ready']]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => ['held']]))->eval($order))->toBeTrue() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'exists', 'value' => null]))->eval($order))->toBeFalse() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'notEqual', 'value' => 'anything']))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'and', 'value' => true]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'or', 'value' => false]))->eval($order))->toBeTrue() ->and((new Condition(['field' => 'status', 'operator' => 'not', 'value' => null]))->eval($order))->toBeFalse() ->and((new Condition(['field' => 'priority', 'operator' => 'lessThan', 'value' => 9]))->eval($order))->toBeTrue(); + + // `has` and `doesntHave` look for the value in a field that is a list. + $tagged = flowTestOrder(['tags' => ['Fragile', 'express']]); + expect((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'fragile']))->eval($tagged))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'doesntHave', 'value' => 'oversize']))->eval($tagged))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'oversize']))->eval($tagged))->toBeFalse(); }); test('flow logic combines conditions with and or not and if semantics', function () { diff --git a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php index 5a754f4fe..6dfc6b0ad 100644 --- a/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php +++ b/server/tests/Unit/Models/OrderPurchaseAndDriversTest.php @@ -2,6 +2,7 @@ use Fleetbase\FleetOps\Models\Driver; use Fleetbase\FleetOps\Models\Order; +use Fleetbase\FleetOps\Models\OrderConfig; use Fleetbase\FleetOps\Models\Place; use Fleetbase\LaravelMysqlSpatial\Types\Point; use Illuminate\Database\ConnectionResolver; @@ -60,6 +61,7 @@ public function __call($method, $arguments) 'transactions' => ['uuid', 'public_id', 'company_uuid', 'customer_uuid', 'customer_type', 'subject_uuid', 'subject_type', 'context_uuid', 'context_type', 'gateway_transaction_id', 'gateway', 'amount', 'currency', 'description', 'type', 'direction', 'status', 'settlement_status', 'voided_at', 'meta', '_key'], 'companies' => ['uuid', 'public_id', 'name', 'currency', 'country'], 'drivers' => ['uuid', 'public_id', 'company_uuid', 'user_uuid', 'status', 'online', 'location', 'current_job_uuid', 'vehicle_uuid'], + 'order_configs' => ['uuid', 'public_id', 'company_uuid', 'key', 'name', 'flow', 'meta', 'policies', 'triggers'], 'users' => ['uuid', 'public_id', 'company_uuid', 'name'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid'], 'payloads' => ['uuid', 'public_id', 'company_uuid', 'pickup_uuid', 'dropoff_uuid', 'current_waypoint_uuid', 'meta'], @@ -174,7 +176,8 @@ function fleetopsOrderPurchaseOrder(): Order $connection->table('users')->insert(['uuid' => 'user-1', 'company_uuid' => 'company-1']); $connection->table('company_users')->insert(['uuid' => 'cu-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1']); $connection->table('drivers')->insert(['uuid' => 'driver-1', 'company_uuid' => 'company-1', 'user_uuid' => 'user-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); - // On another company's books, or busy with an order still under way: neither is offered this one. + // On another company's books: never offered this one. Busy with an order still under way: + // offered unless the order's config excludes busy drivers. $connection->table('drivers')->insert(['uuid' => 'driver-other', 'company_uuid' => 'company-2', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)']); $connection->table('drivers')->insert(['uuid' => 'driver-busy', 'company_uuid' => 'company-1', 'status' => 'available', 'online' => 1, 'location' => 'POINT(1 1)', 'current_job_uuid' => 'order-busy']); $connection->table('orders')->insert(['uuid' => 'order-busy', 'company_uuid' => 'company-1', 'status' => 'started']); @@ -188,5 +191,12 @@ function fleetopsOrderPurchaseOrder(): Order $payload->setRelation('waypoints', collect()); $order->setRelation('payload', $payload); + expect($order->findClosestDrivers())->toHaveCount(2); + + $config = new OrderConfig(); + $config->setRawAttributes(['uuid' => 'config-1', 'company_uuid' => 'company-1', 'policies' => json_encode(['dispatch' => ['matching' => ['exclude_busy_drivers' => true]]])], true); + $order->order_config_uuid = 'config-1'; + $order->setRelation('orderConfig', $config); + expect($order->findClosestDrivers())->toHaveCount(1); }); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php new file mode 100644 index 000000000..df9dc7298 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigAuthorizeTransitionTest.php @@ -0,0 +1,111 @@ +setRawAttributes(array_merge(['uuid' => 'order-1', 'status' => $status], $attributes), true); + + return $order; +} + +function orderConfigTransitionConfig(array $meta = [], ?array $flow = null): OrderConfig +{ + return new OrderConfig(['flow' => $flow ?? OrderConfigTemplates::attributes('transport')['flow'], 'meta' => $meta]); +} + +test('a finished order takes no more activities, unless an operator corrects it', function () { + $config = orderConfigTransitionConfig(); + $activity = new Activity(['code' => 'started', 'status' => 'Order Started']); + + [$kept, $refused] = $config->authorizeTransition(orderConfigTransitionOrder('completed'), $activity); + [, $canceled] = $config->authorizeTransition(orderConfigTransitionOrder('canceled'), $activity); + [, $corrected] = $config->authorizeTransition(orderConfigTransitionOrder('completed'), $activity, null, false, true); + [, $live] = $config->authorizeTransition(orderConfigTransitionOrder('dispatched'), $activity); + + expect($refused)->toBe('This order has already finished.') + ->and($kept)->toBe($activity) + ->and($canceled)->toBe('This order has already finished.') + ->and($corrected)->toBeNull() + ->and($live)->toBeNull(); +}); + +test('a config\'s own terminal activities end its orders too', function () { + $passenger = new OrderConfig(OrderConfigTemplates::attributes('passenger')); + + [, $noShow] = $passenger->authorizeTransition(orderConfigTransitionOrder('no_show'), new Activity(['code' => 'in_progress'])); + [, $fixed] = $passenger->authorizeTransition(orderConfigTransitionOrder('no_show'), new Activity(['code' => 'in_progress']), null, false, true); + + expect($noShow)->toBe('This order has already finished.') + // Correcting a finished order still follows strict transitions: nothing follows no_show. + ->and($fixed)->toBe('This activity is not a permitted next step for the order.'); +}); + +test('strict transitions use the config\'s own activity and refuse anything that is not a next step', function () { + $passenger = new OrderConfig(OrderConfigTemplates::attributes('passenger')); + $sent = new Activity(['code' => 'arrived', 'status' => 'Made up by the client', 'details' => 'Ignored', 'require_pod' => false]); + + [$applied, $allowed] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), $sent); + [, $skipped] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['code' => 'completed'])); + [, $unknown] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['code' => 'teleported'])); + [, $noCode] = $passenger->authorizeTransition(orderConfigTransitionOrder('started'), new Activity(['status' => 'Something'])); + + // Without strict transitions any activity is applied as sent. + $loose = orderConfigTransitionConfig(); + $free = new Activity(['code' => 'teleported', 'status' => 'Anything']); + [$looseApplied, $looseOk] = $loose->authorizeTransition(orderConfigTransitionOrder('created'), $free); + + expect($allowed)->toBeNull() + ->and($applied)->not->toBe($sent) + ->and($applied->get('status'))->toBe('Driver has arrived') + ->and($applied->get('details'))->toBe('The driver is waiting at the pickup.') + ->and($skipped)->toBe('This activity is not a permitted next step for the order.') + ->and($unknown)->toBe('This activity is not a permitted next step for the order.') + ->and($noCode)->toBe('This activity is not a permitted next step for the order.') + ->and($looseOk)->toBeNull() + ->and($looseApplied)->toBe($free); +}); + +test('a config whose lifecycle turns dispatch off refuses the dispatched activity', function () { + $dispatched = new Activity(['code' => 'dispatched']); + + [, $off] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => false]])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $offText] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => 'false']])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $on] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => true]])->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $default] = orderConfigTransitionConfig()->authorizeTransition(orderConfigTransitionOrder('created'), $dispatched); + [, $started] = orderConfigTransitionConfig(['lifecycle' => ['dispatch' => false]])->authorizeTransition(orderConfigTransitionOrder('created'), new Activity(['code' => 'started'])); + + expect($off)->toBe('Orders of this type are not dispatched.') + ->and($offText)->toBe('Orders of this type are not dispatched.') + ->and($on)->toBeNull() + ->and($default)->toBeNull() + ->and($started)->toBeNull(); +}); + +test('an activity that needs proof of delivery needs proof, unless it is bypassed', function () { + $config = orderConfigTransitionConfig(); + $needsPod = new Activity(['code' => 'dropped', 'require_pod' => true]); + $completes = new Activity(['code' => 'completed', 'complete' => true]); + $refusal = 'Proof of delivery is required for this activity or must be explicitly bypassed.'; + + [, $withoutProof] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod); + [, $withProof] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod, 'proof-1'); + [, $bypassed] = $config->authorizeTransition(orderConfigTransitionOrder('started'), $needsPod, null, true); + [, $podOrder] = $config->authorizeTransition(orderConfigTransitionOrder('started', ['pod_required' => 1]), $completes); + [, $plainOrder] = $config->authorizeTransition(orderConfigTransitionOrder('started', ['pod_required' => 0]), $completes); + + expect($withoutProof)->toBe($refusal) + ->and($withProof)->toBeNull() + ->and($bypassed)->toBeNull() + ->and($podOrder)->toBe($refusal) + ->and($plainOrder)->toBeNull(); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php new file mode 100644 index 000000000..c8707ff52 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php @@ -0,0 +1,147 @@ +values); } }; } }'); +} + +class OrderConfigPoliciesTestInvoicingPolicy extends Policy +{ + protected string $key = 'billing.invoicing'; + protected string $label = 'Invoicing'; + protected string $description = 'Send an invoice when the order completes.'; + protected array $defaults = ['auto_send' => false, 'note' => null, 'due_days' => 14]; + protected array $rules = ['note' => ['nullable', 'string'], 'due_days' => ['nullable', 'integer']]; +} + +function orderConfigPoliciesSetting(string $key, string $name): ?array +{ + $policy = collect(OrderConfigPolicies::describe())->firstWhere('key', $key); + + return collect($policy['settings'] ?? [])->firstWhere('name', $name); +} + +test('every policy has defaults: nothing a config does not ask for is switched on', function () { + expect(OrderConfigPolicies::defaults())->toBe([ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => false, 'strategy' => null, 'offer_timeout' => null, 'radius' => null, 'on_exhausted' => 'keep_open'], + 'matching' => ['vehicle_type' => false, 'exclude_busy_drivers' => false], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => [], 'require_quote' => false, 'require_settlement' => []], + 'cancellation' => ['enabled' => true, 'allowed_until' => null], + 'interactions' => ['chat' => false, 'rating' => false, 'share_tracking' => false], + ], + 'pricing' => ['reprice_on_completion' => false, 'metering_starts_at' => null], + ]) + ->and(array_keys(OrderConfigPolicies::all()))->toBe(['dispatch.adhoc', 'dispatch.matching', 'customer.ordering', 'customer.cancellation', 'customer.interactions', 'pricing']) + ->and(OrderConfigPolicies::get('pricing')->label())->toBe('Pricing') + ->and(OrderConfigPolicies::get('nope'))->toBeNull(); +}); + +test('resolving stored policies fills in each missing setting and keeps policies nobody registered', function () { + $resolved = OrderConfigPolicies::resolve([ + 'dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'on_exhausted' => 'cancel']], + 'pricing' => 'not a policy', + 'billing' => ['invoicing' => ['auto_send' => true]], + ]); + + expect(OrderConfigPolicies::resolve(null))->toBe(OrderConfigPolicies::defaults()) + ->and(OrderConfigPolicies::resolve([]))->toBe(OrderConfigPolicies::defaults()) + ->and($resolved['dispatch']['adhoc'])->toBe(['customer_orders' => false, 'strategy' => 'broadcast', 'offer_timeout' => null, 'radius' => null, 'on_exhausted' => 'cancel']) + ->and($resolved['dispatch']['matching'])->toBe(['vehicle_type' => false, 'exclude_busy_drivers' => false]) + ->and($resolved['pricing'])->toBe(['reprice_on_completion' => false, 'metering_starts_at' => null]) + ->and($resolved['billing'])->toBe(['invoicing' => ['auto_send' => true]]); +}); + +test('validation rules sit under the prefix, one set per policy and per setting', function () { + $rules = OrderConfigPolicies::rules(); + $custom = OrderConfigPolicies::rules('config.policies'); + + expect($rules['policies'])->toBe(['nullable', 'array']) + ->and($rules['policies.dispatch.adhoc'])->toBe(['nullable', 'array']) + ->and($rules['policies.dispatch.adhoc.customer_orders'])->toBe(['nullable', 'boolean']) + ->and($rules['policies.dispatch.adhoc.offer_timeout'])->toBe(['nullable', 'integer', 'min:10', 'max:120']) + ->and($rules['policies.customer.ordering.payment_methods.*'])->toBe(['string', 'max:32']) + ->and((string) $rules['policies.dispatch.adhoc.on_exhausted'][1])->toBe('in:keep_open,cancel') + ->and((string) $rules['policies.dispatch.adhoc.strategy'][2])->toContain('sequential', 'broadcast') + ->and($rules['policies.pricing.metering_starts_at'])->toBe(['nullable', 'string', 'max:64']) + ->and(array_keys($custom))->toContain('config.policies', 'config.policies.customer.interactions.chat') + ->and(array_filter(array_keys($custom), fn ($key) => !str_starts_with($key, 'config.policies')))->toBe([]); +}); + +test('policies describe each setting\'s type, default and choices for people configuring them', function () { + $adhoc = collect(OrderConfigPolicies::describe())->firstWhere('key', 'dispatch.adhoc'); + + expect($adhoc['label'])->toBe('Adhoc dispatch') + ->and($adhoc['defaults']['on_exhausted'])->toBe('keep_open') + ->and(array_column($adhoc['settings'], 'type', 'name'))->toBe([ + 'customer_orders' => 'boolean', + 'strategy' => 'choice', + 'offer_timeout' => 'number', + 'radius' => 'number', + 'on_exhausted' => 'choice', + ]) + ->and(array_column(orderConfigPoliciesSetting('dispatch.adhoc', 'strategy')['choices'], 'value'))->toContain('sequential', 'broadcast') + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'on_exhausted')['choices'])->toBe([ + ['value' => 'keep_open', 'label' => 'Keep the order open for the operator'], + ['value' => 'cancel', 'label' => 'Cancel the order'], + ]) + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'customer_orders'))->toBe(['name' => 'customer_orders', 'type' => 'boolean', 'default' => false, 'choices' => null]) + ->and(orderConfigPoliciesSetting('customer.ordering', 'payment_methods')['type'])->toBe('list') + ->and(orderConfigPoliciesSetting('customer.ordering', 'require_settlement')['type'])->toBe('list') + // An activity setting is a choice among the config's own activities. + ->and(orderConfigPoliciesSetting('customer.cancellation', 'allowed_until'))->toBe(['name' => 'allowed_until', 'type' => 'choice', 'default' => null, 'choices' => 'activity']) + ->and(orderConfigPoliciesSetting('pricing', 'metering_starts_at')['choices'])->toBe('activity'); +}); + +test('a config\'s policy reads one setting or a whole policy, with defaults and a fallback', function () { + $config = new OrderConfig(['policies' => ['dispatch' => ['adhoc' => ['strategy' => 'broadcast']]]]); + $empty = new OrderConfig(); + + expect($config->policy('dispatch.adhoc.strategy'))->toBe('broadcast') + ->and($config->policy('dispatch.adhoc.on_exhausted'))->toBe('keep_open') + ->and($config->policy('dispatch.matching'))->toBe(['vehicle_type' => false, 'exclude_busy_drivers' => false]) + ->and($config->policy('dispatch.adhoc.offer_timeout', 30))->toBe(30) + ->and($config->policy('nothing.here', 'fallback'))->toBe('fallback') + ->and($empty->resolvedPolicies())->toBe(OrderConfigPolicies::defaults()) + ->and($empty->policy('customer.interactions.chat'))->toBeFalse(); +}); + +test('a config drops an adhoc strategy that is not registered and keeps the offer timeout in range', function () { + $normalized = function (?array $policies) { + $config = new OrderConfig(); + $config->policies = $policies; + $config->normalizePolicies(); + + return $config->policies; + }; + + expect($normalized(['dispatch' => ['adhoc' => ['strategy' => 'lottery', 'offer_timeout' => 900]]]))->toBe(['dispatch' => ['adhoc' => ['strategy' => null, 'offer_timeout' => 120]]]) + ->and($normalized(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => '3']]]))->toBe(['dispatch' => ['adhoc' => ['strategy' => 'broadcast', 'offer_timeout' => 10]]]) + ->and($normalized(['dispatch' => ['adhoc' => ['offer_timeout' => '']]]))->toBe(['dispatch' => ['adhoc' => ['offer_timeout' => '']]]) + ->and($normalized(['pricing' => ['reprice_on_completion' => true]]))->toBe(['pricing' => ['reprice_on_completion' => true]]) + ->and($normalized(null))->toBeNull(); +}); + +test('extensions register their own policies, and only real policies', function () { + OrderConfigPolicies::register(OrderConfigPoliciesTestInvoicingPolicy::class); + + expect(OrderConfigPolicies::get('billing.invoicing'))->toBeInstanceOf(OrderConfigPoliciesTestInvoicingPolicy::class) + ->and(OrderConfigPolicies::defaults()['billing']['invoicing'])->toBe(['auto_send' => false, 'note' => null, 'due_days' => 14]) + ->and(OrderConfigPolicies::resolve([])['billing']['invoicing']['due_days'])->toBe(14) + ->and(OrderConfigPolicies::rules()['policies.billing.invoicing.due_days'])->toBe(['nullable', 'integer']) + ->and(orderConfigPoliciesSetting('billing.invoicing', 'auto_send')['type'])->toBe('boolean') + ->and(orderConfigPoliciesSetting('billing.invoicing', 'note')['type'])->toBe('text') + ->and(orderConfigPoliciesSetting('billing.invoicing', 'due_days')['type'])->toBe('number') + ->and(fn () => OrderConfigPolicies::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php new file mode 100644 index 000000000..7d6491475 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php @@ -0,0 +1,166 @@ + $code, + 'code' => $code, + 'color' => '#1f2937', + 'logic' => [], + 'events' => [], + 'status' => $status, + 'actions' => [], + 'details' => $details, + 'options' => [], + 'complete' => $complete, + 'entities' => [], + 'sequence' => 0, + 'activities' => $next, + 'pod_method' => 'scan', + 'require_pod' => false, + ]; +} + +/** The flow without the generated `internalId` of each activity. */ +function orderConfigTemplatesFlow(array $flow): array +{ + return array_map(fn ($activity) => Arr::except($activity, 'internalId'), $flow); +} + +test('the registry describes its templates and refuses unknown ones', function () { + expect(OrderConfigTemplates::describe())->toBe([ + ['key' => 'transport', 'name' => 'Transport', 'description' => 'Default order configuration for transport'], + ['key' => 'passenger', 'name' => 'Passenger', 'description' => (new PassengerTemplate())->description()], + ]) + ->and(OrderConfigTemplates::has('passenger'))->toBeTrue() + ->and(OrderConfigTemplates::has('limousine'))->toBeFalse() + ->and(OrderConfigTemplates::has(null))->toBeFalse() + ->and(OrderConfigTemplates::get('transport'))->toBeInstanceOf(TransportTemplate::class) + ->and(OrderConfigTemplates::get('limousine'))->toBeNull() + ->and(fn () => OrderConfigTemplates::attributes('limousine'))->toThrow(InvalidArgumentException::class) + ->and(fn () => OrderConfigTemplates::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('the transport template is the default transport config it replaced', function () { + $attributes = OrderConfigTemplates::attributes('transport'); + + expect(Arr::except($attributes, 'flow'))->toBe([ + 'name' => 'Transport', + 'key' => 'transport', + 'namespace' => 'system:order-config:transport', + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + 'description' => 'Default order configuration for transport', + 'tags' => ['transport', 'delivery'], + 'entities' => [], + 'meta' => [], + ]) + ->and(array_keys($attributes['flow']))->toBe(['created', 'enroute', 'started', 'completed', 'dispatched']) + ->and(orderConfigTemplatesFlow($attributes['flow']))->toBe([ + 'created' => orderConfigTemplatesActivity('created', 'Order Created', 'New order was created.', ['dispatched']), + 'enroute' => orderConfigTemplatesActivity('enroute', 'Driver Enroute', 'Driver is en-route.', ['completed']), + 'started' => orderConfigTemplatesActivity('started', 'Order Started', 'Order has been started', ['enroute']), + 'completed' => orderConfigTemplatesActivity('completed', 'Order Completed', 'Order has been completed.', [], true), + 'dispatched' => orderConfigTemplatesActivity('dispatched', 'Order Dispatched', 'Order has been dispatched.', ['started']), + ]) + ->and(collect($attributes['flow'])->every(fn ($activity) => Str::isUuid($activity['internalId'])))->toBeTrue() + ->and((new TransportTemplate())->customFields())->toBe([]); +}); + +test('the passenger template is a strict flow ending in completed, canceled or no-show', function () { + $attributes = OrderConfigTemplates::attributes('passenger'); + $flow = $attributes['flow']; + + expect(Arr::only($attributes, ['name', 'key', 'namespace', 'core_service', 'status', 'version', 'tags', 'entities']))->toBe([ + 'name' => 'Passenger', + 'key' => 'passenger', + 'namespace' => 'system:order-config:passenger', + 'core_service' => 1, + 'status' => 'private', + 'version' => '0.0.1', + 'tags' => ['passenger', 'on-demand'], + 'entities' => [], + ]) + ->and($attributes['meta'])->toBe(['lifecycle' => ['initial' => 'created', 'completed' => 'completed', 'canceled' => 'canceled', 'terminal' => ['no_show'], 'strict_transitions' => true]]) + ->and(array_map(fn ($activity) => $activity['activities'], $flow))->toBe([ + 'created' => ['dispatched'], + 'dispatched' => ['started'], + 'started' => ['arrived'], + 'arrived' => ['in_progress', 'no_show'], + 'in_progress' => ['completed'], + 'completed' => [], + 'no_show' => [], + ]) + ->and(array_keys(array_filter($flow, fn ($activity) => $activity['complete'])))->toBe(['completed']) + ->and(array_map(fn ($activity) => array_column($activity['actions'], 'action'), $flow))->toBe([ + 'created' => [], + 'dispatched' => [], + 'started' => ['notify_customer', 'open_chat'], + 'arrived' => ['notify_customer'], + 'in_progress' => ['notify_customer'], + 'completed' => ['notify_customer', 'close_chat', 'send_invoice'], + 'no_show' => ['close_chat'], + ]) + ->and($flow['started']['actions'][0]['params'])->toBe(['title' => 'Your driver is on the way', 'message' => '{driver.first_name} accepted your trip.']); +}); + +test('the passenger template\'s policies offer orders one driver at a time, by vehicle type, and price them from the trip', function () { + $policies = OrderConfigTemplates::attributes('passenger')['policies']; + + expect($policies)->toBe([ + 'dispatch' => [ + 'adhoc' => ['customer_orders' => true, 'strategy' => 'sequential', 'offer_timeout' => 20, 'on_exhausted' => 'cancel'], + 'matching' => ['vehicle_type' => true, 'exclude_busy_drivers' => true], + ], + 'customer' => [ + 'ordering' => ['payment_methods' => ['cash', 'card'], 'require_quote' => true, 'require_settlement' => ['card']], + 'cancellation' => ['enabled' => true, 'allowed_until' => 'in_progress'], + 'interactions' => ['chat' => true, 'rating' => true, 'share_tracking' => true], + ], + 'pricing' => ['reprice_on_completion' => true, 'metering_starts_at' => 'in_progress'], + ]) + // Every setting it leaves out takes the policy's default. + ->and(OrderConfigPolicies::resolve($policies)['dispatch']['adhoc']['radius'])->toBeNull() + ->and(array_keys(OrderConfigPolicies::resolve($policies)))->toBe(['dispatch', 'customer', 'pricing']); +}); + +test('the passenger template\'s triggers tell the customer as the driver nears the pickup, when nobody is found, and when canceled', function () { + $triggers = OrderConfigTemplates::attributes('passenger')['triggers']; + + expect(array_column($triggers, 'event'))->toBe(['driver.approaching', 'dispatch.offer_exhausted', 'order.canceled', 'order.canceled']) + ->and(array_column($triggers, 'action'))->toBe(['notify_customer', 'notify_customer', 'notify_customer', 'close_chat']) + ->and($triggers[0]['options'])->toBe(['target' => 'pickup', 'distance' => 400]) + ->and($triggers[0]['when'])->toBe([['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => 'started']]]]) + ->and($triggers[0]['params'])->toBe(['title' => 'Your driver is almost there', 'message' => '{driver.first_name} is about a minute away.']) + ->and($triggers[1]['params']['title'])->toBe('No driver found') + // The cancellation notice is skipped when the customer was already told nobody was found. + ->and($triggers[2]['when'])->toBe([['type' => 'and', 'conditions' => [['field' => 'dispatch_outcome', 'operator' => 'notEqual', 'value' => 'no_driver_found']]]]); +}); + +test('the passenger template asks how many people are travelling', function () { + expect((new PassengerTemplate())->customFields())->toBe([[ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'default_value' => '1', + 'required' => false, + 'editable' => true, + 'validation_rules' => ['nullable', 'integer', 'min:1', 'max:50'], + 'help_text' => 'How many people are travelling.', + 'order' => 0, + ]]); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php new file mode 100644 index 000000000..5ea7256e6 --- /dev/null +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTriggersTest.php @@ -0,0 +1,244 @@ + 'Anything.']; + + public function handle(Order $order, array $params = [], array $context = []): void + { + OrderConfigTriggersTestRecorder::$ran[] = [$order->uuid, $params, $context]; + } +} + +class OrderConfigTriggersTestFailingAction extends Action +{ + protected string $name = 'explode'; + protected string $label = 'Explode'; + protected string $description = 'Always fails.'; + + public function handle(Order $order, array $params = [], array $context = []): void + { + throw new RuntimeException('boom'); + } +} + +function orderConfigTriggersBoot(): void +{ + app()->instance('log', new class { + public array $warnings = []; + + public function warning($message, array $context = []) + { + $this->warnings[] = $message; + } + + public function __call($method, $arguments) + { + return null; + } + }); + Illuminate\Support\Facades\Log::clearResolvedInstance('log'); + + OrderConfigActions::register(OrderConfigTriggersTestAction::class); + OrderConfigActions::register(OrderConfigTriggersTestFailingAction::class); + OrderConfigTriggers::$runImmediately = true; + OrderConfigTriggersTestRecorder::$ran = []; + OrderConfigTriggersTestRecorder::$queued = []; +} + +/** An order with its config already loaded, so triggers are read without a database. */ +function orderConfigTriggersOrder(array $triggers, array $attributes = []): Order +{ + $config = new OrderConfig(['triggers' => $triggers]); + $config->setAttribute('uuid', 'config-1'); + + $order = new Order(); + $order->setRawAttributes(array_merge(['uuid' => 'order-1', 'public_id' => 'order_one', 'order_config_uuid' => 'config-1', 'status' => 'started'], $attributes), true); + $order->setRelation('orderConfig', $config); + + return $order; +} + +function orderConfigTriggersStatusIs(string $status): array +{ + return [['type' => 'and', 'conditions' => [['field' => 'status', 'operator' => 'equal', 'value' => $status]]]]; +} + +test('an event runs the config\'s registered actions for that event, with their params and the event', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([ + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'record', 'params' => ['note' => 'first']], + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'send_invoice'], + ['event' => OrderConfigTriggers::ORDER_COMPLETED, 'action' => 'record', 'params' => 'not a list'], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record'], + ['event' => OrderConfigTriggers::ORDER_COMPLETED], + 'not a trigger', + ]); + + $ran = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED, ['source' => 'test']); + + expect($ran)->toBe(2) + ->and(OrderConfigTriggersTestRecorder::$ran)->toBe([ + ['order-1', ['note' => 'first'], ['event' => 'order.completed', 'source' => 'test']], + ['order-1', [], ['event' => 'order.completed', 'source' => 'test']], + ]) + ->and(OrderConfigTriggers::forEvent($order, OrderConfigTriggers::ORDER_CANCELED))->toHaveCount(1) + ->and(OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED))->toBe(0) + ->and(OrderConfigTriggers::EVENTS)->toBe(['order.created', 'order.completed', 'order.canceled', 'dispatch.offer_exhausted', 'driver.approaching']); +}); + +test('a trigger runs only when every one of its conditions passes', function () { + orderConfigTriggersBoot(); + $triggers = [ + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'while started'], 'when' => orderConfigTriggersStatusIs('started')], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'while arrived'], 'when' => orderConfigTriggersStatusIs('arrived')], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'both'], 'when' => [...orderConfigTriggersStatusIs('started'), ...orderConfigTriggersStatusIs('arrived')]], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'unreadable'], 'when' => [['type' => 'sometimes', 'conditions' => []]]], + ['event' => OrderConfigTriggers::ORDER_CANCELED, 'action' => 'record', 'params' => ['note' => 'empty'], 'when' => []], + ]; + + $ran = OrderConfigTriggers::fire(orderConfigTriggersOrder($triggers), OrderConfigTriggers::ORDER_CANCELED); + + expect($ran)->toBe(2) + ->and(array_column(array_column(OrderConfigTriggersTestRecorder::$ran, 1), 'note'))->toBe(['while started', 'empty']) + ->and(app('log')->warnings)->toContain('Skipped an order config trigger whose conditions could not be read') + ->and(OrderConfigTriggers::passes(orderConfigTriggersOrder([]), ['when' => 'not a list']))->toBeTrue(); +}); + +test('reaching an activity runs that activity\'s actions, with the activity in their context', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([]); + $activity = [ + 'code' => 'arrived', + 'status' => 'Driver has arrived', + 'details' => 'Waiting at the pickup.', + 'actions' => [['action' => 'record', 'params' => ['note' => 'arrived']], ['action' => 'record', 'when' => orderConfigTriggersStatusIs('completed')]], + ]; + + expect(OrderConfigTriggers::activity($order, $activity))->toBe(1) + ->and(OrderConfigTriggersTestRecorder::$ran)->toBe([ + ['order-1', ['note' => 'arrived'], ['event' => 'order.activity', 'activity' => ['code' => 'arrived', 'status' => 'Driver has arrived', 'details' => 'Waiting at the pickup.']]], + ]) + ->and(OrderConfigTriggers::activity($order, null))->toBe(0) + ->and(OrderConfigTriggers::activity($order, new Fleetbase\FleetOps\Flow\Activity(['code' => 'quiet'])))->toBe(0); +}); + +test('an order without a config of its own runs no triggers', function () { + orderConfigTriggersBoot(); + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-2', 'order_config_uuid' => null, 'status' => 'completed'], true); + + expect($order->currentConfig())->toBeNull() + ->and(OrderConfigTriggers::forEvent($order, OrderConfigTriggers::ORDER_COMPLETED))->toBe([]) + ->and(OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_COMPLETED))->toBe(0) + ->and(OrderConfigTriggers::driverMoved(new Driver(), $order))->toBe(0) + ->and(OrderConfigTriggers::driverMoved(new Driver(), null))->toBe(0); +}); + +test('actions are queued unless asked to run now, and a failing action is logged and not counted', function () { + orderConfigTriggersBoot(); + $order = orderConfigTriggersOrder([ + ['event' => OrderConfigTriggers::ORDER_CREATED, 'action' => 'record', 'params' => ['note' => 'later']], + ['event' => OrderConfigTriggers::ORDER_CREATED, 'action' => 'explode'], + ]); + + $failed = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); + + OrderConfigTriggers::$runImmediately = false; + $queued = OrderConfigTriggers::fire($order, OrderConfigTriggers::ORDER_CREATED); + OrderConfigTriggers::$runImmediately = true; + $job = OrderConfigTriggersTestRecorder::$queued[0]; + + expect($failed)->toBe(1) + ->and(app('log')->warnings)->toBe(['An order config action failed']) + ->and($queued)->toBe(2) + ->and(OrderConfigTriggersTestRecorder::$queued)->toHaveCount(2) + ->and($job)->toBeInstanceOf(RunOrderConfigAction::class) + ->and([$job->orderUuid, $job->action, $job->params, $job->context])->toBe(['order-1', 'record', ['note' => 'later'], ['event' => 'order.created']]) + ->and(OrderConfigTriggersTestRecorder::$queued[1]->action)->toBe('explode') + ->and(OrderConfigTriggersTestRecorder::$ran)->toHaveCount(1); +}); + +test('the action registry lists the built-in actions and takes only real actions', function () { + orderConfigTriggersBoot(); + $described = collect(OrderConfigActions::describe())->keyBy('name'); + + expect(OrderConfigActions::names())->toContain('notify_customer', 'notify_driver', 'open_chat', 'close_chat', 'set_meta', 'cancel', 'record') + ->and(OrderConfigActions::has('notify_customer'))->toBeTrue() + ->and(OrderConfigActions::has('send_invoice'))->toBeFalse() + ->and(OrderConfigActions::has(null))->toBeFalse() + ->and(OrderConfigActions::get('send_invoice'))->toBeNull() + ->and(OrderConfigActions::get('record'))->toBeInstanceOf(OrderConfigTriggersTestAction::class) + ->and($described['notify_customer']['label'])->toBe('Notify customer') + ->and(array_keys($described['notify_customer']['parameters']))->toBe(['title', 'message']) + ->and(array_keys($described['set_meta']['parameters']))->toBe(['key', 'value']) + ->and($described['record'])->toBe(['name' => 'record', 'label' => 'Record', 'description' => 'Records that it ran.', 'parameters' => ['note' => 'Anything.']]) + ->and(fn () => OrderConfigActions::register(stdClass::class))->toThrow(InvalidArgumentException::class); +}); + +test('placeholders are filled from the order, its driver, customer and the activity', function () { + $order = new Order(); + $order->setRawAttributes(['uuid' => 'order-1', 'public_id' => 'order_one', 'status' => 'arrived'], true); + $order->setRelation('driverAssigned', new class extends Driver { + public function getNameAttribute() + { + return 'Chen Wei Tan'; + } + }); + $customer = new Contact(); + $customer->setRawAttributes(['name' => 'Sam Lee'], true); + $order->setRelation('customer', $customer); + $tracking = new TrackingNumber(); + $tracking->setRawAttributes(['tracking_number' => 'TRK1'], true); + $order->setRelation('trackingNumber', $tracking); + $context = ['activity' => ['status' => 'Driver has arrived', 'details' => 'Waiting.']]; + + $everything = Action::render('{driver.name}|{driver.first_name}|{customer.name}|{order.id}|{order.tracking_number}|{order.status}|{activity.status}|{activity.details}', $order, $context); + + $nobody = new Order(); + $nobody->setRawAttributes(['public_id' => 'order_two', 'driver_assigned_uuid' => null], true); + $nobody->setRelation('driverAssigned', null); + $nobody->setRelation('customer', null); + $nobody->setRelation('trackingNumber', null); + + expect($everything)->toBe('Chen Wei Tan|Chen|Sam Lee|order_one|TRK1|arrived|Driver has arrived|Waiting.') + ->and(Action::render('{ Driver.First_Name } is here', $order))->toBe('Chen is here') + ->and(Action::render('Hello {unknown.thing} there {activity.status}', $order))->toBe('Hello there') + ->and(Action::render(null, $order))->toBe('') + ->and(Action::render('', $order))->toBe('') + ->and(Action::render('{driver.first_name} accepted {order.id} for {customer.name}{order.tracking_number}', $nobody))->toBe('accepted order_two for') + ->and(Action::driverName($nobody))->toBeNull(); + + // Without the relation loaded and no driver assigned, nothing is looked up. + $unassigned = new Order(); + $unassigned->setRawAttributes(['driver_assigned_uuid' => null], true); + expect(Action::driverName($unassigned))->toBeNull(); +}); diff --git a/translations/en-us.yaml b/translations/en-us.yaml index 6c6b9e761..1f1ea562b 100644 --- a/translations/en-us.yaml +++ b/translations/en-us.yaml @@ -1259,24 +1259,47 @@ order-config-manager: uninstall-order-config: Uninstall Configuration uninstall-order-config-success-message: Extension {extensionName} uninstalled. select-order-config-to-start: Select or create an order config to start. + template: Start From + template-help-text: A ready-made configuration for one kind of operation, with its flow, policies and triggers. Change anything once it is created. + blank-template: Blank configuration tabs: details: Details custom-fields: Custom Fields activity-flow: Activity Flow lifecycle: Lifecycle entities: Entities + policies: Policies + triggers: Triggers + policies: + description: Policies decide how orders of this configuration behave. A setting you leave at its default follows Fleet-Ops' default or your company's dispatch settings. + default: Default + add-value: Add a value + use-default: Use the default + triggers: + title: Triggers + description: What this configuration does when something happens to its orders, such as notifying the customer when the driver arrives. + when: When + do: Do + add: Add Trigger + remove: Remove trigger + empty: No triggers yet. + conditions: This trigger runs only when its {count, plural, one {condition passes} other {# conditions pass}}. + reaches-activity: 'The order reaches: {activity}' + approaching-target: Approaching + approaching-distance: Within (meters) + pickup: Pickup + dropoff: Drop-off + events: + order: + created: The order is created + completed: The order is completed + canceled: The order is canceled + dispatch: + offer_exhausted: No driver accepted the offer + driver: + approaching: The driver is approaching details: details: Details - adhoc-dispatch: Adhoc Dispatch - adhoc-strategy: How Adhoc Orders Are Offered - adhoc-strategy-help-text: How orders on this config without an assigned driver are offered to drivers nearby. - adhoc-offer-timeout: Offer Time (seconds) - adhoc-offer-timeout-help-text: How long each driver has to accept when orders are offered one driver at a time. - company-default: Company default - customer-orders-adhoc: Customers' Orders Go to Nearby Drivers - customer-orders-adhoc-help-text: Orders customers place on this config are offered to drivers nearby instead of waiting for dispatch. - match-vehicle-type: Match Customers' Orders by Vehicle Type - match-vehicle-type-help-text: Customers choose a fare, and their order only goes to drivers whose vehicle type matches it. name: Name description: Description tags: Tags From 6de16d2766e8b0ef64c1d0b0c5ca6e1df9cc4bf1 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 9 Nov 2026 13:29:18 +0800 Subject: [PATCH 20/29] fix(orders): store API custom field values the way the console does, with their value type setCustomFieldValue() leaves value_type empty, which the column refuses; syncCustomFieldValues() takes the field's type. Found running a booking end to end on a local stack. --- server/src/Support/OrderCustomFields.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/server/src/Support/OrderCustomFields.php b/server/src/Support/OrderCustomFields.php index 1ea951f34..871b3ca62 100644 --- a/server/src/Support/OrderCustomFields.php +++ b/server/src/Support/OrderCustomFields.php @@ -54,16 +54,22 @@ public static function apply(Order $order, array $values): int return 0; } - $stored = 0; + // The same path the console saves custom field values through, with each value's type. + $rows = []; foreach ($order->customFields()->get() as $field) { $value = static::valueFor($field, $values); if ($value !== null) { - $order->setCustomFieldValue($field, $value); - $stored++; + $rows[] = ['custom_field_uuid' => $field->uuid, 'value' => $value, 'value_type' => $field->type ?: 'text']; } } - return $stored; + if ($rows === []) { + return 0; + } + + $result = $order->syncCustomFieldValues($rows); + + return (int) ($result['created'] ?? 0) + (int) ($result['updated'] ?? 0); } /** From 890a550e7ee93673b89b2eeb9268306d8f690ca5 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 9 Nov 2026 14:13:14 +0800 Subject: [PATCH 21/29] fix(order-configs): return policies and triggers to the console The internal order config resource lists its fields, and left out policies and triggers, so the console's Policies and Triggers tabs saw only defaults. Found running the console against a local stack. --- server/src/Http/Resources/Internal/v1/OrderConfig.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/src/Http/Resources/Internal/v1/OrderConfig.php b/server/src/Http/Resources/Internal/v1/OrderConfig.php index 2f001484c..c8741653c 100644 --- a/server/src/Http/Resources/Internal/v1/OrderConfig.php +++ b/server/src/Http/Resources/Internal/v1/OrderConfig.php @@ -32,6 +32,9 @@ public function toArray($request): array 'entities' => $this->entities ?? [], 'tags' => $this->tags ?? [], 'meta' => $this->meta ?? [], + // As stored, for editing: settings left out take their defaults on the server. + 'policies' => $this->policies ?? (object) [], + 'triggers' => $this->triggers ?? [], 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'deleted_at' => $this->deleted_at, From 47341cc408e9d259922b49c238d870c265ff1710 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 9 Nov 2026 14:15:23 +0800 Subject: [PATCH 22/29] fix(order-configs): select a config made from a template once the list reloads --- addon/components/order-config-manager.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/addon/components/order-config-manager.js b/addon/components/order-config-manager.js index a3ab01017..538a74133 100644 --- a/addon/components/order-config-manager.js +++ b/addon/components/order-config-manager.js @@ -251,8 +251,8 @@ export default class OrderConfigManagerComponent extends Component { orderConfig.unloadRecord(); this.notifications.success(this.intl.t('order-config-manager.create-success-message')); this.loadOrderConfigs.perform({ - onAfter: () => { - const created = this.configs.find((config) => config.id === order_config?.id || config.public_id === order_config?.public_id); + onAfter: (configs = []) => { + const created = configs.find((config) => config.id === order_config?.uuid || config.public_id === order_config?.public_id); if (created) { this.selectConfig(created); } From f23a9756d094dcc361bcf1a99029f90dd5d37c06 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 9 Nov 2026 15:15:21 +0800 Subject: [PATCH 23/29] ci(contract): call the merged contract workflow on main with the l12 stack Remove the stack after this release ships. --- .github/workflows/postman.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/postman.yml b/.github/workflows/postman.yml index 157d770b0..aef7db2a2 100644 --- a/.github/workflows/postman.yml +++ b/.github/workflows/postman.yml @@ -27,9 +27,14 @@ permissions: jobs: contract: + # Laravel 12 release only. Remove `stack` once this release ships. The published image is + # Laravel 10 and its extensions require core-api 1.x, so this branch can only resolve + # against the whole Laravel 12 train: the `l12` stack builds the image from fleetbase's + # Laravel 12 branch and links core-api and every extension from their release branches. uses: fleetbase/fleetbase/.github/workflows/api-contract.yml@main with: collections: "Fleetbase API" + stack: l12 build-from-source: false # Without this the run tests the version of fleetbase/fleetops-api baked into the # published image, not the branch under review. The workflow checks this From bdcf29713210a7ada513c08d9297a5e3799976a3 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 01:41:38 +0800 Subject: [PATCH 24/29] test(customers): add driver_ratings to the customer helper seams schema CustomerController eager-loads driverRating on customer orders since the passenger rides work, so the hand-built SQLite schema needs the table. --- .../tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php | 1 + 1 file changed, 1 insertion(+) diff --git a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php index 59e65aa74..f4cd0a0c0 100644 --- a/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php +++ b/server/tests/Feature/Http/Api/CustomerControllerHelperSeamsTest.php @@ -229,6 +229,7 @@ public function __call($method, $arguments) 'companies' => ['uuid', 'public_id', 'name', 'country'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'proof_uuid', 'status', 'details', 'location', 'code', 'complete', '_key'], 'directives' => ['uuid', 'public_id', 'company_uuid', 'permission_uuid', 'key', 'rules', 'subject_type'], + 'driver_ratings' => ['uuid', '_key', 'company_uuid', 'order_uuid', 'driver_uuid', 'customer_uuid', 'customer_type', 'stars', 'comment'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { From bfe280132e752086f4428409381d8cd600855c16 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 01:58:14 +0800 Subject: [PATCH 25/29] test(orders): give the nearby filters order_configs fixture its policies column The adhoc strategy moved from order_configs.adhoc_strategy into the policies JSON in the order config policies refactor. --- .../tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php index 09a20f049..c26e8a5ea 100644 --- a/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerNearbyFiltersTest.php @@ -146,7 +146,7 @@ public function __call($method, $arguments) 'vendors' => ['uuid', 'public_id', 'internal_id', 'company_uuid', 'name'], 'integrated_vendors' => ['uuid', 'public_id', 'company_uuid', 'provider'], 'companies' => ['uuid', 'public_id', 'name', 'options'], - 'order_configs' => ['uuid', 'company_uuid', 'adhoc_strategy'], + 'order_configs' => ['uuid', 'company_uuid', 'policies'], 'order_offers' => ['uuid', 'order_uuid', 'driver_uuid', 'status', 'expires_at'], 'tracking_numbers' => ['uuid', 'public_id', 'company_uuid', 'tracking_number', 'owner_uuid', 'owner_type', 'status_uuid', '_key'], 'tracking_statuses' => ['uuid', 'public_id', 'company_uuid', 'tracking_number_uuid', 'code', 'status', 'details'], From 3f11a5366df50f71669b535f879bbd5ae4c5782d Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Sun, 15 Nov 2026 02:28:13 +0800 Subject: [PATCH 26/29] test(order-configs): cover the order config actions, custom fields, templates and endpoints The order config policies, triggers and templates work on release/v0.7.0 had no PHP CI run, so these lines were never measured: - the cancel, open chat and set meta actions, and notify driver with nothing to say - OrderCustomFields validate and apply - OrderUpdate's FCM and APN messages - the internal capabilities and create from template endpoints - the OrderConfig resource's custom fields - template registration and unknown template keys - Condition with collections and single values - custom field and payment method refusals on customer and API order creation, and dispatch refused by the config --- .../tests/ApiOrderControllerContractsTest.php | 21 ++ .../AdhocDispatchAndOrderConfigTest.php | 225 ++++++++++++++++++ .../Http/Api/OrderControllerCreateTest.php | 49 ++++ .../OrderConfigControllerContractsTest.php | 55 ++++- server/tests/FlowResourceTest.php | 10 + .../Resources/OrderConfigResourceTest.php | 52 ++++ .../OrderConfig/OrderConfigTemplatesTest.php | 38 +++ 7 files changed, 449 insertions(+), 1 deletion(-) diff --git a/server/tests/ApiOrderControllerContractsTest.php b/server/tests/ApiOrderControllerContractsTest.php index 228827ff1..98a72a079 100644 --- a/server/tests/ApiOrderControllerContractsTest.php +++ b/server/tests/ApiOrderControllerContractsTest.php @@ -1065,6 +1065,27 @@ public function isString(string $key): bool expect($controller->dispatchOrder('order-public'))->toBe(['apiError' => 'Order has already been dispatched!', 'status' => 400]); + // An order whose config turns dispatch off is refused, and not dispatched. + $withConfig = function (array $lifecycle) { + $config = new OrderConfig(); + $config->setRawAttributes(['uuid' => 'config-uuid', 'key' => 'pickup', 'meta' => json_encode(['lifecycle' => $lifecycle])], true); + $order = new FleetOpsApiOrderCrudFake(); + $order->order_config_uuid = 'config-uuid'; + $order->setRelation('orderConfig', $config); + $controller = new FleetOpsApiOrderCrudControllerProbe(); + $controller->order = $order; + + return [$controller->dispatchOrder('order-public'), $order]; + }; + [$refused, $kept] = $withConfig(['dispatch' => false]); + [$allowed, $sent] = $withConfig(['dispatch' => true]); + + expect($refused)->toBe(['apiError' => 'Orders of this type are not dispatched.', 'status' => 400]) + ->and($kept->dispatchedForTest)->toBeFalse() + ->and($kept->dispatchActivityInserted)->toBeFalse() + ->and($allowed)->toBe(['resource' => 'order', 'order' => $sent]) + ->and($sent->dispatchedForTest)->toBeTrue(); + $order = new FleetOpsApiOrderCrudFake(); $order->trackerFake->throwOnTrack = true; diff --git a/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php index 124eb4a7a..7601fb99b 100644 --- a/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php +++ b/server/tests/Feature/AdhocDispatchAndOrderConfigTest.php @@ -14,10 +14,14 @@ use Fleetbase\FleetOps\Support\DriverMatching; use Fleetbase\FleetOps\Support\DriverRatings; use Fleetbase\FleetOps\Support\OrderChat; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\CancelOrder; use Fleetbase\FleetOps\Support\OrderConfig\Actions\NotifyCustomer; use Fleetbase\FleetOps\Support\OrderConfig\Actions\NotifyDriver; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\OpenChat; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\SetMeta; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers; +use Fleetbase\FleetOps\Support\OrderCustomFields; use Fleetbase\FleetOps\Support\OrderOffers; use Fleetbase\FleetOps\Support\OrderRepricing; use Fleetbase\LaravelMysqlSpatial\Types\Point; @@ -37,10 +41,55 @@ eval('namespace Fleetbase\Observers; function event($event = null, $payload = []) { return []; }'); } +// Settings read the company from the session store, which the harness keeps as a plain array. +if (!function_exists('Fleetbase\Models\session')) { + eval('namespace Fleetbase\Models; function session($key = null, $default = null) { if ($key === null) { return new class { public function has($k) { return \session($k) !== null; } public function get($k, $d = null) { return \session($k, $d); } public function missing($k) { return \session($k) === null; } }; } return \session($key, $default); }'); +} + if (!function_exists('Fleetbase\FleetOps\Support\event')) { eval('namespace Fleetbase\FleetOps\Support; function event($event = null) { if (\AdhocCfgRecorder::$failEvents) { throw new \RuntimeException(\'socket down\'); } \AdhocCfgRecorder::$events[] = $event; return $event; }'); } +/** + * Stands in for Laravel's validator, which this package doesn't install: it records what it was + * asked to check and applies the `required` and `integer` rules, naming fields by their attribute. + */ +class AdhocCfgValidator +{ + public static array $made = []; + + public function make($data = [], $rules = [], $messages = [], $attributes = []) + { + static::$made[] = ['data' => $data, 'rules' => $rules, 'attributes' => $attributes]; + $errors = new Illuminate\Support\MessageBag(); + foreach ($rules as $field => $fieldRules) { + $value = $data[$field] ?? null; + $name = $attributes[$field] ?? $field; + if (in_array('required', $fieldRules, true) && ($value === null || $value === '')) { + $errors->add($field, 'The ' . $name . ' field is required.'); + } elseif ($value !== null && in_array('integer', $fieldRules, true) && filter_var($value, FILTER_VALIDATE_INT) === false) { + $errors->add($field, 'The ' . $name . ' field must be an integer.'); + } + } + + return new class($errors) { + public function __construct(public Illuminate\Support\MessageBag $bag) + { + } + + public function fails(): bool + { + return $this->bag->isNotEmpty(); + } + + public function errors(): Illuminate\Support\MessageBag + { + return $this->bag; + } + }; + } +} + class AdhocCfgRecorder { public static array $notified = []; @@ -998,6 +1047,11 @@ function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): Adh ->and($update->data)->toBe(['id' => 'order_one', 'type' => 'order_arrived']) ->and($default->data)->toBe(['id' => 'order_one', 'type' => 'order_update']) ->and($update->via(null))->toBe([NotificationChannels\Fcm\FcmChannel::class, NotificationChannels\Apn\ApnChannel::class]); + + // Building each channel's message hands the push to core's PushNotification, which needs the + // FCM and APN credentials this harness doesn't configure. + expect(fn () => $update->toFcm(null))->toThrow(TypeError::class) + ->and(fn () => $update->toApn(null))->toThrow(Error::class); }); test('the notify actions push to the order\'s customer and driver, with placeholders filled in', function () { @@ -1128,6 +1182,112 @@ function adhocCfgSeedOrder(SQLiteConnection $connection, array $order = []): Adh ->and((new RunOrderConfigAction($order, 'set_meta'))->orderUuid)->toBe('order-1'); }); +test('the cancel, open chat and set meta actions act on the order, and skip what they cannot do', function () { + $connection = adhocCfgBoot(); + adhocCfgSeedOrder($connection, ['status' => 'started']); + + // A finished order, by its config's terminal activities, is not canceled again. + $connection->table('orders')->update(['status' => 'no_show']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 'Too late']); + $connection->table('orders')->update(['status' => 'started']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 'Rider asked']); + (new CancelOrder())->handle(adhocCfgFresh(), ['reason' => 42]); + (new CancelOrder())->handle(adhocCfgFresh()); + + expect(AdhocCfgOrder::$canceled)->toBe([['order-1', 'Rider asked'], ['order-1', '42'], ['order-1', null]]); + + (new OpenChat())->handle(adhocCfgFresh()); + $channel = $connection->table('chat_channels')->first(); + expect($channel)->not->toBeNull() + ->and($connection->table('orders')->where('uuid', 'order-1')->value('chat_channel_uuid'))->toBe($channel->uuid) + ->and($connection->table('chat_participants')->orderBy('id')->pluck('user_uuid')->all())->toBe(['user-sam', 'user-chen']); + + // A key that is blank or not a string writes nothing; `{now}` writes the current time. + Carbon::setTestNow('2026-11-06 09:30:00'); + (new SetMeta())->handle(adhocCfgFresh(), ['key' => ' ', 'value' => 'blank']); + (new SetMeta())->handle(adhocCfgFresh(), ['key' => 7, 'value' => 'number']); + (new SetMeta())->handle(adhocCfgFresh(), ['value' => 'missing']); + $untouched = adhocCfgFresh()->meta; + (new SetMeta())->handle(adhocCfgFresh(), ['key' => ' picked_up_at ', 'value' => '{now}']); + Carbon::setTestNow(); + + expect($untouched)->toBeEmpty() + ->and(adhocCfgFresh()->getMeta('picked_up_at'))->toBe('2026-11-06T09:30:00.000000Z'); +}); + +test('the notify driver action sends nothing when it has neither a title nor a message', function () { + $connection = adhocCfgBoot(); + $order = adhocCfgSeedOrder($connection, ['status' => 'started']); + + (new NotifyDriver())->handle($order, [], ['event' => 'order.completed']); + (new NotifyDriver())->handle($order, ['title' => '', 'message' => ''], ['event' => 'order.activity', 'activity' => ['status' => 'Started']]); + expect(AdhocCfgRecorder::$notified)->toBe([]); + + (new NotifyDriver())->handle($order, [], ['event' => 'order.activity', 'activity' => ['status' => 'Started']]); + expect(AdhocCfgRecorder::$notified)->toBe([['chen', OrderUpdate::class]]) + ->and([AdhocCfgRecorder::$sent[0]->title, AdhocCfgRecorder::$sent[0]->message])->toBe(['Started', '']); +}); + +/** The test config's custom fields, by name, label and snake-cased label, and a validator that checks them. */ +function adhocCfgCustomFields(SQLiteConnection $connection): void +{ + $subject = ['company_uuid' => 'company-1', 'subject_uuid' => 'config-adhoc', 'subject_type' => OrderConfig::class]; + $connection->table('custom_fields')->insert([ + [...$subject, 'uuid' => 'field-passengers', 'name' => 'passengers', 'label' => 'Passengers', 'type' => 'input', 'required' => 1, 'validation_rules' => json_encode(['nullable', 'integer', 'required', 5]), 'order' => '0'], + [...$subject, 'uuid' => 'field-flight', 'name' => 'cf_flight', 'label' => 'Flight Number', 'type' => null, 'required' => 0, 'validation_rules' => null, 'order' => '1'], + [...$subject, 'uuid' => 'field-notes', 'name' => 'cf_notes', 'label' => 'Pickup Notes', 'type' => 'textarea', 'required' => 0, 'validation_rules' => json_encode([]), 'order' => '2'], + [...$subject, 'uuid' => 'field-gate', 'name' => 'gate_code', 'label' => null, 'type' => 'input', 'required' => 0, 'validation_rules' => null, 'order' => '3'], + ]); + app()->instance('validator', new AdhocCfgValidator()); + Illuminate\Support\Facades\Validator::clearResolvedInstance('validator'); + AdhocCfgValidator::$made = []; +} + +test('custom field values are checked against the config\'s fields, found by name, label or snake-cased label', function () { + $connection = adhocCfgBoot(); + adhocCfgCustomFields($connection); + $connection->table('order_configs')->insert(['uuid' => 'config-bare', 'public_id' => 'order_config_bare', 'company_uuid' => 'company-1', 'name' => 'Bare', 'key' => 'bare']); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + + $missing = OrderCustomFields::validate($config, ['flight_number' => 'SQ12', 'Pickup Notes' => 'By the lobby', 'gate_code' => '4411']); + $checked = AdhocCfgValidator::$made[0]; + $typed = OrderCustomFields::validate($config, ['passengers' => 'two']); + $fine = OrderCustomFields::validate($config, ['passengers' => 3, 'ignored' => 'x']); + + expect($missing)->toBe('The Passengers field is required.') + ->and($checked['data'])->toBe(['passengers' => null, 'cf_flight' => 'SQ12', 'cf_notes' => 'By the lobby', 'gate_code' => '4411']) + // A field's own `required` and `nullable` rules give way to its required flag; rules that aren't strings are dropped. + ->and($checked['rules'])->toBe(['passengers' => ['required', 'integer'], 'cf_flight' => ['nullable'], 'cf_notes' => ['nullable'], 'gate_code' => ['nullable']]) + ->and($checked['attributes'])->toBe(['passengers' => 'Passengers', 'cf_flight' => 'Flight Number', 'cf_notes' => 'Pickup Notes', 'gate_code' => 'gate_code']) + ->and($typed)->toBe('The Passengers field must be an integer.') + ->and($fine)->toBeNull() + // A config without fields, or a request without values, isn't checked. + ->and(OrderCustomFields::validate(OrderConfig::where('uuid', 'config-bare')->first(), ['passengers' => 2]))->toBeNull() + ->and(OrderCustomFields::validate($config, []))->toBeNull() + ->and(AdhocCfgValidator::$made)->toHaveCount(3); +}); + +test('custom field values are stored on the order for the fields its config has, typed by the field', function () { + $connection = adhocCfgBoot(); + adhocCfgCustomFields($connection); + $order = adhocCfgOrder($connection); + $stored = fn () => $connection->table('custom_field_values')->orderBy('id')->get(['custom_field_uuid', 'subject_uuid', 'value', 'value_type'])->map(fn ($row) => (array) $row)->all(); + + expect(OrderCustomFields::apply($order, ['luggage' => 2]))->toBe(0) + ->and(OrderCustomFields::apply($order, []))->toBe(0) + ->and($stored())->toBe([]) + ->and(OrderCustomFields::apply($order, ['passengers' => '2', 'flight_number' => 'SQ12', 'Pickup Notes' => 'By the lobby']))->toBe(3) + ->and($stored())->toBe([ + ['custom_field_uuid' => 'field-passengers', 'subject_uuid' => 'order-1', 'value' => '2', 'value_type' => 'input'], + ['custom_field_uuid' => 'field-flight', 'subject_uuid' => 'order-1', 'value' => 'SQ12', 'value_type' => 'text'], + ['custom_field_uuid' => 'field-notes', 'subject_uuid' => 'order-1', 'value' => 'By the lobby', 'value_type' => 'textarea'], + ]) + // Sending a field again updates its value rather than adding one. + ->and(OrderCustomFields::apply(adhocCfgFresh(), ['passengers' => '4']))->toBe(1) + ->and($connection->table('custom_field_values')->count())->toBe(3) + ->and($connection->table('custom_field_values')->where('custom_field_uuid', 'field-passengers')->value('value'))->toBe('4'); +}); + /** Positions the driver reported: one before metering began, then 1.0 km and 1.05 km. */ function adhocCfgSeedPositions(SQLiteConnection $connection): void { @@ -1600,3 +1760,68 @@ function adhocCfgJson($response): array ->and($order->dispatchOutcome())->toBe('no_driver_found') ->and($order->chatChannel)->toBeNull(); }); + +test('a customer order is refused with 422 for a config customers may not order, a payment method the policy doesn\'t offer, or a bad custom field', function () { + $connection = adhocCfgBoot(); + adhocCfgPolicies($connection, ['customer' => ['ordering' => ['payment_methods' => ['cash', 'card']]]]); + adhocCfgSeedOrder($connection); + adhocCfgCustomFields($connection); + $controller = new AdhocCfgCustomerController(); + $order = fn (array $input) => $controller->createOrder(new Fleetbase\FleetOps\Http\Requests\CreateCustomerOrderRequest($input)); + + $controller->settings = ['fleet-ops.customer-enabled-order-configs' => ['config-other']]; + $notOffered = $order(['payment_method' => 'cash']); + $controller->settings = []; + $bitcoin = $order(['payment_method' => 'bitcoin']); + $noPassengers = $order(['payment_method' => 'cash', 'custom_fields' => ['flight_number' => 'SQ12']]); + $wordy = $order(['custom_fields' => ['passengers' => 'two']]); + + expect([$notOffered->getStatusCode(), $bitcoin->getStatusCode(), $noPassengers->getStatusCode(), $wordy->getStatusCode()])->toBe([422, 422, 422, 422]) + ->and(adhocCfgJson($notOffered)['error'])->toBe('Customers cannot place this type of order.') + ->and(adhocCfgJson($bitcoin)['error'])->toBe('Choose a payment method: cash, card.') + ->and(adhocCfgJson($noPassengers)['error'])->toBe('The Passengers field is required.') + ->and(adhocCfgJson($wordy)['error'])->toBe('The Passengers field must be an integer.') + // Nothing was made for a refused order. + ->and($connection->table('orders')->count())->toBe(1) + ->and($connection->table('payloads')->count())->toBe(1); +}); + +/** A customer controller that reads the company's settings from the settings table, as it does in production. */ +class AdhocCfgStoredSettingsCustomerController extends Fleetbase\FleetOps\Http\Controllers\Api\v1\CustomerController +{ + public function helper(string $method, ...$arguments): mixed + { + return $this->{$method}(...$arguments); + } +} + +test('the order configs customers may use are read from the company\'s stored settings', function () { + $connection = adhocCfgBoot(); + $connection->getSchemaBuilder()->create('settings', function ($blueprint) { + $blueprint->increments('id'); + $blueprint->string('key')->nullable(); + $blueprint->text('value')->nullable(); + $blueprint->timestamps(); + }); + $controller = new AdhocCfgStoredSettingsCustomerController(); + $config = OrderConfig::where('uuid', 'config-adhoc')->first(); + $key = 'fleet-ops.customer-enabled-order-configs'; + + $unset = [$controller->helper('lookupCompanySetting', $key, ['fallback']), $controller->helper('customersMayOrder', $config)]; + + $connection->table('settings')->insert(['key' => 'company.company-1.' . $key, 'value' => json_encode(['order_config_other'])]); + $refused = [$controller->helper('lookupCompanySetting', $key), $controller->helper('customersMayOrder', $config)]; + + $connection->table('settings')->update(['value' => json_encode(['order_config_passenger'])]); + $allowed = $controller->helper('customersMayOrder', $config); + + // Another company's setting doesn't apply. + session(['company' => 'company-2']); + $elsewhere = $controller->helper('lookupCompanySetting', $key, []); + session(['company' => 'company-1']); + + expect($unset)->toBe([['fallback'], true]) + ->and($refused)->toBe([['order_config_other'], false]) + ->and($allowed)->toBeTrue() + ->and($elsewhere)->toBe([]); +}); diff --git a/server/tests/Feature/Http/Api/OrderControllerCreateTest.php b/server/tests/Feature/Http/Api/OrderControllerCreateTest.php index 07f78f0f0..750e44da1 100644 --- a/server/tests/Feature/Http/Api/OrderControllerCreateTest.php +++ b/server/tests/Feature/Http/Api/OrderControllerCreateTest.php @@ -123,6 +123,7 @@ public function __call($method, $arguments) 'integrated_vendors' => ['uuid', 'public_id', 'company_uuid', 'provider'], 'companies' => ['uuid', 'public_id', 'name', 'options'], 'company_users' => ['uuid', 'company_uuid', 'user_uuid', 'status'], + 'custom_fields' => ['uuid', 'public_id', 'company_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'required', 'validation_rules', 'order'], ]; foreach ($tables as $table => $columns) { $schema->create($table, function ($blueprint) use ($columns) { @@ -277,3 +278,51 @@ protected function firstOrCreateCustomerContact(array $attributes, array $values ])); expect($existing->getData(true)['error'] ?? '')->toBe('That user already exists.'); }); + +test('create refuses custom field values that fail the order config\'s fields with 422, before making the order', function () { + $connection = fleetopsApiOrderCreateBoot(); + $connection->table('payloads')->insert(['uuid' => '66666666-6666-4666-8666-666666666666', 'public_id' => 'payload_test', 'company_uuid' => 'company-1']); + $connection->table('custom_fields')->insert(['uuid' => 'field-dock', 'company_uuid' => 'company-1', 'subject_uuid' => 'config-1', 'subject_type' => Fleetbase\FleetOps\Models\OrderConfig::class, 'name' => 'dock_number', 'label' => 'Dock Number', 'required' => '1', 'order' => '0']); + $checked = []; + app()->instance('validator', new class($checked) { + public function __construct(public array &$checked) + { + } + + public function make($data = [], $rules = [], $messages = [], $attributes = []) + { + $this->checked[] = [$data, $rules, $attributes]; + $missing = array_keys(array_filter($data, fn ($value) => $value === null)); + + return new class($missing ? 'The ' . $attributes[$missing[0]] . ' field is required.' : null) { + public function __construct(public ?string $message) + { + } + + public function fails(): bool + { + return $this->message !== null; + } + + public function errors(): Illuminate\Support\MessageBag + { + return new Illuminate\Support\MessageBag($this->message ? ['dock_number' => [$this->message]] : []); + } + }; + } + }); + Illuminate\Support\Facades\Validator::clearResolvedInstance('validator'); + + $response = (new FleetOpsApiOrderCreateProbe())->create(CreateOrderRequest::create('/v1/orders', 'POST', [ + 'type' => 'transport', + 'payload' => 'payload_test', + 'custom_fields' => ['gate' => 'B'], + 'dispatch' => false, + ])); + + expect($response)->toBeInstanceOf(JsonResponse::class) + ->and($response->getStatusCode())->toBe(422) + ->and($response->getData(true))->toBe(['error' => 'The Dock Number field is required.']) + ->and($checked)->toBe([[['dock_number' => null], ['dock_number' => ['required']], ['dock_number' => 'Dock Number']]]) + ->and($connection->table('orders')->count())->toBe(0); +}); diff --git a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php index 69bfcbfd4..8090c8708 100644 --- a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php @@ -220,7 +220,7 @@ public function __call($method, $arguments) }); $schema->create('order_configs', function ($blueprint) { $blueprint->increments('id'); - foreach (['uuid', 'public_id', 'company_uuid', 'created_by_uuid', 'author_uuid', 'category_uuid', 'icon_uuid', 'name', 'key', 'namespace', 'description', 'tags', 'flow', 'entities', 'meta', 'version', 'status', 'type', '_key'] as $column) { + foreach (['uuid', 'public_id', 'company_uuid', 'created_by_uuid', 'author_uuid', 'category_uuid', 'icon_uuid', 'name', 'key', 'namespace', 'description', 'tags', 'flow', 'entities', 'meta', 'policies', 'triggers', 'version', 'status', 'type', '_key'] as $column) { $blueprint->string($column)->nullable(); } $blueprint->integer('core_service')->nullable(); @@ -228,6 +228,15 @@ public function __call($method, $arguments) $blueprint->timestamp('deleted_at')->nullable(); }); + $schema->create('custom_fields', function ($blueprint) { + $blueprint->increments('id'); + foreach (['uuid', 'public_id', 'company_uuid', 'category_uuid', 'subject_uuid', 'subject_type', 'name', 'label', 'type', 'for', 'component', 'options', 'required', 'editable', 'default_value', 'validation_rules', 'meta', 'description', 'help_text', 'order'] as $column) { + $blueprint->string($column)->nullable(); + } + $blueprint->timestamps(); + $blueprint->timestamp('deleted_at')->nullable(); + }); + session(['company' => 'company-1']); $connection->table('companies')->insert(['uuid' => 'company-1', 'name' => 'Acme']); app()->instance('responsecache', new class { @@ -312,3 +321,47 @@ public function __call($method, $arguments) $missing = $controller->deleteRecord('missing-uuid', Request::create('/int/v1/order-configs', 'DELETE')); expect(json_encode($missing->getData(true)))->toContain('No order config found'); }); + +test('internal order config controller describes what order configs can use, for the console', function () { + $response = (new FleetOpsInternalOrderConfigRealHelpersProbe())->capabilities(); + $body = $response->getData(true); + + expect($response->getStatusCode())->toBe(200) + ->and(array_keys($body))->toBe(['templates', 'policies', 'actions', 'events']) + ->and($body['templates'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::describe()) + ->and(array_column($body['templates'], 'key'))->toBe(['transport', 'passenger']) + ->and($body['policies'])->toBe(json_decode(json_encode(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies::describe()), true)) + ->and(array_column($body['actions'], 'name'))->toContain('cancel', 'open_chat', 'set_meta', 'notify_driver') + ->and($body['events'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers::EVENTS); +}); + +test('internal order config controller makes a named config from a template once, for the company in session', function () { + $connection = fleetopsInternalOrderConfigDbBoot(); + $controller = new FleetOpsInternalOrderConfigRealHelpersProbe(); + $make = fn (array $input) => $controller->createFromTemplate(Request::create('/int/v1/order-configs/from-template', 'POST', $input)); + $error = fn ($response) => $response->getData(true)['error'] ?? null; + + $unknown = $make(['template' => 'limousine', 'name' => 'Limos']); + $blank = $make(['template' => 'passenger', 'name' => ' ']); + $created = $make(['template' => 'passenger', 'name' => ' Airport Transfers ']); + $sameKey = $make(['template' => 'transport', 'name' => 'airport transfers']); + $sameName = $make(['template' => 'transport', 'name' => 'Airport Transfers']); + + session(['company' => null]); + $noCompany = $make(['template' => 'passenger', 'name' => 'Night Rides']); + session(['company' => 'company-1']); + + $config = $connection->table('order_configs')->first(); + expect($error($unknown))->toBe('Choose an order config template.') + ->and($error($blank))->toBe('Give the order config a name.') + ->and($error($sameKey))->toBe('An order config with this name already exists.') + ->and($error($sameName))->toBe('An order config with this name already exists.') + ->and($error($noCompany))->toBe('No organization in session.') + ->and($created)->toHaveKey('order_config') + ->and($created['order_config']->resource->uuid)->toBe($config->uuid) + ->and($connection->table('order_configs')->count())->toBe(1) + ->and([$config->company_uuid, $config->name, $config->key, $config->namespace, (int) $config->core_service])->toBe(['company-1', 'Airport Transfers', 'airport-transfers', 'acme:order-config:airport-transfers', 0]) + ->and(json_decode($config->policies, true)['dispatch']['adhoc']['strategy'])->toBe('sequential') + // The passenger template's custom field is made with the config. + ->and($connection->table('custom_fields')->where('subject_uuid', $config->uuid)->pluck('name')->all())->toBe(['passengers']); +}); diff --git a/server/tests/FlowResourceTest.php b/server/tests/FlowResourceTest.php index 85d60dc61..2e8a73d8f 100644 --- a/server/tests/FlowResourceTest.php +++ b/server/tests/FlowResourceTest.php @@ -173,6 +173,16 @@ function flowFixture(): array expect((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'fragile']))->eval($tagged))->toBeTrue() ->and((new Condition(['field' => 'tags', 'operator' => 'doesntHave', 'value' => 'oversize']))->eval($tagged))->toBeTrue() ->and((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'oversize']))->eval($tagged))->toBeFalse(); + + // A field read as a collection, such as a relation, is compared as its list. + $collected = flowTestOrder(['tags' => collect(['Fragile', 'express']), 'status' => 'Ready']); + expect((new Condition(['field' => 'tags', 'operator' => 'has', 'value' => 'FRAGILE']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'tags', 'operator' => 'doesntHave', 'value' => 'express']))->eval($collected))->toBeFalse() + // A single value is a list of one, and a missing field an empty list. + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => 'ready']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'status', 'operator' => 'notIn', 'value' => 'held']))->eval($collected))->toBeTrue() + ->and((new Condition(['field' => 'missing_field', 'operator' => 'has', 'value' => 'fragile']))->eval($collected))->toBeFalse() + ->and((new Condition(['field' => 'status', 'operator' => 'in', 'value' => null]))->eval($collected))->toBeFalse(); }); test('flow logic combines conditions with and or not and if semantics', function () { diff --git a/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php b/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php index 1ba4af30c..e6b5fd222 100644 --- a/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php +++ b/server/tests/Unit/Http/Resources/OrderConfigResourceTest.php @@ -136,3 +136,55 @@ class FleetOpsSupportRequestState ->and($flow[0]['activities'])->toBe([]) ->and($flow[0]['logic'])->toBeNull(); }); + +test('order config resource lists the custom fields orders of the config carry, once they are loaded', function () { + $request = Request::create('/v1/fleet-ops/order-configs/order_config_public', 'GET'); + FleetOpsOrderConfigResourceRequestState::$request = $request; + FleetOpsSupportRequestState::$request = $request; + + $config = new OrderConfig(); + $config->setRawAttributes(['id' => 11, 'uuid' => 'order-config-uuid', 'public_id' => 'order_config_public', 'key' => 'passenger', 'name' => 'Passenger', 'flow' => []], true); + + // Without the relation loaded, the resource doesn't query for it. + expect((new OrderConfigResource($config))->resolve($request))->not->toHaveKey('custom_fields'); + + $passengers = new Fleetbase\Models\CustomField(); + $passengers->setRawAttributes([ + 'uuid' => 'field-passengers', + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'options' => json_encode(['min' => 1]), + 'required' => 1, + 'default_value' => '1', + 'help_text' => 'How many people are travelling.', + 'validation_rules' => json_encode(['integer']), + ], true); + $notes = new Fleetbase\Models\CustomField(); + $notes->setRawAttributes(['uuid' => 'field-notes', 'name' => 'notes', 'label' => 'Notes', 'type' => 'textarea', 'required' => null], true); + $config->setRelation('customFields', collect([3 => $passengers, 7 => $notes])); + + expect((new OrderConfigResource($config))->resolve($request)['custom_fields'])->toBe([ + [ + 'name' => 'passengers', + 'label' => 'Passengers', + 'type' => 'input', + 'component' => 'input', + 'options' => ['min' => 1], + 'required' => true, + 'default_value' => '1', + 'help_text' => 'How many people are travelling.', + ], + [ + 'name' => 'notes', + 'label' => 'Notes', + 'type' => 'textarea', + 'component' => null, + 'options' => null, + 'required' => false, + 'default_value' => null, + 'help_text' => null, + ], + ]); +}); diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php index 7d6491475..d71dd87fc 100644 --- a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php @@ -164,3 +164,41 @@ function orderConfigTemplatesFlow(array $flow): array 'order' => 0, ]]); }); + +/** A template an extension might add. */ +class OrderConfigTemplatesFreightTemplate extends Fleetbase\FleetOps\Support\OrderConfig\Templates\Template +{ + protected string $key = 'freight'; + protected string $name = 'Freight'; + protected string $description = 'Pallets, picked up and delivered.'; + + public function attributes(): array + { + return ['tags' => ['freight'], 'flow' => ['created' => static::activity('created', 'Order Created', 'New order was created.')]]; + } +} + +test('extensions register their own templates by key, and an unknown template makes no config', function () { + $registry = new ReflectionProperty(OrderConfigTemplates::class, 'templates'); + $before = $registry->getValue(); + + try { + OrderConfigTemplates::register(OrderConfigTemplatesFreightTemplate::class); + + expect(OrderConfigTemplates::has('freight'))->toBeTrue() + ->and(OrderConfigTemplates::get('freight'))->toBeInstanceOf(OrderConfigTemplatesFreightTemplate::class) + ->and(array_column(OrderConfigTemplates::describe(), 'key'))->toBe(['transport', 'passenger', 'freight']) + ->and(Arr::only(OrderConfigTemplates::attributes('freight'), ['name', 'key', 'namespace', 'tags']))->toBe([ + 'name' => 'Freight', + 'key' => 'freight', + 'namespace' => 'system:order-config:freight', + 'tags' => ['freight'], + ]); + } finally { + $registry->setValue(null, $before); + } + + // Refused before any config is looked up or made. + expect(fn () => OrderConfigTemplates::create('limousine', new Fleetbase\Models\Company()))->toThrow(InvalidArgumentException::class, 'No order config template named limousine.') + ->and(OrderConfigTemplates::has('freight'))->toBeFalse(); +}); From c8095fd1878c0de3fd2c10b742aa496739c2d64e Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 16 Nov 2026 11:39:59 +0800 Subject: [PATCH 27/29] feat(order-configs): describe template summaries, number ranges and message placeholders for the console Templates now describe the step labels along their main path and how many steps, policies, triggers and custom fields they set up. Number settings carry the min and max their rules allow, and capabilities lists the placeholders notification text can use. --- .../Internal/v1/OrderConfigController.php | 10 ++-- .../Support/OrderConfig/Actions/Action.php | 14 ++++++ .../OrderConfig/OrderConfigPolicies.php | 19 ++++++- .../OrderConfig/OrderConfigTemplates.php | 49 +++++++++++++++++-- .../OrderConfigControllerContractsTest.php | 5 +- .../OrderConfig/OrderConfigPoliciesTest.php | 3 ++ .../OrderConfig/OrderConfigTemplatesTest.php | 16 +++++- 7 files changed, 101 insertions(+), 15 deletions(-) diff --git a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php index fa2a5c63f..f6340ea92 100644 --- a/server/src/Http/Controllers/Internal/v1/OrderConfigController.php +++ b/server/src/Http/Controllers/Internal/v1/OrderConfigController.php @@ -6,6 +6,7 @@ use Fleetbase\FleetOps\Http\Controllers\FleetOpsController; use Fleetbase\FleetOps\Http\Requests\Internal\CreateOrderConfigRequest; use Fleetbase\FleetOps\Models\OrderConfig; +use Fleetbase\FleetOps\Support\OrderConfig\Actions\Action; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigActions; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies; use Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates; @@ -85,10 +86,11 @@ public function deleteRecord($id, Request $request) public function capabilities() { return response()->json([ - 'templates' => OrderConfigTemplates::describe(), - 'policies' => OrderConfigPolicies::describe(), - 'actions' => OrderConfigActions::describe(), - 'events' => OrderConfigTriggers::EVENTS, + 'templates' => OrderConfigTemplates::describe(), + 'policies' => OrderConfigPolicies::describe(), + 'actions' => OrderConfigActions::describe(), + 'events' => OrderConfigTriggers::EVENTS, + 'placeholders' => Action::PLACEHOLDERS, ]); } diff --git a/server/src/Support/OrderConfig/Actions/Action.php b/server/src/Support/OrderConfig/Actions/Action.php index 419dc70b5..859d484a6 100644 --- a/server/src/Support/OrderConfig/Actions/Action.php +++ b/server/src/Support/OrderConfig/Actions/Action.php @@ -17,6 +17,20 @@ abstract class Action implements OrderConfigAction protected string $description; protected array $parameters = []; + /** + * The placeholders `render()` fills in, for people writing notification text. + */ + public const PLACEHOLDERS = [ + 'driver.first_name', + 'driver.name', + 'customer.name', + 'order.id', + 'order.tracking_number', + 'order.status', + 'activity.status', + 'activity.details', + ]; + public function name(): string { return $this->name; diff --git a/server/src/Support/OrderConfig/OrderConfigPolicies.php b/server/src/Support/OrderConfig/OrderConfigPolicies.php index feec4ba22..979d6ea44 100644 --- a/server/src/Support/OrderConfig/OrderConfigPolicies.php +++ b/server/src/Support/OrderConfig/OrderConfigPolicies.php @@ -100,7 +100,7 @@ public static function rules(string $prefix = 'policies'): array /** * Every policy, for people configuring them, with each setting's type (`boolean`, `number`, - * `text`, `list` or `choice`) and choices. + * `text`, `list` or `choice`), choices, and for numbers the `min` and `max` its rules allow. * * @return array */ @@ -119,7 +119,7 @@ public static function describe(): array in_array('integer', $settingRules, true) || in_array('numeric', $settingRules, true) => 'number', default => 'text', }; - $settings[] = ['name' => $name, 'type' => $type, 'default' => $default, 'choices' => $choices[$name] ?? null]; + $settings[] = ['name' => $name, 'type' => $type, 'default' => $default, 'choices' => $choices[$name] ?? null] + ($type === 'number' ? static::bounds($settingRules) : []); } return [ @@ -131,4 +131,19 @@ public static function describe(): array ]; }, static::all())); } + + /** + * The `min` and `max` in a setting's rules, as numbers, when it has them. + */ + protected static function bounds(array $rules): array + { + $bounds = []; + foreach ($rules as $rule) { + if (is_string($rule) && preg_match('/^(min|max):(-?\d+(?:\.\d+)?)$/', $rule, $match)) { + $bounds[$match[1]] = $match[2] + 0; + } + } + + return $bounds; + } } diff --git a/server/src/Support/OrderConfig/OrderConfigTemplates.php b/server/src/Support/OrderConfig/OrderConfigTemplates.php index 6fdaf7a49..bff72ec67 100644 --- a/server/src/Support/OrderConfig/OrderConfigTemplates.php +++ b/server/src/Support/OrderConfig/OrderConfigTemplates.php @@ -48,19 +48,58 @@ public static function get(string $key): ?OrderConfigTemplate } /** - * Every template, for people choosing one. + * Every template, for people choosing one, with what it sets up: the step labels along its + * main path and how many steps, policies, triggers and custom fields it brings. * - * @return array + * @return array, summary: array{steps: int, policies: int, triggers: int, custom_fields: int}}> */ public static function describe(): array { return array_values(array_map(function (string $class) { - $template = app($class); - - return ['key' => $template->key(), 'name' => $template->name(), 'description' => $template->description()]; + $template = app($class); + $attributes = $template->attributes(); + $flow = is_array($attributes['flow'] ?? null) ? $attributes['flow'] : []; + + return [ + 'key' => $template->key(), + 'name' => $template->name(), + 'description' => $template->description(), + 'steps' => static::mainPath($flow, data_get($attributes, 'meta.lifecycle.initial')), + 'summary' => [ + 'steps' => count($flow), + 'policies' => static::countPolicies($attributes['policies'] ?? []), + 'triggers' => count($attributes['triggers'] ?? []) + array_sum(array_map(fn ($activity) => count($activity['actions'] ?? []), $flow)), + 'custom_fields' => count($template->customFields()), + ], + ]; }, static::$templates)); } + /** + * The status labels from the first step, following each step's first next step. + */ + protected static function mainPath(array $flow, ?string $initial = null): array + { + $code = $initial ?: (isset($flow['created']) ? 'created' : array_key_first($flow)); + $labels = []; + $seen = []; + while ($code && isset($flow[$code]) && !isset($seen[$code])) { + $seen[$code] = true; + $labels[] = (string) ($flow[$code]['status'] ?? $code); + $code = $flow[$code]['activities'][0] ?? null; + } + + return $labels; + } + + /** + * How many registered policies the template sets anything on. + */ + protected static function countPolicies(array $policies): int + { + return count(array_filter(array_keys(OrderConfigPolicies::all()), fn (string $key) => !empty(data_get($policies, $key)))); + } + /** * The attributes of the system config made from the template (`system:order-config:`). */ diff --git a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php index 8090c8708..27fe6377b 100644 --- a/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php +++ b/server/tests/Feature/Http/Internal/OrderConfigControllerContractsTest.php @@ -327,12 +327,13 @@ public function __call($method, $arguments) $body = $response->getData(true); expect($response->getStatusCode())->toBe(200) - ->and(array_keys($body))->toBe(['templates', 'policies', 'actions', 'events']) + ->and(array_keys($body))->toBe(['templates', 'policies', 'actions', 'events', 'placeholders']) ->and($body['templates'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTemplates::describe()) ->and(array_column($body['templates'], 'key'))->toBe(['transport', 'passenger']) ->and($body['policies'])->toBe(json_decode(json_encode(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigPolicies::describe()), true)) ->and(array_column($body['actions'], 'name'))->toContain('cancel', 'open_chat', 'set_meta', 'notify_driver') - ->and($body['events'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers::EVENTS); + ->and($body['events'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\OrderConfigTriggers::EVENTS) + ->and($body['placeholders'])->toBe(Fleetbase\FleetOps\Support\OrderConfig\Actions\Action::PLACEHOLDERS); }); test('internal order config controller makes a named config from a template once, for the company in session', function () { diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php index c8707ff52..a5156745b 100644 --- a/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigPoliciesTest.php @@ -97,6 +97,9 @@ function orderConfigPoliciesSetting(string $key, string $name): ?array ['value' => 'cancel', 'label' => 'Cancel the order'], ]) ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'customer_orders'))->toBe(['name' => 'customer_orders', 'type' => 'boolean', 'default' => false, 'choices' => null]) + // Numbers carry the range their rules allow. + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'offer_timeout'))->toMatchArray(['type' => 'number', 'min' => 10, 'max' => 120]) + ->and(orderConfigPoliciesSetting('dispatch.adhoc', 'radius'))->toMatchArray(['min' => 100, 'max' => 200000]) ->and(orderConfigPoliciesSetting('customer.ordering', 'payment_methods')['type'])->toBe('list') ->and(orderConfigPoliciesSetting('customer.ordering', 'require_settlement')['type'])->toBe('list') // An activity setting is a choice among the config's own activities. diff --git a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php index d71dd87fc..e084338e3 100644 --- a/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php +++ b/server/tests/Unit/Support/OrderConfig/OrderConfigTemplatesTest.php @@ -41,8 +41,20 @@ function orderConfigTemplatesFlow(array $flow): array test('the registry describes its templates and refuses unknown ones', function () { expect(OrderConfigTemplates::describe())->toBe([ - ['key' => 'transport', 'name' => 'Transport', 'description' => 'Default order configuration for transport'], - ['key' => 'passenger', 'name' => 'Passenger', 'description' => (new PassengerTemplate())->description()], + [ + 'key' => 'transport', + 'name' => 'Transport', + 'description' => 'Default order configuration for transport', + 'steps' => ['Order Created', 'Order Dispatched', 'Order Started', 'Driver Enroute', 'Order Completed'], + 'summary' => ['steps' => 5, 'policies' => 0, 'triggers' => 0, 'custom_fields' => 0], + ], + [ + 'key' => 'passenger', + 'name' => 'Passenger', + 'description' => (new PassengerTemplate())->description(), + 'steps' => ['Trip requested', 'Finding a driver', 'Driver on the way', 'Driver has arrived', 'Trip in progress', 'Trip completed'], + 'summary' => ['steps' => count((new PassengerTemplate())->attributes()['flow']), 'policies' => 6, 'triggers' => count((new PassengerTemplate())->attributes()['triggers']) + array_sum(array_map(fn ($activity) => count($activity['actions']), (new PassengerTemplate())->attributes()['flow'])), 'custom_fields' => count((new PassengerTemplate())->customFields())], + ], ]) ->and(OrderConfigTemplates::has('passenger'))->toBeTrue() ->and(OrderConfigTemplates::has('limousine'))->toBeFalse() From c6cb53f596b491ad7487365944607346ca57a634 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 16 Nov 2026 11:56:55 +0800 Subject: [PATCH 28/29] feat(order-configs): redesign policies, lifecycle, step triggers, order events and the flow canvas Policies and lifecycle read as plain sentences with the settings inline, showing what a setting left alone falls back to. A step's triggers live in its side panel under What happens here, and order events open from the Activity Flow canvas, so the Triggers tab goes. System configs can open a step to change what happens there. A new Overview tab summarises what happens to an order. Flow nodes show each step's role, code and actions, joined by curved connectors. --- addon/components/activity/form.hbs | 157 ++- addon/components/activity/form.js | 52 + addon/components/activity/logic-builder.hbs | 8 +- addon/components/order-config-manager.hbs | 1 + addon/components/order-config-manager.js | 17 +- .../order-config-manager/activity-flow.hbs | 60 +- .../order-config-manager/activity-flow.js | 311 +++-- .../order-config-manager/lifecycle.hbs | 307 +---- .../order-config-manager/lifecycle.js | 475 +++---- .../order-config-manager/overview.hbs | 86 ++ .../order-config-manager/overview.js | 179 +++ .../order-config-manager/policies.hbs | 153 +-- .../order-config-manager/policies.js | 495 ++++++- .../order-config-manager/triggers.hbs | 98 -- .../order-config-manager/triggers.js | 221 --- addon/components/order-config/inline-list.hbs | 25 + addon/components/order-config/inline-list.js | 33 + .../components/order-config/inline-number.hbs | 12 + .../components/order-config/inline-number.js | 36 + .../components/order-config/inline-select.hbs | 46 + .../components/order-config/inline-select.js | 37 + addon/components/order-config/notice.hbs | 6 + .../components/order-config/order-events.hbs | 75 ++ addon/components/order-config/order-events.js | 187 +++ .../order-config/sentence-field.hbs | 55 + .../components/order-config/trigger-list.hbs | 123 ++ addon/components/order-config/trigger-list.js | 205 +++ addon/components/order-config/unsaved-bar.hbs | 20 + addon/styles/fleetops-engine.css | 1200 ++++++++++++++++- addon/utils/order-config-action-meta.js | 52 + addon/utils/order-config-steps.js | 38 + addon/utils/sentence-parts.js | 35 + app/components/order-config/inline-list.js | 1 + app/components/order-config/inline-number.js | 1 + app/components/order-config/inline-select.js | 1 + app/components/order-config/notice.js | 1 + app/components/order-config/order-events.js | 1 + app/components/order-config/sentence-field.js | 1 + app/components/order-config/trigger-list.js | 1 + app/components/order-config/unsaved-bar.js | 1 + app/utils/order-config-action-meta.js | 1 + app/utils/order-config-steps.js | 1 + app/utils/sentence-parts.js | 1 + 43 files changed, 3720 insertions(+), 1096 deletions(-) create mode 100644 addon/components/order-config-manager/overview.hbs create mode 100644 addon/components/order-config-manager/overview.js delete mode 100644 addon/components/order-config-manager/triggers.hbs delete mode 100644 addon/components/order-config-manager/triggers.js create mode 100644 addon/components/order-config/inline-list.hbs create mode 100644 addon/components/order-config/inline-list.js create mode 100644 addon/components/order-config/inline-number.hbs create mode 100644 addon/components/order-config/inline-number.js create mode 100644 addon/components/order-config/inline-select.hbs create mode 100644 addon/components/order-config/inline-select.js create mode 100644 addon/components/order-config/notice.hbs create mode 100644 addon/components/order-config/order-events.hbs create mode 100644 addon/components/order-config/order-events.js create mode 100644 addon/components/order-config/sentence-field.hbs create mode 100644 addon/components/order-config/trigger-list.hbs create mode 100644 addon/components/order-config/trigger-list.js create mode 100644 addon/components/order-config/unsaved-bar.hbs create mode 100644 addon/utils/order-config-action-meta.js create mode 100644 addon/utils/order-config-steps.js create mode 100644 addon/utils/sentence-parts.js create mode 100644 app/components/order-config/inline-list.js create mode 100644 app/components/order-config/inline-number.js create mode 100644 app/components/order-config/inline-select.js create mode 100644 app/components/order-config/notice.js create mode 100644 app/components/order-config/order-events.js create mode 100644 app/components/order-config/sentence-field.js create mode 100644 app/components/order-config/trigger-list.js create mode 100644 app/components/order-config/unsaved-bar.js create mode 100644 app/utils/order-config-action-meta.js create mode 100644 app/utils/order-config-steps.js create mode 100644 app/utils/sentence-parts.js diff --git a/addon/components/activity/form.hbs b/addon/components/activity/form.hbs index e334ea4db..e867e946b 100644 --- a/addon/components/activity/form.hbs +++ b/addon/components/activity/form.hbs @@ -1,52 +1,109 @@ -
- - - - - - - {{t "activity.form.completes-order"}} - - - - - {{t "activity.form.require-pod"}} - - - {{#if @resource.require_pod}} - - + - {{/each}} - - + {{#each this.podOptions as |podOption|}} + + {{/each}} + + + {{/if}} + {{#unless this.readonlyDetails}} +
+ {{t "order-config-manager.step.developer-events"}} + {{t "order-config-manager.step.developer-events-help"}} + +
+ {{/unless}} + {{else if (eq this.tab "happens")}} +

{{t "order-config-manager.step.when-reaches" step=(or @resource.status @resource.code)}}

+ +

{{t "order-config-manager.step.footnote"}}

+ {{else}} +

{{t "order-config-manager.step.conditions-lead" step=(or @resource.status @resource.code)}}

+ {{#if this.readonlyDetails}} + + {{else}} + + {{/if}} {{/if}} - {{#unless (cannot "fleet-ops update order-config")}} - - - {{/unless}} - -
\ No newline at end of file + + diff --git a/addon/components/activity/form.js b/addon/components/activity/form.js index fd4a4079f..7d0bea445 100644 --- a/addon/components/activity/form.js +++ b/addon/components/activity/form.js @@ -3,8 +3,60 @@ import { tracked } from '@glimmer/tracking'; import { action } from '@ember/object'; import { underscore, capitalize, w } from '@ember/string'; import { task } from 'ember-concurrency'; +import { inject as service } from '@ember/service'; +/** + * A step of an order config's flow, in its side panel: Details (status, code, details, whether it + * completes the order and needs proof of delivery), What happens here (the triggers that run when + * an order reaches it) and Conditions (logic that must pass to reach it). + * + * The panel passes options on its overlay: `readonlyDetails` for system configs and steps that + * can't change, `actions` and `placeholders` from capabilities, and `initialTab`. + */ export default class ActivityFormComponent extends Component { + @service abilities; + @service intl; + + @tracked tab; + + constructor() { + super(...arguments); + this.tab = this.args.overlay?.initialTab ?? 'details'; + } + + get canUpdate() { + return this.abilities.can('fleet-ops update order-config'); + } + + get readonlyDetails() { + return !this.canUpdate || Boolean(this.args.overlay?.readonlyDetails); + } + + get triggers() { + return this.args.resource?.get?.('actions') ?? this.args.resource?.actions ?? []; + } + + get tabs() { + const tab = (key, label) => ({ key, label, selected: this.tab === key }); + return [ + tab('details', this.intl.t('order-config-manager.step.tab-details')), + tab('happens', this.intl.t('order-config-manager.step.tab-happens', { count: this.triggers.length })), + tab('conditions', this.intl.t('order-config-manager.step.tab-conditions')), + ]; + } + + @action selectTab(key) { + this.tab = key; + } + + @action setTriggers(triggers) { + this.args.resource.set('actions', triggers); + } + + @action toggle(key, value) { + this.args.resource.set(key, value); + } + /** * Proof of delivery options. * diff --git a/addon/components/activity/logic-builder.hbs b/addon/components/activity/logic-builder.hbs index 14bf3219d..a59ecaeee 100644 --- a/addon/components/activity/logic-builder.hbs +++ b/addon/components/activity/logic-builder.hbs @@ -1,16 +1,16 @@
-
{{t "activity.form.logic-builder.activity-logic"}}
+
{{or @title (t "activity.form.logic-builder.activity-logic")}}
- +
-
-
-
+ +
+
+
+
+ {{#if this.legend.length}} +
+ {{#each this.legend as |item|}} + {{item.label}} + {{/each}} +
+ {{/if}} + +
+
+
-
-
-
-
\ No newline at end of file diff --git a/addon/components/order-config-manager/activity-flow.js b/addon/components/order-config-manager/activity-flow.js index 3ed847ca8..2117d3d07 100644 --- a/addon/components/order-config-manager/activity-flow.js +++ b/addon/components/order-config-manager/activity-flow.js @@ -13,6 +13,29 @@ import inlineTask from '@fleetbase/ember-core/utils/inline-task'; import createFlowActivity from '../../utils/create-flow-activity'; import contextComponentCallback from '@fleetbase/ember-core/utils/context-component-callback'; import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from '../../utils/normalize-order-config-flow'; +import { ICON_GROUPS, actionIcon, actionLabel } from '../../utils/order-config-action-meta'; + +const NODE_WIDTH = 236; +const NODE_HEIGHT = 64; + +/** Role tile icons, drawn on a 24 × 24 grid. */ +const ROLE_ICONS = { + start: 'M8 5v14l11-7z', + step: 'M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6z', + complete: 'M5 12l5 5L20 7', + end: 'M7 7h10v10H7z', +}; + +/** Action icons on a node, drawn on a 24 × 24 grid, keyed by the icon names in order-config-action-meta. */ +const ACTION_PATHS = { + bell: 'M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10 21h4', + comments: 'M21 12a8 8 0 0 1-12 7l-5 1 1-4a8 8 0 1 1 16-4z', + 'comment-slash': 'M21 12a8 8 0 0 1-12 7l-5 1 1-4a8 8 0 1 1 16-4zM4 4l16 16', + 'file-invoice': 'M6 3h12v18l-3-2-3 2-3-2-3 2zM9 8h6M9 12h6', + tag: 'M3 12V4h8l10 10-8 8zM7.5 7.5h.01', + ban: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM5.6 5.6l12.8 12.8', + bolt: 'M13 3L5 14h6l-1 7 8-11h-6z', +}; /** * Manages the activity flow for order configuration, allowing users to create, edit, and view a sequence of activities. @@ -23,6 +46,10 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { @service notifications; @service intl; @service abilities; + @service fetch; + + /** Actions, events and placeholders triggers can use, from `order-configs/capabilities`. */ + @tracked capabilities = { actions: [], events: [], placeholders: [] }; /** * Represents the current state of the activity flow. @@ -94,6 +121,7 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { constructor(owner, { config, configManagerContext }) { super(...arguments); this.config = config; + this.loadCapabilities.perform(); configManagerContext.on('onConfigChanged', (newConfig) => { this.changeConfig(newConfig); @@ -256,46 +284,32 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * Initializes the custom JointJS shapes used in the activity flow. */ initializeActivityJointModel() { + const chip = (index) => [ + { tagName: 'rect', selector: `chip${index}`, className: 'flow-activity-chip' }, + { tagName: 'path', selector: `chipIcon${index}`, className: 'flow-activity-chip-icon' }, + ]; joint.shapes.fleetbase = {}; - joint.shapes.fleetbase.Activity = joint.shapes.standard.Rectangle.define( + joint.shapes.fleetbase.Activity = joint.dia.Element.define( 'fleetbase.Activity', { attrs: { - rect: { stroke: 'none', fillOpacity: 0 }, - text: { - textVerticalAnchor: 'middle', - textAnchor: 'middle', - refX: '50%', - refY: '50%', - fontSize: 14, - fill: '#333', - }, + body: { width: 'calc(w)', height: 'calc(h)', rx: 12, ry: 12 }, + tile: { x: 12, y: 'calc(0.5*h-16)', width: 32, height: 32, rx: 9, ry: 9 }, + tileIcon: { transform: 'translate(20, 24) scale(0.67)' }, + status: { x: 54, y: 'calc(0.5*h-4)', fontSize: 13, fontWeight: 600, textVerticalAnchor: 'middle' }, + meta: { x: 54, y: 'calc(0.5*h+13)', fontSize: 11, textVerticalAnchor: 'middle' }, }, }, { markup: [ - { - tagName: 'rect', - selector: 'body', - className: 'flow-activity', - }, - { - tagName: 'rect', - selector: 'pill', - className: 'flow-activity-status-pill', - }, - { - tagName: 'text', - selector: 'code', - }, - { - tagName: 'text', - selector: 'status', - }, - { - tagName: 'text', - selector: 'details', - }, + { tagName: 'rect', selector: 'body', className: 'flow-activity' }, + { tagName: 'rect', selector: 'tile', className: 'flow-activity-tile' }, + { tagName: 'path', selector: 'tileIcon', className: 'flow-activity-tile-icon' }, + { tagName: 'text', selector: 'status', className: 'flow-activity-status' }, + { tagName: 'text', selector: 'meta', className: 'flow-activity-meta' }, + ...chip(0), + ...chip(1), + ...chip(2), ], } ); @@ -315,6 +329,63 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { }); } + /** + * Saves the flow as it is on the canvas without redrawing it, for "Save step". + */ + @task *persistFlow() { + this.config.set('flow', this.serializeFlow()); + try { + yield this.config.save(); + this.notifications.success(this.intl.t('order-config-manager.step.saved')); + this.args.onConfigUpdated?.(this.config); + } catch (error) { + this.notifications.serverError(error); + } + } + + @task *loadCapabilities() { + try { + const { actions, events, placeholders } = yield this.fetch.get('order-configs/capabilities'); + this.capabilities = { actions: actions ?? [], events: events ?? [], placeholders: placeholders ?? [] }; + } catch { + this.capabilities = { actions: [], events: [], placeholders: [] }; + } + } + + get eventCount() { + return (this.config?.triggers ?? []).length; + } + + /** The actions used anywhere on the flow, for the legend. */ + get legend() { + const used = new Set( + Object.values(this.config?.flow ?? {}) + .flatMap((activity) => activity?.actions ?? []) + .map((trigger) => trigger?.action) + ); + return ICON_GROUPS.filter((group) => group.actions.some((name) => used.has(name))).map((group) => ({ + icon: group.icon, + label: this.intl.t(`order-config-manager.flow.${group.key}`), + })); + } + + /** + * Opens the order events: triggers for things that happen to an order outside its steps. + */ + @action openOrderEvents() { + this.resourceContextPanel.open({ + content: 'order-config/order-events', + title: this.intl.t('order-config-manager.events.title'), + panelContentClass: 'py-2 px-4', + resource: this.config, + config: this.config, + actions: this.capabilities.actions, + events: this.capabilities.events, + placeholders: this.capabilities.placeholders, + onSaved: (config) => this.args.onConfigUpdated?.(config), + }); + } + /** * If any context is provided then initialize the state. * @@ -577,21 +648,55 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * @returns {Object} - The link object that has been added to the graph. */ addLinkToGraph(parentActivity, childActivity) { - const link = new joint.shapes.standard.Link({ - source: { id: parentActivity.get('id') }, - target: { id: childActivity.get('id') }, - }); + const link = this.createLink(parentActivity, childActivity); link.addTo(this.graph); return link; } + /** + * A connector from a step to one it leads to: a smooth curve with an arrowhead, labelled "or" + * when it's the second (or later) way out of the step. + */ + createLink(parentActivity, childActivity) { + const siblings = (parentActivity.get('activities') ?? []).map((activity) => activity?.get?.('id')); + const isBranch = siblings.indexOf(childActivity.get('id')) > 0; + return new joint.shapes.standard.Link({ + source: { id: parentActivity.get('id'), anchor: { name: 'right' } }, + target: { id: childActivity.get('id'), anchor: { name: 'left' } }, + connector: { name: 'smooth' }, + attrs: { + line: { + class: 'flow-activity-link', + stroke: '#64748b', + strokeWidth: 1.6, + targetMarker: { type: 'path', d: 'M 9 -4.5 L 0 0 L 9 4.5', fill: 'none', 'stroke-width': 1.6 }, + }, + }, + labels: isBranch + ? [ + { + markup: [ + { tagName: 'rect', selector: 'labelBody', className: 'flow-activity-link-label' }, + { tagName: 'text', selector: 'labelText', className: 'flow-activity-link-label-text' }, + ], + attrs: { + labelText: { text: this.intl.t('order-config-manager.common.or'), fontSize: 11, textAnchor: 'middle', textVerticalAnchor: 'middle' }, + labelBody: { ref: 'labelText', x: 'calc(x-8)', y: 'calc(y-3)', width: 'calc(w+16)', height: 'calc(h+6)', rx: 9, ry: 9 }, + }, + position: { distance: 0.5 }, + }, + ] + : [], + }); + } + /** * Handles activity clicks within the JointJS paper. * @param {Object} elementView - The JointJS element view of the clicked activity. */ onActivityClicked(elementView) { - // Disable editing activity if core service or if cannot view order config - if (this.config.core_service || this.abilities.cannot('fleet-ops view order-config')) return; + // Anyone who can view the config can open a step; what they can change is decided in the panel. + if (this.abilities.cannot('fleet-ops view order-config')) return; const { model } = elementView; const activity = this.getActivityById(model.id); @@ -744,38 +849,10 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { */ createActivityNode(activity, positionals = {}) { const { width, height, x, y } = positionals; - const code = this.activityText(activity.get('code')); - const status = this.activityText(activity.get('status')); - const details = this.activityText(activity.get('details')); - const wrappedDetails = this.activityText(joint.util.breakText(details, { width })); const activityNode = new joint.shapes.fleetbase.Activity({ position: { x, y }, size: { width, height }, - attrs: { - pill: { - ref: 'code', - refWidth: code.length * 1.35, - refHeight: 5, - refX: -5, - refY: -2, - rx: 5, - ry: 5, - fill: '#374151', - stroke: '#374151', - strokeWidth: 1, - }, - code: { ref: 'pill', text: code, fill: 'white', fontSize: 14, textAnchor: 'left', refX: 15, refY: 20, yAlignment: 'middle' }, - status: { text: status, fill: 'white', fontSize: 14, fontWeight: 'bold', refY: 40, refX: 10, textAnchor: 'left' }, - details: { - text: wrappedDetails, - fill: 'white', - refY: 60, - fontSize: 14, - refX: 10, - textAnchor: 'left', - }, - body: { fill: activity.get('color'), stroke: '#374151', strokeWidth: 1, rx: 10, ry: 10 }, - }, + attrs: this.activityNodeAttrs(activity, width), interactive: false, activity: activity, }); @@ -786,6 +863,72 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { return activity; } + /** + * What a step's node shows: a tile for its role (start, step, completes the order, ends it), + * its status and code, and an icon for each thing that happens when an order reaches it. + * + * @param {Object} activity + * @param {Number} width + * @returns {Object} JointJS attrs + */ + activityNodeAttrs(activity, width = NODE_WIDTH) { + const code = this.activityText(activity.get('code')); + const status = this.activityText(activity.get('status')) || code; + const role = this.activityRole(activity); + const actions = (activity.get('actions') ?? []).map((trigger) => trigger?.action).filter(Boolean); + const shown = actions.slice(0, 3); + const roleText = role === 'step' ? '' : ` · ${this.intl.t(`order-config-manager.flow.role-${role}`)}`; + const textWidth = width - 54 - 12 - shown.length * 23; + const attrs = { + body: { class: 'flow-activity' }, + tile: { class: `flow-activity-tile flow-activity-tile--${role}` }, + tileIcon: { d: ROLE_ICONS[role], class: `flow-activity-tile-icon flow-activity-tile-icon--${role}` }, + status: { text: joint.util.breakText(status, { width: textWidth }, { 'font-size': 13, 'font-weight': 600 }, { maxLineCount: 1, ellipsis: true }) }, + meta: { text: joint.util.breakText(`${code}${roleText}`, { width: textWidth }, { 'font-size': 11 }, { maxLineCount: 1, ellipsis: true }) }, + }; + for (let index = 0; index < 3; index++) { + const name = shown[index]; + const chipX = width - 12 - (shown.length - index) * 23 + 3; + attrs[`chip${index}`] = name ? { display: 'block', x: chipX, y: 22, width: 20, height: 20, rx: 6, ry: 6 } : { display: 'none' }; + attrs[`chipIcon${index}`] = name + ? { display: 'block', d: ACTION_PATHS[actionIcon(name)] ?? ACTION_PATHS.bolt, transform: `translate(${chipX + 4.5}, 26.5) scale(0.46)` } + : { display: 'none' }; + if (name) { + attrs[`chip${index}`].title = actionLabel(this.intl, name, this.capabilities.actions); + } + } + + return attrs; + } + + /** + * A step's role in the lifecycle: where orders start, a step along the way, the step that + * completes them, or another step that ends them. + */ + activityRole(activity) { + const code = activity.get('code'); + const lifecycle = this.lifecycle ?? {}; + const root = getOrderConfigFlowRootCode(normalizeOrderConfigFlow(this.config?.flow ?? {}), lifecycle.initial); + if (activity.get('complete') || lifecycle.completed === code) { + return 'complete'; + } + if (lifecycle.canceled === code || (lifecycle.terminal ?? []).includes(code)) { + return 'end'; + } + if (code === (lifecycle.initial ?? root ?? 'created')) { + return 'start'; + } + return 'step'; + } + + /** Redraws a step's node after it changed in the side panel. */ + refreshActivityNode(activity) { + const node = activity?.get?.('node'); + if (node) { + node.attr(this.activityNodeAttrs(activity, node.size().width)); + } + } + /** * Determines the positioning for an activity node. * @param {Object} activity - The activity for which to determine positioning. @@ -794,13 +937,8 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { */ getActivityPositioning(activity, parentActivity) { const parentActivities = parentActivity ? parentActivity.get('activities') : []; - const width = 250; - const baseHeight = 90; - const lineHeight = 10; - const details = this.activityText(activity.get('details')); - const wrappedDetails = this.activityText(joint.util.breakText(details, { width })); - const numberOfLines = wrappedDetails.split('\n').length; - const height = baseHeight + lineHeight * (numberOfLines - 1); + const width = NODE_WIDTH; + const height = NODE_HEIGHT; let x = 100; if (parentActivity) { const parentActivityX = parentActivity.get('node').position().x; @@ -1059,17 +1197,25 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { * @param {Object} targetActivity - The target activity object that may be linked to the activity being edited. */ editActivity(activity, targetActivity) { - // if immutable do nothing - if (this.immutableActivities.includes(activity.get('code'))) return; + const isNew = Boolean(targetActivity) && !this.flow[activity.get('code')]; + // A system config's steps, and the standard dispatch steps, keep their details; what happens at them can still change. + const readonlyDetails = Boolean(this.config.core_service) || this.immutableActivities.includes(activity.get('code')); + const steps = Object.keys(this.flow); + const position = steps.indexOf(activity.get('code')) + 1; contextComponentCallback(this, 'onContextChanged', this._createContextualActivity(activity)); this.resourceContextPanel.open({ content: 'activity/form', - title: this.intl.t('common.create-new-resource', { resource: lowercase(this.intl.t('resource.activity')) }), + title: isNew ? this.intl.t('common.create-new-resource', { resource: lowercase(this.intl.t('resource.activity')) }) : activity.get('status') || activity.get('code'), panelContentClass: 'py-2 px-4', resource: activity, pojoResource: true, - saveTask: inlineTask(() => { + readonlyDetails, + initialTab: isNew ? 'details' : 'happens', + actions: this.capabilities.actions, + placeholders: this.capabilities.placeholders, + stepPosition: position > 0 ? this.intl.t('order-config-manager.step.kicker', { position, total: steps.length }) : null, + saveTask: inlineTask(async () => { // Check if the activity exists and if it's not the same instance being updated const existingActivity = this.flow[activity.get('code')]; if (existingActivity && existingActivity !== activity) { @@ -1081,10 +1227,13 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { if (targetActivity) { this.addNewLinkedActivity(targetActivity, activity); } + this.refreshActivityNode(activity); this.resourceContextPanel.closeAll(); + await this.persistFlow.perform(); }), onClose: () => { contextComponentCallback(this, 'onContextChanged', null); + this.refreshActivityNode(activity); }, }); } @@ -1128,11 +1277,7 @@ export default class OrderConfigManagerActivityFlowComponent extends Component { this.repositionActivities(targetActivity); // Link the new activity - const link = new joint.shapes.standard.Link({ - source: { id: targetActivity.get('id') }, - target: { id: newActivity.get('id') }, - }); - link.addTo(this.graph); + this.addLinkToGraph(targetActivity, newActivity); this.resizePaperWidthToFitActivities(); return newActivity; diff --git a/addon/components/order-config-manager/lifecycle.hbs b/addon/components/order-config-manager/lifecycle.hbs index 8799540a5..b002562cd 100644 --- a/addon/components/order-config-manager/lifecycle.hbs +++ b/addon/components/order-config-manager/lifecycle.hbs @@ -1,250 +1,73 @@ -
- -

{{t "order-config-manager.lifecycle.description"}}

- -
- -
+
+
+
+ {{#if this.isSystemConfig}} + + {{else if this.readonly}} + + {{/if}} - {{#if this.enabled}} -
-
-
{{t "order-config-manager.lifecycle.activities"}}
- {{#if (and this.canEdit this.hasActivities)}} - - {{/if}} +
+
+

{{t "order-config-manager.lifecycle.title"}}

+ {{t "order-config-manager.lifecycle.description"}}
-

{{t "order-config-manager.lifecycle.activities-help"}}

- - {{#if this.hasActivities}} -
- {{#each this.activityRows as |activity|}} -
- - - - -
{{activity.code}}{{#if activity.isInitial}} ({{t "order-config-manager.lifecycle.initial-short"}}){{/if}}
-
- - - - -
- - {{next.label}} - -
-
-
- - {{#if this.canEdit}} -
-
- {{/each}} -
- {{else}} -
{{t "order-config-manager.lifecycle.no-activities"}}
- {{/if}} +
+ {{#each this.lines as |line|}} + + {{/each}} +
+
- {{#if this.canEdit}} -
-
{{t "order-config-manager.lifecycle.add-activity"}}
-
- - - - - - - - - -
- -
+ {{#if this.own}} +
+

{{t "order-config-manager.lifecycle.checks"}}

+ {{#each this.checks as |check|}} +
+ + + + {{check.title}} + {{#if check.body}}{{check.body}}{{/if}} + + + {{#if check.fix}} +
- {{#if this.newActivityCodeTaken}} -
{{t "order-config-manager.lifecycle.problem-duplicate-code" code=this.newActivityCode}}
- {{/if}} -
- {{/if}} -
- -
- -
- - {{activity.label}} - {{activity.code}} - -
-
- - -
- - {{activity.label}} - -
-
+ {{/each}} + + {{/if}} - -
- - {{activity.label}} - {{activity.code}} - -
-
+ +
- -
- - {{activity.label}} - {{activity.code}} - +
\ No newline at end of file + {{/each}} + +
+
diff --git a/addon/components/order-config-manager/lifecycle.js b/addon/components/order-config-manager/lifecycle.js index 6712e5899..3249838bc 100644 --- a/addon/components/order-config-manager/lifecycle.js +++ b/addon/components/order-config-manager/lifecycle.js @@ -4,51 +4,33 @@ import { inject as service } from '@ember/service'; import { action } from '@ember/object'; import { isArray } from '@ember/array'; import { task } from 'ember-concurrency'; -import { underscore } from '@ember/string'; -import generateUUID from '@fleetbase/ember-core/utils/generate-uuid'; import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from '../../utils/normalize-order-config-flow'; +import sentenceParts from '../../utils/sentence-parts'; -/** Keys of `meta.lifecycle` understood by the server (see OrderConfig::lifecycle()). */ +const L = 'order-config-manager.lifecycle'; const DEFAULTS = { initial: null, completed: null, canceled: null, terminal: [], dispatch: true, strict_transitions: false }; - -const NEW_ACTIVITY = { status: '', code: '', details: '', color: '#1f2937' }; +const STANDARD = ['created', 'dispatched', 'started', 'completed']; /** - * Manages an order config's configured lifecycle (`meta.lifecycle`): the activity new orders start - * at, the activities that complete, cancel and end an order, whether orders may be dispatched and - * whether transitions must follow the flow. Without a configured lifecycle the default dispatch - * lifecycle applies. + * How orders of a config start and end: whether they follow the standard dispatch steps or the + * config's own, which step they start at, which complete or cancel them, which other steps end + * them, whether they're dispatched, and whether they must follow the flow's arrows. Stored under + * `meta.lifecycle`; without one the config follows the standard dispatch steps. * - * The activities themselves (the config's `flow`) can be defined here too, so a lifecycle can be - * built from scratch without the graph editor: add or remove activities, set their labels and the - * activities each one can move to. Flow and lifecycle are saved together. + * The steps themselves are edited on Activity Flow. Checks here point out steps orders would get + * stuck at. * * @extends Component */ export default class OrderConfigManagerLifecycleComponent extends Component { - @service modalsManager; @service notifications; @service abilities; @service intl; - /** The config being managed. */ @tracked config; - - /** Working copy of `meta.lifecycle`, or null when the config has none. */ @tracked lifecycle = null; - - /** Last saved lifecycle, to tell whether there is anything to save. */ @tracked saved = null; - /** Working copy of the config's flow, keyed by activity code, with next activities as codes. */ - @tracked flow = {}; - - /** Flow as last saved, serialized, to tell whether there is anything to save. */ - @tracked savedFlow = '{}'; - - /** The activity being added. */ - @tracked newActivity = { ...NEW_ACTIVITY }; - constructor(owner, { config, configManagerContext }) { super(...arguments); this.changeConfig(config); @@ -62,217 +44,285 @@ export default class OrderConfigManagerLifecycleComponent extends Component { return this.abilities.can('fleet-ops update order-config') && !this.config?.core_service; } - get enabled() { - return this.lifecycle !== null; + get readonly() { + return !this.canEdit; } - /** Activities of the flow as select options. */ - get activities() { - return Object.values(this.flow).map((activity) => ({ code: activity.code, label: activity.status || activity.code })); + get isSystemConfig() { + return Boolean(this.config?.core_service); } - /** Activities with their next activities resolved, for the editor. */ - get activityRows() { - return Object.values(this.flow).map((activity) => ({ - ...activity, - next: (activity.activities ?? []).map((code) => this.option(code)).filter(Boolean), - isInitial: this.lifecycle?.initial === activity.code, - })); + get own() { + return this.lifecycle !== null; } - get hasActivities() { - return Object.keys(this.flow).length > 0; + get flow() { + return normalizeOrderConfigFlow(this.config?.flow ?? {}); } - get newActivityCode() { - return underscore((this.newActivity.code || this.newActivity.status || '').trim()); + get steps() { + return Object.values(this.flow) + .filter((activity) => activity && (activity.code || activity.key)) + .map((activity) => ({ + code: activity.code ?? activity.key, + label: activity.status || activity.code || activity.key, + next: (isArray(activity.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean), + complete: Boolean(activity.complete), + })); } - get canAddActivity() { - const code = this.newActivityCode; - return this.canEdit && this.newActivity.status.trim() !== '' && code !== '' && !this.flow[code]; + label(code) { + return this.steps.find((step) => step.code === code)?.label ?? code; } - get newActivityCodeTaken() { - const code = this.newActivityCode; - return code !== '' && Boolean(this.flow[code]); + t(key, values) { + return this.intl.t(`${L}.${key}`, values); } - get selectedInitial() { - return this.option(this.lifecycle?.initial); - } + // ----- editing - get selectedCompleted() { - return this.option(this.lifecycle?.completed); + patch(patch) { + this.lifecycle = { ...(this.lifecycle ?? DEFAULTS), ...patch }; } - get selectedCanceled() { - return this.option(this.lifecycle?.canceled); + @action setMode(own) { + if (!own) { + this.lifecycle = null; + return; + } + this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : { ...DEFAULTS, terminal: [], initial: getOrderConfigFlowRootCode(this.flow) ?? null }; } - get selectedTerminal() { - return (this.lifecycle?.terminal ?? []).map((code) => this.option(code)).filter(Boolean); + @action discard() { + this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : null; } - get isDirty() { - return JSON.stringify(this.lifecycle) !== JSON.stringify(this.saved) || this.serializeFlow() !== this.savedFlow; + @action endAt(code) { + this.patch({ terminal: [...new Set([...(this.lifecycle?.terminal ?? []), code])] }); } - /** Problems that make the lifecycle unusable server-side. */ - get problems() { - if (!this.lifecycle) { - return []; - } + // ----- sentences - const problems = []; - const codes = this.activities.map((activity) => activity.code); - if (codes.length === 0) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-no-activities')); - } - if (!this.lifecycle.initial) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-initial-required')); - } + isUnsaved(key) { + return JSON.stringify(this.lifecycle?.[key] ?? null) !== JSON.stringify(this.saved?.[key] ?? null); + } - const referenced = [this.lifecycle.initial, this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean); - for (const code of new Set(referenced)) { - if (!codes.includes(code)) { - problems.push(this.intl.t('order-config-manager.lifecycle.problem-missing-activity', { code })); - } - } + stepChoice(key, ariaKey, { allowNone } = {}) { + const options = this.steps.map((step) => ({ value: step.code, label: step.label })); + return { + kind: 'choice', + value: this.lifecycle?.[key] ?? null, + isDefault: false, + label: this.lifecycle?.[key] ? this.label(this.lifecycle[key]) : this.t('not-set'), + invalid: !this.lifecycle?.[key] && !allowNone, + ariaLabel: this.t(ariaKey), + options: allowNone ? [{ value: null, label: this.t('not-set') }, ...options] : options, + onChange: (value) => this.patch({ [key]: value }), + }; + } - return problems; + flagChoice(key, pairs, ariaKey) { + const value = this.lifecycle?.[key] ?? DEFAULTS[key]; + return { + kind: 'choice', + value, + isDefault: value === DEFAULTS[key], + ariaLabel: this.t(ariaKey), + options: pairs.map(([optionValue, label]) => ({ value: optionValue, label, isDefault: optionValue === DEFAULTS[key] })), + onChange: (next) => this.patch({ [key]: next }), + }; } - get canSave() { - return this.canEdit && this.isDirty && this.problems.length === 0; + line(keys, key, controls, help, error) { + return { keys, parts: sentenceParts(this.intl, `${L}.${key}`, controls), help, error, unsaved: keys.some((k) => this.isUnsaved(k)) }; } - /** Arrow function so templates can call it as a helper: (this.option code). */ - option = (code) => { - return code ? (this.activities.find((activity) => activity.code === code) ?? { code, label: code }) : null; - }; + get lines() { + const modeLine = { + keys: ['mode'], + parts: sentenceParts(this.intl, `${L}.mode.sentence`, { + choice: { + kind: 'choice', + value: this.own, + isDefault: !this.own, + ariaLabel: this.t('mode-aria'), + options: [ + { value: false, label: this.t('mode.standard'), isDefault: true }, + { value: true, label: this.t('mode.own') }, + ], + onChange: (own) => this.setMode(own), + }, + }), + help: this.own ? this.t('mode-help-own') : this.t('mode-help-standard'), + unsaved: (this.lifecycle === null) !== (this.saved === null), + }; - changeConfig(config) { - this.config = config; - this.saved = this.normalize(config?.meta?.lifecycle); - this.lifecycle = this.normalize(config?.meta?.lifecycle); - this.flow = this.readFlow(config?.flow); - this.savedFlow = this.serializeFlow(); - this.newActivity = { ...NEW_ACTIVITY }; - } + if (!this.own) { + return [modeLine]; + } - /** The stored flow as plain activity objects with next activities as codes. */ - readFlow(flow) { - const normalized = normalizeOrderConfigFlow(flow ?? {}); - const result = {}; - Object.values(normalized).forEach((activity, index) => { - if (!activity || typeof activity !== 'object') { - return; - } - const code = activity.code ?? activity.key; - if (!code) { - return; - } - result[code] = { - ...activity, - code, - key: activity.key ?? code, - sequence: activity.sequence ?? index, - activities: (isArray(activity.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean), - }; - }); - return result; + const ends = new Set([this.lifecycle.completed, this.lifecycle.canceled].filter(Boolean)); + const endable = this.steps.filter((step) => !ends.has(step.code) && step.code !== this.lifecycle.initial).map((step) => step.code); + + return [ + modeLine, + this.line( + ['initial'], + 'initial', + { step: this.stepChoice('initial', 'initial-aria') }, + this.t('initial-help'), + this.lifecycle.initial ? null : this.t('problem-initial-required') + ), + this.line(['completed'], 'completed', { step: this.stepChoice('completed', 'completed-aria', { allowNone: true }) }, this.t('completed-help')), + this.line(['canceled'], 'canceled', { step: this.stepChoice('canceled', 'canceled-aria', { allowNone: true }) }, this.t('canceled-help')), + this.line( + ['terminal'], + 'terminal', + { + steps: { + kind: 'list', + items: (this.lifecycle.terminal ?? []).map((code) => ({ value: code, label: this.label(code) })), + options: endable.map((code) => ({ value: code, label: this.label(code) })), + emptyLabel: this.t('terminal-none'), + ariaLabel: this.t('terminal-aria'), + onChange: (terminal) => this.patch({ terminal }), + }, + }, + this.t('terminal-help') + ), + this.line( + ['dispatch'], + 'dispatch.sentence', + { + choice: this.flagChoice( + 'dispatch', + [ + [true, this.t('dispatch.on')], + [false, this.t('dispatch.off')], + ], + 'dispatch-aria' + ), + }, + this.t('dispatch-help') + ), + this.line( + ['strict_transitions'], + 'strict.sentence', + { + choice: this.flagChoice( + 'strict_transitions', + [ + [false, this.t('strict.off')], + [true, this.t('strict.on')], + ], + 'strict-aria' + ), + }, + this.t('strict-help') + ), + ]; } - serializeFlow() { - const serialized = {}; - Object.values(this.flow).forEach((activity) => { - // Graph-only state never belongs in the stored flow. - // eslint-disable-next-line no-unused-vars - const { node, id, parentId, _internalModel, ...stored } = activity; - serialized[activity.code] = { ...stored, activities: [...(activity.activities ?? [])] }; - }); - return JSON.stringify(serialized); + // ----- checks + + get endCodes() { + if (!this.lifecycle) { + return new Set(); + } + return new Set([this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean)); } - @action setNewActivityField(field, event) { - this.newActivity = { ...this.newActivity, [field]: event.target.value }; + /** Steps with nowhere to go that don't end the order: orders reaching them get stuck. */ + get deadEnds() { + return this.steps.filter((step) => step.next.length === 0 && !step.complete && !this.endCodes.has(step.code)); } - @action addActivity() { - if (!this.canAddActivity) { - return; + get missing() { + if (!this.lifecycle) { + return []; } + const codes = this.steps.map((step) => step.code); + const referenced = [this.lifecycle.initial, this.lifecycle.completed, this.lifecycle.canceled, ...(this.lifecycle.terminal ?? [])].filter(Boolean); + return [...new Set(referenced)].filter((code) => !codes.includes(code)); + } - const code = this.newActivityCode; - const activity = { - key: code, - code, - status: this.newActivity.status.trim(), - details: this.newActivity.details.trim(), - color: this.newActivity.color || '#1f2937', - sequence: Object.keys(this.flow).length, - activities: [], - events: [], - logic: [], - actions: [], - entities: [], - complete: false, - require_pod: false, - pod_method: 'scan', - options: {}, - internalId: generateUUID(), - }; + get checks() { + if (!this.own) { + return []; + } - this.flow = { ...this.flow, [code]: activity }; - if (this.lifecycle && !this.lifecycle.initial) { - this.lifecycle = { ...this.lifecycle, initial: code }; + const checks = []; + if (this.lifecycle.completed) { + checks.push({ ok: true, title: this.t('check-completable', { step: this.label(this.lifecycle.completed) }) }); + } + this.missing.forEach((code) => checks.push({ ok: false, title: this.t('problem-missing-activity', { code }) })); + this.deadEnds.forEach((step) => + checks.push({ + ok: false, + title: this.t('check-dead-end', { step: step.label }), + body: this.t('check-dead-end-body'), + fix: this.canEdit ? () => this.endAt(step.code) : null, + }) + ); + if (this.deadEnds.length === 0) { + checks.push({ ok: true, title: this.t('check-no-dead-ends') }); } - this.newActivity = { ...NEW_ACTIVITY }; - } - @action removeActivity(code) { - const flow = { ...this.flow }; - delete flow[code]; - Object.keys(flow).forEach((key) => { - flow[key] = { ...flow[key], activities: flow[key].activities.filter((next) => next !== code) }; - }); - this.flow = flow; + return checks; + } - if (this.lifecycle) { - const without = (value) => (value === code ? null : value); - this.lifecycle = { - ...this.lifecycle, - initial: without(this.lifecycle.initial), - completed: without(this.lifecycle.completed), - canceled: without(this.lifecycle.canceled), - terminal: this.lifecycle.terminal.filter((item) => item !== code), - }; + // ----- at a glance + + get glance() { + if (!this.own) { + const label = (code) => this.intl.t(`${L}.standard.${code}`); + return [ + { title: this.t('glance-starts'), items: [{ role: 'start', label: label('created') }] }, + { title: this.t('glance-along'), items: STANDARD.slice(1, 3).map((code) => ({ role: 'step', label: label(code) })) }, + { + title: this.t('glance-ends'), + items: [ + { role: 'complete', label: label('completed'), note: this.t('glance-complete') }, + { role: 'end', label: label('canceled'), note: this.t('glance-canceled') }, + ], + }, + ]; } - } - @action setActivityField(code, field, event) { - this.flow = { ...this.flow, [code]: { ...this.flow[code], [field]: event.target.value } }; + const { initial, completed, canceled, terminal = [] } = this.lifecycle; + const ends = this.endCodes; + return [ + { title: this.t('glance-starts'), items: initial ? [{ role: 'start', label: this.label(initial) }] : [] }, + { title: this.t('glance-along'), items: this.steps.filter((step) => step.code !== initial && !ends.has(step.code)).map((step) => ({ role: 'step', label: step.label })) }, + { + title: this.t('glance-ends'), + items: [ + completed ? { role: 'complete', label: this.label(completed), note: this.t('glance-complete') } : null, + canceled ? { role: 'end', label: this.label(canceled), note: this.t('glance-canceled') } : null, + ...terminal.map((code) => ({ role: 'end', label: this.label(code) })), + ].filter(Boolean), + }, + { + title: this.t('glance-rules'), + items: [ + { role: 'step', label: this.lifecycle.dispatch === false ? this.t('glance-never-dispatched') : this.t('glance-dispatched') }, + { role: 'step', label: this.lifecycle.strict_transitions ? this.t('glance-strict') : this.t('glance-any') }, + ], + }, + ]; } - @action setNextActivities(code, selected) { - this.flow = { ...this.flow, [code]: { ...this.flow[code], activities: (selected ?? []).map((activity) => activity.code) } }; + // ----- saving + + get unsavedCount() { + return this.lines.filter((line) => line.unsaved).length; } - /** Drops the default dispatch activities so a lifecycle can be designed from nothing. */ - @action startBlankFlow() { - this.modalsManager.confirm({ - title: this.intl.t('order-config-manager.lifecycle.blank-flow-title'), - body: this.intl.t('order-config-manager.lifecycle.blank-flow-body'), - acceptButtonText: this.intl.t('order-config-manager.lifecycle.blank-flow-confirm'), - confirm: (modal) => { - this.flow = {}; - if (this.lifecycle) { - this.lifecycle = { ...this.lifecycle, initial: null, completed: null, canceled: null, terminal: [] }; - } - modal.done(); - }, - }); + get errorHint() { + if (!this.lifecycle) { + return null; + } + return !this.lifecycle.initial || this.missing.length ? this.t('save-blocked') : null; } normalize(lifecycle) { @@ -289,47 +339,17 @@ export default class OrderConfigManagerLifecycleComponent extends Component { }; } - @action toggleEnabled(enabled) { - if (enabled) { - const flow = normalizeOrderConfigFlow(this.config?.flow ?? {}); - this.lifecycle = this.saved ? { ...this.saved, terminal: [...this.saved.terminal] } : { ...DEFAULTS, terminal: [], initial: getOrderConfigFlowRootCode(flow) ?? null }; - return; - } + changeConfig(config) { + this.config = config; + this.saved = this.normalize(config?.meta?.lifecycle); + this.lifecycle = this.normalize(config?.meta?.lifecycle); + } - if (this.saved) { - this.modalsManager.confirm({ - title: this.intl.t('order-config-manager.lifecycle.remove-title'), - body: this.intl.t('order-config-manager.lifecycle.remove-body'), - acceptButtonText: this.intl.t('order-config-manager.lifecycle.remove-confirm'), - confirm: async (modal) => { - modal.startLoading(); - this.lifecycle = null; - await this.save.perform(); - modal.done(); - }, - decline: (modal) => { - modal.done(); - }, - }); + @task *save() { + if (this.errorHint) { return; } - this.lifecycle = null; - } - - @action setActivity(key, activity) { - this.lifecycle = { ...this.lifecycle, [key]: activity?.code ?? null }; - } - - @action setTerminal(activities) { - this.lifecycle = { ...this.lifecycle, terminal: (activities ?? []).map((activity) => activity.code) }; - } - - @action setFlag(key, value) { - this.lifecycle = { ...this.lifecycle, [key]: Boolean(value) }; - } - - @task *save() { const meta = { ...(this.config.meta ?? {}) }; if (this.lifecycle) { meta.lifecycle = { ...this.lifecycle }; @@ -339,19 +359,16 @@ export default class OrderConfigManagerLifecycleComponent extends Component { try { this.config.set('meta', meta); - this.config.set('flow', JSON.parse(this.serializeFlow())); yield this.config.save(); this.saved = this.normalize(this.lifecycle); this.lifecycle = this.normalize(this.lifecycle); - this.savedFlow = this.serializeFlow(); - this.notifications.success(this.intl.t('order-config-manager.lifecycle.saved', { orderConfigName: this.config.name })); + this.notifications.success(this.t('saved', { orderConfigName: this.config.name })); if (typeof this.args.onConfigUpdated === 'function') { this.args.onConfigUpdated(this.config); } } catch (error) { this.config.rollbackAttributes(); this.lifecycle = this.normalize(this.config.meta?.lifecycle); - this.flow = this.readFlow(this.config.flow); this.notifications.serverError(error); } } diff --git a/addon/components/order-config-manager/overview.hbs b/addon/components/order-config-manager/overview.hbs new file mode 100644 index 000000000..899780b12 --- /dev/null +++ b/addon/components/order-config-manager/overview.hbs @@ -0,0 +1,86 @@ +
+
+
+
+

{{t "order-config-manager.overview.title" config=this.config.name}}

+ {{t "order-config-manager.overview.readonly-hint"}} +
+ + {{#if this.before}} +
+ 0 +
+
+ {{t "order-config-manager.overview.before"}} + +
+ {{#each this.before as |rule|}} + {{rule}} + {{/each}} +
+
+ {{/if}} + +
    + {{#each this.steps as |step|}} +
  1. +
    + {{step.number}} + {{#unless step.isLast}}{{/unless}} +
    +
    +
    + + {{step.label}} + {{step.code}} + {{#if step.tag}}{{step.tag}}{{/if}} + + +
    +
    +
    + {{t "order-config-manager.overview.happens-here"}} + {{#each step.happens as |item|}} + {{item.text}} + {{else}} + {{t "order-config-manager.overview.nothing"}} + {{/each}} +
    +
    + {{t "order-config-manager.overview.policies-apply"}} + {{#each step.rules as |rule|}} + {{rule}} + {{else}} + {{t "order-config-manager.overview.none"}} + {{/each}} +
    +
    +
    +
  2. + {{/each}} +
+
+ + +
+
diff --git a/addon/components/order-config-manager/overview.js b/addon/components/order-config-manager/overview.js new file mode 100644 index 000000000..e3392e2a1 --- /dev/null +++ b/addon/components/order-config-manager/overview.js @@ -0,0 +1,179 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action, get } from '@ember/object'; +import { task } from 'ember-concurrency'; +import orderConfigSteps from '../../utils/order-config-steps'; +import { actionIcon, triggerSummary } from '../../utils/order-config-action-meta'; + +const O = 'order-config-manager.overview'; +const EVENT_KEYS = { + 'order.created': 'created', + 'order.completed': 'completed', + 'order.canceled': 'canceled', + 'dispatch.offer_exhausted': 'exhausted', + 'driver.approaching': 'approaching', +}; + +/** + * What happens to an order of this config, read-only: before it's placed, at each step, and at + * any time. Each part links to the tab where it's changed. + * + * @extends Component + */ +export default class OrderConfigManagerOverviewComponent extends Component { + @service fetch; + @service intl; + + @tracked config; + @tracked actions = []; + + constructor(owner, { config, configManagerContext }) { + super(...arguments); + this.config = config; + this.loadCapabilities.perform(); + + configManagerContext.on('onConfigChanged', (newConfig) => { + this.config = newConfig; + }); + } + + @task *loadCapabilities() { + try { + const { actions } = yield this.fetch.get('order-configs/capabilities'); + this.actions = actions ?? []; + } catch { + this.actions = []; + } + } + + @action go(tab) { + this.args.onSwitchTab?.(tab); + } + + t(key, values) { + return this.intl.t(`${O}.${key}`, values); + } + + policy(key, name) { + return get(this.config?.policies ?? {}, `${key}.${name}`); + } + + get lifecycle() { + return this.config?.meta?.lifecycle ?? null; + } + + get endCodes() { + const lifecycle = this.lifecycle ?? {}; + return new Set([lifecycle.completed, lifecycle.canceled, ...(lifecycle.terminal ?? [])].filter(Boolean)); + } + + get before() { + const items = []; + const methods = this.policy('customer.ordering', 'payment_methods') ?? []; + if (methods.length) { + items.push(this.t('rule-payment', { methods: methods.map((m) => this.methodLabel(m)).join(', ') })); + } + if (this.policy('customer.ordering', 'require_quote')) { + items.push(this.t('rule-quote')); + } + const settle = this.policy('customer.ordering', 'require_settlement') ?? []; + if (settle.length) { + items.push(this.t('rule-settlement', { methods: settle.map((m) => this.methodLabel(m)).join(', ') })); + } + const interactions = ['chat', 'rating', 'share_tracking'].filter((name) => this.policy('customer.interactions', name)); + if (interactions.length) { + items.push(this.t('rule-interactions', { list: interactions.map((name) => this.t(`interaction-${name}`)).join(', ') })); + } + return items; + } + + methodLabel(method) { + const key = `order-config-manager.policies.ordering.method.${method}`; + return this.intl.exists(key) ? this.intl.t(key) : method; + } + + get steps() { + const steps = orderConfigSteps(this.config); + const label = (code) => steps.find((step) => step.code === code)?.label ?? code; + const adhoc = this.policy('dispatch.adhoc', 'customer_orders'); + const cancelUntil = this.policy('customer.cancellation', 'allowed_until'); + const cancelOff = this.policy('customer.cancellation', 'enabled') === false; + const reprice = this.policy('pricing', 'reprice_on_completion'); + const meterFrom = this.policy('pricing', 'metering_starts_at'); + const rating = this.policy('customer.interactions', 'rating'); + const cancelIndex = cancelUntil ? steps.findIndex((step) => step.code === cancelUntil) : -1; + + return steps.map((step, index) => { + const isComplete = step.activity?.complete || this.lifecycle?.completed === step.code; + const ends = isComplete || this.endCodes.has(step.code); + const rules = []; + if (index === 0 && adhoc) { + rules.push(this.t('rule-offered')); + } + if (index === 0 && this.policy('dispatch.matching', 'vehicle_type')) { + rules.push(this.t('rule-vehicle')); + } + if (!cancelOff && cancelIndex >= 0 && !ends) { + rules.push(index < cancelIndex ? this.t('rule-can-cancel') : this.t('rule-cannot-cancel')); + } + if (reprice && meterFrom === step.code) { + rules.push(this.t('rule-metering')); + } + if (isComplete && reprice) { + rules.push(this.t('rule-repriced')); + } + if (isComplete && rating) { + rules.push(this.t('rule-rating')); + } + const happens = (step.activity?.actions ?? []).map((trigger) => ({ icon: actionIcon(trigger.action), text: triggerSummary(this.intl, trigger, this.actions) })); + + return { + ...step, + number: index + 1, + happens, + rules, + tag: isComplete ? this.t('tag-completes') : ends ? (step.branchFrom ? this.t('branch-from', { step: label(step.branchFrom) }) : this.t('tag-ends')) : null, + ends, + isLast: index === steps.length - 1, + }; + }); + } + + get anyTime() { + return (this.config?.triggers ?? []).map((trigger) => { + const event = EVENT_KEYS[trigger.event]; + const options = trigger.options ?? {}; + const when = event ? this.intl.t(`order-config-manager.events.${event}-menu`, {}) : trigger.event; + const detail = + trigger.event === 'driver.approaching' + ? this.intl.t('order-config-manager.events.approaching-short', { + metres: options.distance ?? 500, + target: this.intl.t(`order-config-manager.events.target-${options.target === 'dropoff' ? 'dropoff' : 'pickup'}`), + }) + : when; + return { when: detail, then: triggerSummary(this.intl, trigger, this.actions), hasCondition: (trigger.when ?? []).length > 0 }; + }); + } + + get glance() { + const steps = this.steps; + const automatic = steps.reduce((sum, step) => sum + step.happens.length, 0) + this.anyTime.length; + let changed = 0; + const walk = (node) => { + Object.values(node ?? {}).forEach((value) => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + walk(value); + } else { + changed += 1; + } + }); + }; + walk(this.config?.policies); + return [ + this.t('glance-steps', { count: steps.length, ends: steps.filter((step) => step.ends).length }), + this.t('glance-automatic', { count: automatic }), + this.t('glance-policies', { count: changed }), + ]; + } +} diff --git a/addon/components/order-config-manager/policies.hbs b/addon/components/order-config-manager/policies.hbs index efd3e0b80..94f1ba629 100644 --- a/addon/components/order-config-manager/policies.hbs +++ b/addon/components/order-config-manager/policies.hbs @@ -1,81 +1,84 @@ -
-

{{t "order-config-manager.policies.description"}}

+
+
+ - {{#if this.loadPolicies.isRunning}} -
- {{/if}} +
+ {{#if this.readonly}} + + {{else if this.isSystemConfig}} + + {{/if}} + {{#if this.allDefaults}} + + {{/if}} - {{#each this.rows as |policy|}} - -

{{policy.description}}

-
- {{#each policy.settings as |setting|}} - - {{#if (eq setting.type "boolean")}} - - {{else if (eq setting.type "choice")}} - - {{else if (eq setting.type "list")}} - - {{item}} - - {{else}} -
+ {{/if}} + + {{#each this.groups as |group|}} +
+
+
+

{{group.title}}

+ {{#if group.isExtension}} + {{t "order-config-manager.policies.extension-badge"}} + {{/if}} +
+ {{group.description}} +
+
+ {{#each group.lines as |line|}} + - {{/if}} - {{#if (and setting.isSet this.canEdit)}} - - {{/if}} - - {{/each}} -
- - {{/each}} + {{/each}} +
+ + {{/each}} - {{#if this.canEdit}} -
-
- {{/if}} -
\ No newline at end of file +
+
diff --git a/addon/components/order-config-manager/policies.js b/addon/components/order-config-manager/policies.js index 6e03ac0e6..d52df1ccf 100644 --- a/addon/components/order-config-manager/policies.js +++ b/addon/components/order-config-manager/policies.js @@ -4,12 +4,19 @@ import { inject as service } from '@ember/service'; import { action, get } from '@ember/object'; import { task } from 'ember-concurrency'; import humanize from '@fleetbase/ember-core/utils/humanize'; +import sentenceParts from '../../utils/sentence-parts'; + +const P = 'order-config-manager.policies'; +const PAYMENT_METHODS = ['cash', 'card', 'bank_transfer', 'wallet']; /** - * Manages an order config's policies: the settings that decide how its orders behave, such as how - * adhoc orders are offered, what customers may do and whether a completed order is priced again. - * The policies and their settings come from the server (`order-configs/capabilities`), so a policy - * an extension registers shows up here too. A setting left at its default isn't stored. + * An order config's policies, written as plain sentences with the settings inline. Each built-in + * policy has its own sentences; a policy an extension registers reads "Label: [control]" for each + * of its settings. A setting left at its default isn't stored, and reads as the default. + * + * Policies and their settings come from `order-configs/capabilities`; the company's dispatch + * defaults (offer method, time, radius) come from Settings → Dispatch, so placeholders show what + * an empty setting falls back to. * * @extends Component */ @@ -25,16 +32,20 @@ export default class OrderConfigManagerPoliciesComponent extends Component { /** The registered policies, each with its settings. */ @tracked policies = []; - /** Working copy of the config's stored policies. */ + /** Working copy of the config's stored policies, keyed by policy key. */ @tracked values = {}; - /** Stored policies as last saved, serialized, to tell whether there is anything to save. */ - @tracked saved = '{}'; + /** The stored policies as last saved, keyed by policy key. */ + @tracked savedValues = {}; + + /** The company's adhoc dispatch defaults. */ + @tracked companyDefaults = { adhoc_strategy: 'sequential', adhoc_offer_timeout: 20, adhoc_distance: 6000 }; constructor(owner, { config, configManagerContext }) { super(...arguments); this.changeConfig(config); this.loadPolicies.perform(); + this.loadCompanyDefaults.perform(); configManagerContext.on('onConfigChanged', (newConfig) => { this.changeConfig(newConfig); @@ -45,52 +56,74 @@ export default class OrderConfigManagerPoliciesComponent extends Component { return this.abilities.can('fleet-ops update order-config'); } - get isDirty() { - return JSON.stringify(this.values) !== this.saved; + get readonly() { + return !this.canEdit; + } + + get isSystemConfig() { + return Boolean(this.config?.core_service); + } + + get allDefaults() { + return Object.values(this.values).every((settings) => Object.keys(settings ?? {}).length === 0); + } + + get unsavedCount() { + return this.lines.filter((line) => line.unsaved).length; } - /** The config's activities, for settings that name one. */ - get activityChoices() { + get errorCount() { + return this.lines.filter((line) => line.error).length; + } + + get errorHint() { + return this.errorCount ? this.intl.t(`${P}.save-hint-errors`, { count: this.errorCount }) : null; + } + + get lines() { + return this.groups.flatMap((group) => group.lines); + } + + /** The config's steps, for settings that name one. */ + get steps() { return Object.values(this.config?.flow ?? {}) .filter((activity) => activity && activity.code) .map((activity) => ({ value: activity.code, label: activity.status || activity.code })); } - /** Policies with each setting's current value and choices, for the template. */ - get rows() { - return this.policies.map((policy) => ({ - ...policy, - settings: (policy.settings ?? []).map((setting) => ({ - ...setting, - label: humanize(setting.name), - value: this.valueOf(policy.key, setting), - isSet: this.storedValue(policy.key, setting.name) !== undefined, - options: this.optionsFor(setting), - })), - })); - } + // ----- reading and writing values - storedValue(policyKey, name) { + stored(policyKey, name) { return this.values?.[policyKey]?.[name]; } - valueOf(policyKey, setting) { - const stored = this.storedValue(policyKey, setting.name); - return stored === undefined ? setting.default : stored; + definition(policyKey) { + return this.policies.find((policy) => policy.key === policyKey); } - optionsFor(setting) { - if (setting.type !== 'choice') { - return null; - } + setting(policyKey, name) { + return (this.definition(policyKey)?.settings ?? []).find((setting) => setting.name === name); + } - const choices = setting.choices === 'activity' ? this.activityChoices : (setting.choices ?? []); - return [{ value: null, label: this.intl.t('order-config-manager.policies.default') }, ...choices]; + valueOf(policyKey, name) { + const stored = this.stored(policyKey, name); + return stored === undefined ? this.setting(policyKey, name)?.default : stored; + } + + isDefault(policyKey, name) { + return this.stored(policyKey, name) === undefined; + } + + isUnsaved(policyKey, name) { + return JSON.stringify(this.values?.[policyKey]?.[name]) !== JSON.stringify(this.savedValues?.[policyKey]?.[name]); } @action setValue(policyKey, name, value) { const policy = { ...(this.values[policyKey] ?? {}) }; - if (value === '' || value === undefined) { + const setting = this.setting(policyKey, name); + const isEmptyList = Array.isArray(value) && value.length === 0; + // Choosing the default, or emptying a setting, stores nothing so it keeps following the default. + if (value === '' || value === undefined || value === null || isEmptyList || JSON.stringify(value) === JSON.stringify(setting?.default)) { delete policy[name]; } else { policy[name] = value; @@ -99,33 +132,374 @@ export default class OrderConfigManagerPoliciesComponent extends Component { this.values = { ...this.values, [policyKey]: policy }; } - @action setNumber(policyKey, name, event) { - const raw = event?.target?.value ?? event; - this.setValue(policyKey, name, raw === '' || raw === null ? undefined : Number(raw)); + @action reset(policyKey, names) { + const policy = { ...(this.values[policyKey] ?? {}) }; + names.forEach((name) => delete policy[name]); + this.values = { ...this.values, [policyKey]: policy }; + } + + @action discard() { + this.values = JSON.parse(JSON.stringify(this.savedValues)); + } + + // ----- building sentences + + t(key, values) { + return this.intl.t(`${P}.${key}`, values); + } + + /** A choice part for a setting, from `[value, label]` pairs. */ + choice(policyKey, name, pairs, ariaKey) { + const setting = this.setting(policyKey, name); + return { + kind: 'choice', + value: this.valueOf(policyKey, name), + isDefault: this.isDefault(policyKey, name), + ariaLabel: this.t(ariaKey), + options: pairs.map(([value, label]) => ({ value, label, isDefault: value === (setting?.default ?? null) })), + onChange: (value) => this.setValue(policyKey, name, value), + }; + } + + /** An on/off setting as a two-way choice. */ + toggle(policyKey, name, offLabel, onLabel, ariaKey) { + return this.choice( + policyKey, + name, + [ + [false, offLabel], + [true, onLabel], + ], + ariaKey + ); + } + + /** A number part with the range from the setting's rules. Returns `[part, error]`. */ + number(policyKey, name, defaultLabel, ariaKey, width) { + const setting = this.setting(policyKey, name) ?? {}; + const value = this.stored(policyKey, name); + const n = Number(value); + const invalid = value !== undefined && (Number.isNaN(n) || (setting.min !== undefined && n < setting.min) || (setting.max !== undefined && n > setting.max)); + const part = { + kind: 'number', + value: value ?? '', + defaultLabel, + invalid, + width, + ariaLabel: this.t(ariaKey), + onChange: (number) => this.setValue(policyKey, name, number), + }; + + return [part, invalid ? this.intl.t('order-config-manager.common.number-range-error', { min: setting.min, max: setting.max }) : null]; + } + + methodLabel(method) { + const key = `${P}.ordering.method.${method}`; + return this.intl.exists(key) ? this.intl.t(key) : humanize(method); + } + + list(policyKey, name, choices, emptyKey, ariaKey) { + const values = this.valueOf(policyKey, name) ?? []; + return { + kind: 'list', + items: values.map((value) => ({ value, label: this.methodLabel(value) })), + options: choices.map((value) => ({ value, label: this.methodLabel(value) })), + emptyLabel: this.intl.t('order-config-manager.common.default-suffix', { value: this.t(emptyKey) }), + ariaLabel: this.t(ariaKey), + onChange: (list) => this.setValue(policyKey, name, list), + }; + } + + /** A sentence line. `settings` are the `[policyKey, name]` pairs it shows. */ + line(policyKey, names, key, controls, { help, error, dim, values } = {}) { + return { + policyKey, + names, + parts: sentenceParts(this.intl, `${P}.${key}`, controls, values), + help, + error, + dim, + unsaved: names.some((name) => this.isUnsaved(policyKey, name)), + isSet: names.some((name) => !this.isDefault(policyKey, name)), + canReset: names.some((name) => !this.isDefault(policyKey, name)), + onReset: () => this.reset(policyKey, names), + }; + } + + strategyLabel(value) { + const key = `${P}.offering.strategy.${value}`; + if (this.intl.exists(key)) { + return this.intl.t(key); + } + return (this.setting('dispatch.adhoc', 'strategy')?.choices ?? []).find((choice) => choice.value === value)?.label ?? humanize(value ?? ''); } - @action setText(policyKey, name, event) { - this.setValue(policyKey, name, event?.target?.value ?? event); + stepLabel(code) { + return this.steps.find((step) => step.value === code)?.label ?? code; } - @action addListItem(policyKey, setting, item) { - const list = [...(this.valueOf(policyKey, setting) ?? [])]; - if (item && !list.includes(item)) { - list.push(item); + // ----- groups + + get groups() { + if (!this.policies.length) { + return []; } - this.setValue(policyKey, setting.name, list); + + const known = ['dispatch.adhoc', 'dispatch.matching', 'customer.ordering', 'customer.cancellation', 'customer.interactions', 'pricing']; + const groups = [this.offeringGroup(), this.driversGroup(), this.orderingGroup(), this.cancellingGroup(), this.interactionsGroup(), this.priceGroup()].filter(Boolean); + const extensions = this.policies.filter((policy) => !known.includes(policy.key)).map((policy) => this.extensionGroup(policy)); + + return [...groups, ...extensions].map((group) => { + const set = group.lines.filter((line) => line.isSet).length; + const unsaved = group.lines.filter((line) => line.unsaved).length; + return { + ...group, + anchor: `oc-policy-${group.id.replace(/[^a-z0-9]+/gi, '-')}`, + navCount: [set ? this.t('nav-set', { count: set }) : this.t('nav-defaults'), unsaved ? this.t('nav-unsaved', { count: unsaved }) : null].filter(Boolean).join(' · '), + hasUnsaved: unsaved > 0, + }; + }); + } + + offeringGroup() { + const K = 'dispatch.adhoc'; + if (!this.definition(K)) return null; + const company = this.companyDefaults; + const offering = this.valueOf(K, 'customer_orders') === true; + const strategy = this.valueOf(K, 'strategy') ?? company.adhoc_strategy; + const dimHelp = offering ? null : this.t('applies-when-offered'); + const strategyChoices = (this.setting(K, 'strategy')?.choices ?? []).map((choice) => [choice.value, this.strategyLabel(choice.value)]); + const strategyBase = this.choice(K, 'strategy', strategyChoices, 'offering.strategy-aria'); + // An empty strategy follows the company's, so that is the option marked as the default. + const strategyPart = { ...strategyBase, value: strategy, options: strategyBase.options.map((option) => ({ ...option, isDefault: option.value === company.adhoc_strategy })) }; + const [seconds, secondsError] = this.number(K, 'offer_timeout', String(company.adhoc_offer_timeout ?? 20), 'offering.seconds-aria', 132); + const [metres, metresError] = this.number(K, 'radius', Number(company.adhoc_distance ?? 6000).toLocaleString(), 'offering.radius-aria', 150); + const companyHelp = this.t('offering.strategy-help', { strategy: this.strategyLabel(company.adhoc_strategy), seconds: company.adhoc_offer_timeout ?? 20 }); + + return { + id: K, + nav: this.t('offering.nav'), + title: this.t('offering.title'), + description: this.t('offering.description'), + lines: [ + this.line( + K, + ['customer_orders'], + 'offering.customer-orders.sentence', + { choice: this.toggle(K, 'customer_orders', this.t('offering.customer-orders.wait'), this.t('offering.customer-orders.offer'), 'offering.customer-orders-aria') }, + { help: this.t('offering.customer-orders-help') } + ), + strategy === 'sequential' + ? this.line( + K, + ['strategy', 'offer_timeout'], + 'offering.strategy.sentence', + { strategy: strategyPart, seconds }, + { help: dimHelp ?? companyHelp, error: secondsError, dim: !offering } + ) + : this.line(K, ['strategy', 'offer_timeout'], 'offering.strategy-only', { strategy: strategyPart }, { help: dimHelp ?? companyHelp, dim: !offering }), + this.line( + K, + ['radius'], + 'offering.radius', + { metres }, + { help: dimHelp ?? this.t('offering.radius-help', { metres: Number(company.adhoc_distance ?? 6000).toLocaleString() }), error: metresError, dim: !offering } + ), + this.line( + K, + ['on_exhausted'], + 'offering.exhausted.sentence', + { + choice: this.choice( + K, + 'on_exhausted', + [ + ['keep_open', this.t('offering.exhausted.keep-open')], + ['cancel', this.t('offering.exhausted.cancel')], + ], + 'offering.exhausted-aria' + ), + }, + { help: dimHelp ?? this.t('offering.exhausted-help'), dim: !offering } + ), + ], + }; + } + + driversGroup() { + const K = 'dispatch.matching'; + if (!this.definition(K)) return null; + return { + id: K, + nav: this.t('drivers.nav'), + title: this.t('drivers.title'), + description: this.t('drivers.description'), + lines: [ + this.line( + K, + ['vehicle_type'], + 'drivers.vehicle.sentence', + { choice: this.toggle(K, 'vehicle_type', this.t('drivers.vehicle.any'), this.t('drivers.vehicle.match'), 'drivers.vehicle-aria') }, + { help: this.t('drivers.vehicle-help') } + ), + this.line( + K, + ['exclude_busy_drivers'], + 'drivers.busy.sentence', + { choice: this.toggle(K, 'exclude_busy_drivers', this.t('drivers.busy.offered'), this.t('drivers.busy.skipped'), 'drivers.busy-aria') }, + { help: this.t('drivers.busy-help') } + ), + ], + }; } - @action removeListItem(policyKey, setting, index) { - const list = [...(this.valueOf(policyKey, setting) ?? [])]; - list.splice(index, 1); - this.setValue(policyKey, setting.name, list); + orderingGroup() { + const K = 'customer.ordering'; + if (!this.definition(K)) return null; + const chosen = this.valueOf(K, 'payment_methods') ?? []; + const allMethods = [...new Set([...PAYMENT_METHODS, ...chosen, ...(this.valueOf(K, 'require_settlement') ?? [])])]; + return { + id: K, + nav: this.t('ordering.nav'), + title: this.t('ordering.title'), + description: this.t('ordering.description'), + lines: [ + this.line( + K, + ['payment_methods'], + 'ordering.payment', + { methods: this.list(K, 'payment_methods', allMethods, 'ordering.payment-empty', 'ordering.payment-aria') }, + { help: this.t('ordering.payment-help') } + ), + this.line( + K, + ['require_quote'], + 'ordering.quote.sentence', + { choice: this.toggle(K, 'require_quote', this.t('ordering.quote.optional'), this.t('ordering.quote.required'), 'ordering.quote-aria') }, + { help: this.t('ordering.quote-help') } + ), + this.line( + K, + ['require_settlement'], + 'ordering.settlement', + { methods: this.list(K, 'require_settlement', chosen.length ? chosen : allMethods, 'ordering.settlement-empty', 'ordering.settlement-aria') }, + { help: this.t('ordering.settlement-help') } + ), + ], + }; } - @action reset(policyKey, name) { - this.setValue(policyKey, name, undefined); + cancellingGroup() { + const K = 'customer.cancellation'; + if (!this.definition(K)) return null; + const enabled = this.valueOf(K, 'enabled') !== false; + const can = this.choice( + K, + 'enabled', + [ + [true, this.t('cancelling.can')], + [false, this.t('cancelling.cannot')], + ], + 'cancelling.enabled-aria' + ); + const until = this.choice( + K, + 'allowed_until', + [[null, this.t('cancelling.finishes')], ...this.steps.map((step) => [step.value, this.t('cancelling.reaches', { step: step.label })])], + 'cancelling.until-aria' + ); + return { + id: K, + nav: this.t('cancelling.nav'), + title: this.t('cancelling.title'), + description: this.t('cancelling.description'), + lines: [ + enabled + ? this.line(K, ['enabled', 'allowed_until'], 'cancelling.until', { choice: can, step: until }, { help: this.t('cancelling-help') }) + : this.line(K, ['enabled', 'allowed_until'], 'cancelling.off', { choice: can }), + ], + }; } + interactionsGroup() { + const K = 'customer.interactions'; + if (!this.definition(K)) return null; + return { + id: K, + nav: this.t('interactions.nav'), + title: this.t('interactions.title'), + description: this.t('interactions.description'), + lines: [ + this.line( + K, + ['chat', 'rating', 'share_tracking'], + 'interactions.sentence', + { + message: this.toggle(K, 'chat', this.t('interactions.message.off'), this.t('interactions.message.on'), 'interactions.message-aria'), + rate: this.toggle(K, 'rating', this.t('interactions.rate.off'), this.t('interactions.rate.on'), 'interactions.rate-aria'), + share: this.toggle(K, 'share_tracking', this.t('interactions.share.off'), this.t('interactions.share.on'), 'interactions.share-aria'), + }, + { help: this.t('interactions-help') } + ), + ], + }; + } + + priceGroup() { + const K = 'pricing'; + if (!this.definition(K)) return null; + const reprice = this.valueOf(K, 'reprice_on_completion') === true; + const choice = this.toggle(K, 'reprice_on_completion', this.t('price.stands'), this.t('price.recalculate'), 'price.reprice-aria'); + const from = this.choice(K, 'metering_starts_at', [[null, this.t('price.from-start')], ...this.steps.map((step) => [step.value, step.label])], 'price.from-aria'); + return { + id: K, + nav: this.t('price.nav'), + title: this.t('price.title'), + description: this.t('price.description'), + lines: [ + reprice + ? this.line(K, ['reprice_on_completion', 'metering_starts_at'], 'price.reprice', { choice, step: from }, { help: this.t('price-help') }) + : this.line(K, ['reprice_on_completion', 'metering_starts_at'], 'price.no-reprice', { choice }, { help: this.t('price-help') }), + ], + }; + } + + /** A policy an extension registered: "Label: [control]" for each setting. */ + extensionGroup(policy) { + const K = policy.key; + const lines = (policy.settings ?? []).map((setting) => { + const label = humanize(setting.name); + let control; + let error = null; + if (setting.type === 'boolean') { + control = this.toggle(K, setting.name, this.t('extension-off'), this.t('extension-on'), 'extension-aria'); + } else if (setting.type === 'choice' && Array.isArray(setting.choices)) { + control = this.choice(K, setting.name, [[null, this.t('extension-none')], ...setting.choices.map((choice) => [choice.value, choice.label])], 'extension-aria'); + } else if (setting.type === 'choice' && setting.choices === 'activity') { + control = this.choice(K, setting.name, [[null, this.t('extension-none')], ...this.steps.map((step) => [step.value, step.label])], 'extension-aria'); + } else if (setting.type === 'list') { + const values = this.valueOf(K, setting.name) ?? []; + control = { + kind: 'list', + items: values.map((value) => ({ value, label: String(value) })), + options: [], + emptyLabel: this.t('extension-none'), + ariaLabel: label, + disabled: true, + }; + } else { + [control, error] = this.number(K, setting.name, setting.default === null || setting.default === undefined ? '' : String(setting.default), 'extension-aria', 150); + } + control.ariaLabel = label; + + return this.line(K, [setting.name], 'extension-fallback', { control }, { values: { label }, error }); + }); + + return { id: K, nav: policy.label, title: policy.label, description: policy.description, isExtension: true, lines }; + } + + // ----- loading and saving + @task *loadPolicies() { try { const { policies } = yield this.fetch.get('order-configs/capabilities'); @@ -137,13 +511,26 @@ export default class OrderConfigManagerPoliciesComponent extends Component { } } + @task *loadCompanyDefaults() { + try { + const settings = yield this.fetch.get('fleet-ops/settings/adhoc-dispatch-settings'); + this.companyDefaults = { ...this.companyDefaults, ...settings }; + } catch { + // The built-in defaults stand in. + } + } + @task *save() { + if (this.errorCount) { + return; + } + this.config.policies = this.merge(this.config.policies, this.values); try { yield this.config.save(); - this.saved = JSON.stringify(this.values); - this.notifications.success(this.intl.t('order-config-manager.saved-success-message', { orderConfigName: this.config.name })); + this.savedValues = JSON.parse(JSON.stringify(this.values)); + this.notifications.success(this.t('saved')); if (typeof this.args.onConfigUpdated === 'function') { this.args.onConfigUpdated(this.config); } @@ -193,6 +580,6 @@ export default class OrderConfigManagerPoliciesComponent extends Component { changeConfig(config) { this.config = config; this.values = this.flatten(config?.policies ?? {}); - this.saved = JSON.stringify(this.values); + this.savedValues = JSON.parse(JSON.stringify(this.values)); } } diff --git a/addon/components/order-config-manager/triggers.hbs b/addon/components/order-config-manager/triggers.hbs deleted file mode 100644 index f77f7e3e9..000000000 --- a/addon/components/order-config-manager/triggers.hbs +++ /dev/null @@ -1,98 +0,0 @@ -
- -

{{t "order-config-manager.triggers.description"}}

- - {{#if this.loadCapabilities.isRunning}} -
- {{else}} -
- {{#each this.editableRows as |row|}} -
-
- - - -
- {{#if this.canEdit}} -
-
- - {{#if row.isApproaching}} -
- - - - - - -
- {{/if}} - - {{#if row.parameters.length}} -
- {{#each row.parameters as |parameter|}} - - - - {{/each}} -
- {{/if}} - - {{#if row.conditionCount}} -

{{t "order-config-manager.triggers.conditions" count=row.conditionCount}}

- {{/if}} -
- {{else}} -

{{t "order-config-manager.triggers.empty"}}

- {{/each}} -
- - {{#if this.canEdit}} -
-
- {{/if}} - {{/if}} -
-
\ No newline at end of file diff --git a/addon/components/order-config-manager/triggers.js b/addon/components/order-config-manager/triggers.js deleted file mode 100644 index e6054856a..000000000 --- a/addon/components/order-config-manager/triggers.js +++ /dev/null @@ -1,221 +0,0 @@ -import Component from '@glimmer/component'; -import { tracked } from '@glimmer/tracking'; -import { inject as service } from '@ember/service'; -import { action } from '@ember/object'; -import { task } from 'ember-concurrency'; -import humanize from '@fleetbase/ember-core/utils/humanize'; - -const ACTIVITY_PREFIX = 'activity:'; - -/** - * Manages what an order config does when things happen to its orders: when an order reaches one - * of its activities (the activity's `actions` in the flow) or on an order event such as - * `order.created` or `driver.approaching` (the config's `triggers`). Both are edited here as one - * list of "when ..., do ..." rows. The actions and events come from the server - * (`order-configs/capabilities`), so an extension's actions show up too. - * - * A trigger's conditions (`when`) are kept as they are; they are set through the API. - * - * @extends Component - */ -export default class OrderConfigManagerTriggersComponent extends Component { - @service fetch; - @service notifications; - @service abilities; - @service intl; - - /** The config being managed. */ - @tracked config; - - /** The registered actions and trigger events. */ - @tracked actions = []; - @tracked events = []; - - /** Working list of triggers: `{ id, on, action, params, options, when }`. */ - @tracked rows = []; - - /** Rows as last saved, serialized, to tell whether there is anything to save. */ - @tracked saved = '[]'; - - constructor(owner, { config, configManagerContext }) { - super(...arguments); - this.changeConfig(config); - this.loadCapabilities.perform(); - - configManagerContext.on('onConfigChanged', (newConfig) => { - this.changeConfig(newConfig); - }); - } - - get canEdit() { - return this.abilities.can('fleet-ops update order-config'); - } - - get isDirty() { - return JSON.stringify(this.serialize(this.rows)) !== this.saved; - } - - /** What a trigger can run on: reaching an activity, or an order event. */ - get eventOptions() { - const activities = Object.values(this.config?.flow ?? {}) - .filter((activity) => activity && activity.code) - .map((activity) => ({ - value: ACTIVITY_PREFIX + activity.code, - label: this.intl.t('order-config-manager.triggers.reaches-activity', { activity: activity.status || activity.code }), - })); - const events = this.events.map((event) => ({ value: event, label: this.intl.t(`order-config-manager.triggers.events.${event}`, { default: humanize(event) }) })); - - return [...activities, ...events]; - } - - get actionOptions() { - return this.actions.map((action) => ({ value: action.name, label: action.label })); - } - - /** Rows with what the template needs to show each one. */ - get editableRows() { - return this.rows.map((row) => { - const definition = this.actions.find((action) => action.name === row.action); - return { - ...row, - parameters: Object.entries(definition?.parameters ?? {}).map(([name, description]) => ({ name, description, label: humanize(name), value: row.params?.[name] ?? '' })), - isApproaching: row.on === 'driver.approaching', - conditionCount: Array.isArray(row.when) ? row.when.length : 0, - }; - }); - } - - @action addRow() { - this.rows = [ - ...this.rows, - { id: this.nextId(), on: this.eventOptions[0]?.value ?? 'order.created', action: this.actionOptions[0]?.value ?? 'notify_customer', params: {}, options: {}, when: [] }, - ]; - } - - @action removeRow(id) { - this.rows = this.rows.filter((row) => row.id !== id); - } - - @action setRowField(id, field, value) { - this.rows = this.rows.map((row) => (row.id === id ? { ...row, [field]: value } : row)); - } - - @action setParam(id, name, event) { - const value = event?.target?.value ?? event; - this.rows = this.rows.map((row) => (row.id === id ? { ...row, params: { ...row.params, [name]: value } } : row)); - } - - @action setOption(id, name, event) { - let value = event?.target?.value ?? event; - if (name === 'distance') { - value = value === '' ? undefined : Number(value); - } - this.rows = this.rows.map((row) => (row.id === id ? { ...row, options: { ...row.options, [name]: value } } : row)); - } - - @task *loadCapabilities() { - try { - const { actions, events } = yield this.fetch.get('order-configs/capabilities'); - this.actions = actions ?? []; - this.events = events ?? []; - } catch (error) { - this.notifications.serverError(error); - } - } - - @task *save() { - const { triggers, flow } = this.split(this.rows); - this.config.triggers = triggers; - this.config.flow = flow; - - try { - yield this.config.save(); - this.saved = JSON.stringify(this.serialize(this.rows)); - this.notifications.success(this.intl.t('order-config-manager.saved-success-message', { orderConfigName: this.config.name })); - if (typeof this.args.onConfigUpdated === 'function') { - this.args.onConfigUpdated(this.config); - } - } catch (error) { - this.notifications.serverError(error); - } - } - - /** The rows as the server keeps them: activity rows in the flow, the rest in `triggers`. */ - split(rows) { - const flow = JSON.parse(JSON.stringify(this.config.flow ?? {})); - Object.values(flow).forEach((activity) => { - if (activity && typeof activity === 'object') { - activity.actions = []; - } - }); - - const triggers = []; - for (const row of this.serialize(rows)) { - const { on, ...trigger } = row; - if (on.startsWith(ACTIVITY_PREFIX)) { - const activity = flow[on.slice(ACTIVITY_PREFIX.length)]; - if (activity) { - delete trigger.options; - activity.actions.push(trigger); - } - } else { - triggers.push({ event: on, ...trigger }); - } - } - - return { triggers, flow }; - } - - /** Rows without their editor ids and empty values. */ - serialize(rows) { - return rows.map(({ on, action, params, options, when }) => { - const row = { on, action }; - const cleanParams = Object.fromEntries(Object.entries(params ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); - const cleanOptions = Object.fromEntries(Object.entries(options ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); - if (Object.keys(cleanParams).length) { - row.params = cleanParams; - } - if (on === 'driver.approaching' && Object.keys(cleanOptions).length) { - row.options = cleanOptions; - } - if (Array.isArray(when) && when.length) { - row.when = when; - } - - return row; - }); - } - - /** The config's triggers and its activities' actions as one list of rows. */ - read(config) { - const rows = []; - Object.values(config?.flow ?? {}).forEach((activity) => { - (activity?.actions ?? []).forEach((trigger) => { - rows.push({ id: this.nextId(), on: ACTIVITY_PREFIX + activity.code, action: trigger.action, params: { ...(trigger.params ?? {}) }, options: {}, when: trigger.when ?? [] }); - }); - }); - (config?.triggers ?? []).forEach((trigger) => { - rows.push({ - id: this.nextId(), - on: trigger.event, - action: trigger.action, - params: { ...(trigger.params ?? {}) }, - options: { ...(trigger.options ?? {}) }, - when: trigger.when ?? [], - }); - }); - - return rows; - } - - nextId() { - this._id = (this._id ?? 0) + 1; - return this._id; - } - - changeConfig(config) { - this.config = config; - this.rows = this.read(config); - this.saved = JSON.stringify(this.serialize(this.rows)); - } -} diff --git a/addon/components/order-config/inline-list.hbs b/addon/components/order-config/inline-list.hbs new file mode 100644 index 000000000..6d071ae2c --- /dev/null +++ b/addon/components/order-config/inline-list.hbs @@ -0,0 +1,25 @@ + + {{#each @items as |item|}} + + {{item.label}} + {{#unless @disabled}} + + {{/unless}} + + {{else}} + {{@emptyLabel}} + {{/each}} + {{#if this.canAdd}} + + {{/if}} + diff --git a/addon/components/order-config/inline-list.js b/addon/components/order-config/inline-list.js new file mode 100644 index 000000000..30d21bd09 --- /dev/null +++ b/addon/components/order-config/inline-list.js @@ -0,0 +1,33 @@ +import Component from '@glimmer/component'; +import { action } from '@ember/object'; + +/** + * A list of values inside a sentence, such as payment methods: removable chips and an Add menu. + * + * @argument {Array<{value, label}>} items the chosen values + * @argument {Array<{value, label}>} options every value that can be chosen + * @argument {String} emptyLabel shown when nothing is chosen + * @argument {Function} onChange called with the new array of values + */ +export default class OrderConfigInlineListComponent extends Component { + get addable() { + const chosen = (this.args.items ?? []).map((item) => item.value); + return (this.args.options ?? []).filter((option) => !chosen.includes(option.value)); + } + + get canAdd() { + return !this.args.disabled && this.addable.length > 0; + } + + get values() { + return (this.args.items ?? []).map((item) => item.value); + } + + @action add(value) { + this.args.onChange?.([...this.values, value]); + } + + @action remove(item) { + this.args.onChange?.(this.values.filter((value) => value !== item.value)); + } +} diff --git a/addon/components/order-config/inline-number.hbs b/addon/components/order-config/inline-number.hbs new file mode 100644 index 000000000..360f68a53 --- /dev/null +++ b/addon/components/order-config/inline-number.hbs @@ -0,0 +1,12 @@ + diff --git a/addon/components/order-config/inline-number.js b/addon/components/order-config/inline-number.js new file mode 100644 index 000000000..476804899 --- /dev/null +++ b/addon/components/order-config/inline-number.js @@ -0,0 +1,36 @@ +import Component from '@glimmer/component'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { htmlSafe } from '@ember/template'; + +/** + * A number inside a sentence. Left empty it follows the default, which the placeholder shows. + * + * @argument {Number|String} value + * @argument {String} defaultLabel the default, shown as the placeholder ("20 · default") + * @argument {Function} onChange called with the number, or undefined when emptied + * @argument {Boolean} invalid + * @argument {Number} width in pixels + */ +export default class OrderConfigInlineNumberComponent extends Component { + @service intl; + + get isEmpty() { + return this.args.value === undefined || this.args.value === null || this.args.value === ''; + } + + get placeholder() { + return this.args.defaultLabel ? this.intl.t('order-config-manager.common.default-suffix', { value: this.args.defaultLabel }) : ''; + } + + get style() { + return htmlSafe(`width: ${this.args.width ?? 132}px`); + } + + @action change(event) { + const raw = String(event.target.value ?? '').replace(/[^0-9.-]/g, ''); + if (typeof this.args.onChange === 'function') { + this.args.onChange(raw === '' ? undefined : Number(raw), raw); + } + } +} diff --git a/addon/components/order-config/inline-select.hbs b/addon/components/order-config/inline-select.hbs new file mode 100644 index 000000000..7f5e22a10 --- /dev/null +++ b/addon/components/order-config/inline-select.hbs @@ -0,0 +1,46 @@ +{{#if @disabled}} + {{this.displayLabel}} +{{else}} + + + {{this.displayLabel}} + {{#unless @hideCaret}} + + {{/unless}} + + +
    + {{#each @options as |option|}} +
  • + + {{option.label}} + {{#if option.description}} + {{option.description}} + {{/if}} + + + {{#if option.isDefault}} + {{t "order-config-manager.common.default"}} + {{/if}} + {{#if (eq option.value @value)}} + + {{/if}} + +
  • + {{/each}} +
+
+
+{{/if}} diff --git a/addon/components/order-config/inline-select.js b/addon/components/order-config/inline-select.js new file mode 100644 index 000000000..eb2545f91 --- /dev/null +++ b/addon/components/order-config/inline-select.js @@ -0,0 +1,37 @@ +import Component from '@glimmer/component'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; + +/** + * A choice inside a sentence: the chosen option's words, styled as following the default + * (dashed, "· default") or set for this config (solid). Opens a list of the options. + * + * @argument {Array<{value, label, description?, isDefault?}>} options + * @argument {*} value the chosen option's value + * @argument {Boolean} isDefault the value is the default, so it reads as one + * @argument {Function} onSelect called with the chosen option's value + * @argument {Boolean} disabled render as read-only text + * @argument {String} label words to show instead of the chosen option's label + */ +export default class OrderConfigInlineSelectComponent extends Component { + @service intl; + + get displayLabel() { + const label = this.args.label ?? this.args.options?.find((option) => option.value === this.args.value)?.label ?? ''; + return this.args.isDefault && !this.args.hideDefaultSuffix ? this.intl.t('order-config-manager.common.default-suffix', { value: label }) : label; + } + + @action select(dropdown, option) { + dropdown.actions.close(); + if (typeof this.args.onSelect === 'function') { + this.args.onSelect(option.value, option); + } + } + + @action selectOnKey(dropdown, option, event) { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault(); + this.select(dropdown, option); + } + } +} diff --git a/addon/components/order-config/notice.hbs b/addon/components/order-config/notice.hbs new file mode 100644 index 000000000..1a3bd9734 --- /dev/null +++ b/addon/components/order-config/notice.hbs @@ -0,0 +1,6 @@ +
+ + + {{#if @title}}{{@title}} {{/if}}{{@text}}{{yield}} + +
diff --git a/addon/components/order-config/order-events.hbs b/addon/components/order-config/order-events.hbs new file mode 100644 index 000000000..f2ebcf07f --- /dev/null +++ b/addon/components/order-config/order-events.hbs @@ -0,0 +1,75 @@ +
+

{{t "order-config-manager.events.intro"}}

+ + {{#each this.cards as |card|}} +
+
+
+ + {{#each card.parts as |part|}} + {{#if (eq part.kind "text")}} + {{part.text}} + {{else if (eq part.kind "number")}} + + {{else if (eq part.kind "choice")}} + + {{/if}} + {{/each}} +
+ {{#unless this.readonly}} +
+ {{#if card.help}}{{card.help}}{{/if}} + +
+ {{else}} +
{{t "order-config-manager.events.empty"}}
+ {{/each}} + + {{#unless this.readonly}} + + {{/unless}} + + {{#if this.isDirty}} +
+ {{t "order-config-manager.common.unsaved-changes"}} + +
+ {{/if}} +
diff --git a/addon/components/order-config/order-events.js b/addon/components/order-config/order-events.js new file mode 100644 index 000000000..1332cc5da --- /dev/null +++ b/addon/components/order-config/order-events.js @@ -0,0 +1,187 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { task } from 'ember-concurrency'; +import sentenceParts from '../../utils/sentence-parts'; + +const E = 'order-config-manager.events'; +const EVENT_KEYS = { + 'order.created': 'created', + 'order.completed': 'completed', + 'order.canceled': 'canceled', + 'dispatch.offer_exhausted': 'exhausted', + 'driver.approaching': 'approaching', +}; +const APPROACHING_DISTANCE = 500; + +/** + * An order config's order events: what happens when something happens to an order outside its + * steps, such as being canceled or the driver approaching. Opened from the Activity Flow canvas. + * + * Stored triggers (`config.triggers`, each `{ event, options, action, params, when }`) are shown + * grouped by event and options, each group listing its actions; saving writes them back flat. + */ +export default class OrderConfigOrderEventsComponent extends Component { + @service abilities; + @service notifications; + @service intl; + + @tracked groups = []; + @tracked saved = '[]'; + + constructor() { + super(...arguments); + this.groups = this.read(this.config?.triggers ?? []); + this.saved = JSON.stringify(this.serialize(this.groups)); + } + + get config() { + return this.args.overlay?.config ?? this.args.resource; + } + + get readonly() { + return this.abilities.cannot('fleet-ops update order-config'); + } + + get isDirty() { + return JSON.stringify(this.serialize(this.groups)) !== this.saved; + } + + get eventMenu() { + const events = this.args.overlay?.events?.length ? this.args.overlay.events : Object.keys(EVENT_KEYS); + return events.map((event) => { + const key = EVENT_KEYS[event]; + return { + value: event, + label: key ? this.intl.t(`${E}.${key}-menu`) : event, + description: key ? this.intl.t(`${E}.${key}-description`) : '', + }; + }); + } + + get cards() { + return this.groups.map((group, index) => { + const key = EVENT_KEYS[group.event]; + let parts; + let help = null; + if (group.event === 'driver.approaching') { + const distance = group.options?.distance; + const target = group.options?.target === 'dropoff' ? 'dropoff' : 'pickup'; + parts = sentenceParts(this.intl, `${E}.approaching`, { + metres: { + kind: 'number', + value: distance ?? '', + defaultLabel: String(APPROACHING_DISTANCE), + width: 128, + ariaLabel: this.intl.t(`${E}.distance-aria`), + invalid: distance !== undefined && (Number.isNaN(Number(distance)) || Number(distance) < 50), + onChange: (value) => this.setOption(index, 'distance', value), + }, + target: { + kind: 'choice', + value: target, + isDefault: false, + ariaLabel: this.intl.t(`${E}.target-aria`), + options: [ + { value: 'pickup', label: this.intl.t(`${E}.target-pickup`), isDefault: true }, + { value: 'dropoff', label: this.intl.t(`${E}.target-dropoff`) }, + ], + onChange: (value) => this.setOption(index, 'target', value), + }, + }); + help = this.intl.t(target === 'dropoff' ? `${E}.approaching-help-dropoff` : `${E}.approaching-help`); + } else { + parts = [{ kind: 'text', text: this.intl.t(`${E}.when`, { event: key ? this.intl.t(`${E}.${key}`) : group.event }) }]; + } + + return { index, group, parts, help, isNew: group.isNew }; + }); + } + + // ----- editing + + @action addEvent(event) { + const options = event === 'driver.approaching' ? { target: 'pickup' } : {}; + this.groups = [...this.groups, { id: this.nextId(), event, options, triggers: [], isNew: true }]; + } + + @action removeGroup(index) { + this.groups = this.groups.filter((_, i) => i !== index); + } + + @action setTriggers(index, triggers) { + this.groups = this.groups.map((group, i) => (i === index ? { ...group, triggers } : group)); + } + + setOption(index, name, value) { + this.groups = this.groups.map((group, i) => { + if (i !== index) return group; + const options = { ...(group.options ?? {}) }; + if (value === undefined || value === null || value === '') { + delete options[name]; + } else { + options[name] = value; + } + return { ...group, options }; + }); + } + + @action discard() { + this.groups = this.read(JSON.parse(this.saved)); + } + + @task *save() { + this.config.triggers = this.serialize(this.groups); + try { + yield this.config.save(); + this.saved = JSON.stringify(this.config.triggers); + this.groups = this.read(this.config.triggers); + this.notifications.success(this.intl.t(`${E}.saved`)); + this.args.overlay?.onSaved?.(this.config); + } catch (error) { + this.notifications.serverError(error); + } + } + + // ----- reading and writing + + read(triggers) { + const groups = []; + (triggers ?? []).forEach((trigger) => { + const options = trigger.event === 'driver.approaching' ? { ...(trigger.options ?? {}) } : {}; + const key = JSON.stringify([trigger.event, options]); + let group = groups.find((candidate) => candidate.key === key); + if (!group) { + group = { id: this.nextId(), key, event: trigger.event, options, triggers: [] }; + groups.push(group); + } + const item = { action: trigger.action }; + if (trigger.params) item.params = { ...trigger.params }; + if (trigger.when?.length) item.when = trigger.when; + group.triggers.push(item); + }); + return groups; + } + + serialize(groups) { + return groups.flatMap((group) => + (group.triggers ?? []) + .filter((trigger) => trigger.action) + .map((trigger) => { + const row = { event: group.event }; + const options = Object.fromEntries(Object.entries(group.options ?? {}).filter(([, value]) => value !== undefined && value !== null && value !== '')); + if (group.event === 'driver.approaching' && Object.keys(options).length) row.options = options; + if (trigger.when?.length) row.when = trigger.when; + row.action = trigger.action; + if (trigger.params && Object.keys(trigger.params).length) row.params = trigger.params; + return row; + }) + ); + } + + nextId() { + this._id = (this._id ?? 0) + 1; + return this._id; + } +} diff --git a/addon/components/order-config/sentence-field.hbs b/addon/components/order-config/sentence-field.hbs new file mode 100644 index 000000000..cfb3a33c7 --- /dev/null +++ b/addon/components/order-config/sentence-field.hbs @@ -0,0 +1,55 @@ +
+
+
+ {{#each @parts as |part|}} + {{#if (eq part.kind "text")}} + {{part.text}} + {{else if (eq part.kind "choice")}} + + {{else if (eq part.kind "number")}} + + {{else if (eq part.kind "list")}} + + {{/if}} + {{/each}} +
+
+ {{#if @unsaved}} + {{t "order-config-manager.common.unsaved"}} + {{/if}} + {{#if (and @canReset (not @readonly))}} + + {{/if}} +
+
+ {{#if @help}} + {{@help}} + {{/if}} + {{#if @error}} + {{@error}} + {{/if}} +
diff --git a/addon/components/order-config/trigger-list.hbs b/addon/components/order-config/trigger-list.hbs new file mode 100644 index 000000000..d0534d25f --- /dev/null +++ b/addon/components/order-config/trigger-list.hbs @@ -0,0 +1,123 @@ +
+ {{#each this.cards as |card|}} + {{#if card.isEditing}} +
+
+ {{t "order-config-manager.step.then"}} + + {{#if card.isNew}}{{t "order-config-manager.step.new"}}{{/if}} +
+ {{#if this.missingAction}} + {{t "order-config-manager.step.no-action-error"}} + {{/if}} + + {{#if this.draftIsNotify}} + + + + + + +
+ {{t "order-config-manager.step.insert"}} + {{#each this.placeholders as |token|}} + + {{/each}} +
+
+ {{t "order-config-manager.step.preview"}} + + + + {{this.previewTitle}} + {{this.previewMessage}} + + +
+ {{/if}} + + {{#each this.draftParameters as |parameter|}} + + + + {{/each}} + + + +
+
+
+ {{else}} +
+ +
+ {{card.label}}{{#if card.title}} “{{card.title}}”{{/if}} + {{#if card.message}}{{card.message}}{{/if}} + {{card.meta}} +
+ {{#unless @readonly}} +
+ {{#if card.isChanged}}{{t "order-config-manager.step.edited"}}{{/if}} +
+ {{/unless}} +
+ {{/if}} + {{/each}} + + {{#each this.removed as |entry|}} +
+ {{entry.label}} · {{t "order-config-manager.step.removed-note"}} + +
+ {{/each}} + + {{#unless this.triggers.length}} + {{#unless this.removed.length}} +
{{or @emptyText (t "order-config-manager.step.empty")}}
+ {{/unless}} + {{/unless}} + + {{#unless @readonly}} + {{#unless this.draft}} + + {{#unless @hideQuickAdd}} +
+ {{t "order-config-manager.step.quick-add"}} + {{#each this.quickAdd as |quick|}} + + {{/each}} +
+ {{/unless}} + {{/unless}} + {{/unless}} +
diff --git a/addon/components/order-config/trigger-list.js b/addon/components/order-config/trigger-list.js new file mode 100644 index 000000000..87cfc69c7 --- /dev/null +++ b/addon/components/order-config/trigger-list.js @@ -0,0 +1,205 @@ +import Component from '@glimmer/component'; +import { tracked } from '@glimmer/tracking'; +import { inject as service } from '@ember/service'; +import { action } from '@ember/object'; +import { actionIcon, actionLabel, actionDescription } from '../../utils/order-config-action-meta'; + +const S = 'order-config-manager.step'; +const NOTIFY = ['notify_customer', 'notify_driver']; +const SAMPLE = { + 'driver.first_name': 'Sam', + 'driver.name': 'Sam Lee', + 'customer.name': 'Alex Kim', + 'order.id': 'order_7f3k2', + 'order.tracking_number': 'FLB102938', + 'order.status': 'started', +}; + +/** + * The things that happen at one point of an order, as cards: "Notify the customer 'Your driver + * has arrived'". Edit opens the card in place: what happens, its settings (title and message + * with placeholder chips and a preview for notifications), and "Only if" conditions. A removed + * card can be undone until the list is saved. + * + * Triggers are `{ action, params, when }`; the list hands the whole new array to `onChange`. + * + * @argument {Array} triggers + * @argument {Function} onChange + * @argument {Array} actions the actions from `order-configs/capabilities` + * @argument {Array} placeholders the message placeholders from capabilities + * @argument {String} stepStatus the step's status, used when a notification has no title + * @argument {String} stepDetails the step's details, used when it has no message + * @argument {Boolean} readonly + */ +export default class OrderConfigTriggerListComponent extends Component { + @service intl; + + @tracked editing = null; + @tracked draft = null; + @tracked missingAction = false; + @tracked removed = []; + @tracked changedIndexes = []; + messageElement; + + get triggers() { + return this.args.triggers ?? []; + } + + get actionOptions() { + return (this.args.actions ?? []).map((described) => ({ + value: described.name, + label: actionLabel(this.intl, described.name, this.args.actions), + description: actionDescription(this.intl, described.name, this.args.actions), + })); + } + + get quickAdd() { + const names = (this.args.actions ?? []).map((described) => described.name); + return ['notify_customer', 'notify_driver', 'open_chat', 'close_chat', 'send_invoice'] + .filter((name) => names.includes(name)) + .map((name) => ({ name, label: this.intl.t(`${S}.quick.${name}`, { default: actionLabel(this.intl, name, this.args.actions) }) })); + } + + get cards() { + return this.triggers.map((trigger, index) => { + const isNotify = NOTIFY.includes(trigger.action); + const conditions = (trigger.when ?? []).reduce((count, block) => count + (block?.conditions?.length ?? 0), 0); + return { + index, + trigger, + icon: actionIcon(trigger.action), + label: actionLabel(this.intl, trigger.action, this.args.actions), + title: isNotify ? trigger.params?.title || this.args.stepStatus : null, + message: isNotify ? trigger.params?.message || this.intl.t(`${S}.message-fallback`) : null, + meta: [isNotify ? this.intl.t(`${S}.push-notification`) : null, conditions ? this.intl.t(`${S}.only-if-count`, { count: conditions }) : this.intl.t(`${S}.every-time`)] + .filter(Boolean) + .join(' · '), + isEditing: this.editing === index, + isNew: this.editing === index && this.draft?.isNew, + isChanged: this.changedIndexes.includes(index), + }; + }); + } + + get draftIsNotify() { + return NOTIFY.includes(this.draft?.action); + } + + /** The draft action's parameters other than a notification's title and message. */ + get draftParameters() { + const described = (this.args.actions ?? []).find((item) => item.name === this.draft?.action); + if (!described || this.draftIsNotify) { + return []; + } + return Object.entries(described.parameters ?? {}).map(([name, description]) => ({ name, description, value: this.draft.params?.[name] ?? '' })); + } + + get titlePlaceholder() { + return this.intl.t(`${S}.title-placeholder`, { status: this.args.stepStatus || this.intl.t(`${S}.title-placeholder-event`) }); + } + + get placeholders() { + return (this.args.placeholders ?? Object.keys(SAMPLE)).filter((token) => !token.startsWith('activity.') || this.args.stepStatus).map((token) => `{${token}}`); + } + + fill(text) { + return String(text ?? '').replace(/\{\s*([a-z_]+(?:\.[a-z_]+)*)\s*\}/gi, (match, token) => { + const key = token.toLowerCase(); + if (key === 'activity.status') return this.args.stepStatus ?? ''; + if (key === 'activity.details') return this.args.stepDetails ?? ''; + return SAMPLE[key] ?? ''; + }); + } + + get previewTitle() { + return this.fill(this.draft?.params?.title || this.args.stepStatus || ''); + } + + get previewMessage() { + return this.fill(this.draft?.params?.message || this.args.stepDetails || ''); + } + + // ----- editing + + @action edit(index) { + const trigger = this.triggers[index]; + this.editing = index; + this.missingAction = false; + this.draft = { action: trigger.action, params: { ...(trigger.params ?? {}) }, when: JSON.parse(JSON.stringify(trigger.when ?? [])), isNew: false }; + } + + @action add(name = null) { + const list = [...this.triggers, { action: name, params: {}, when: [] }]; + this.args.onChange?.(list); + this.editing = list.length - 1; + this.missingAction = false; + this.draft = { action: name, params: {}, when: [], isNew: true }; + } + + @action setDraftAction(name) { + this.draft = { ...this.draft, action: name }; + this.missingAction = false; + } + + @action setParam(name, event) { + this.draft = { ...this.draft, params: { ...this.draft.params, [name]: event.target.value } }; + } + + @action setWhen(logic) { + this.draft = { ...this.draft, when: logic ?? [] }; + } + + @action registerMessage(element) { + this.messageElement = element; + } + + @action insertToken(token) { + const current = this.draft.params?.message ?? ''; + const element = this.messageElement; + const start = element && typeof element.selectionStart === 'number' ? element.selectionStart : current.length; + const end = element && typeof element.selectionEnd === 'number' ? element.selectionEnd : current.length; + const needsSpace = start > 0 && !/\s$/.test(current.slice(0, start)); + const message = current.slice(0, start) + (needsSpace ? ' ' : '') + token + current.slice(end); + this.draft = { ...this.draft, params: { ...this.draft.params, message } }; + } + + @action cancel() { + if (this.draft?.isNew) { + this.args.onChange?.(this.triggers.filter((_, index) => index !== this.editing)); + } + this.editing = null; + this.draft = null; + this.missingAction = false; + } + + @action done() { + if (!this.draft?.action) { + this.missingAction = true; + return; + } + + const params = Object.fromEntries(Object.entries(this.draft.params ?? {}).filter(([, value]) => value !== '' && value !== undefined && value !== null)); + const trigger = { action: this.draft.action }; + if (Object.keys(params).length) trigger.params = params; + if ((this.draft.when ?? []).length) trigger.when = this.draft.when; + + const index = this.editing; + this.args.onChange?.(this.triggers.map((existing, i) => (i === index ? { ...existing, ...trigger, params: trigger.params, when: trigger.when } : existing))); + this.changedIndexes = [...new Set([...this.changedIndexes, index])]; + this.editing = null; + this.draft = null; + } + + @action remove(index) { + const trigger = this.triggers[index]; + this.removed = [...this.removed, { trigger, index, label: actionLabel(this.intl, trigger.action, this.args.actions) }]; + this.args.onChange?.(this.triggers.filter((_, i) => i !== index)); + } + + @action undo(entry) { + const list = [...this.triggers]; + list.splice(Math.min(entry.index, list.length), 0, entry.trigger); + this.removed = this.removed.filter((item) => item !== entry); + this.args.onChange?.(list); + } +} diff --git a/addon/components/order-config/unsaved-bar.hbs b/addon/components/order-config/unsaved-bar.hbs new file mode 100644 index 000000000..72fbe950d --- /dev/null +++ b/addon/components/order-config/unsaved-bar.hbs @@ -0,0 +1,20 @@ +{{#if @count}} +
+ + {{t "order-config-manager.common.unsaved-count" count=@count}} + {{or @errorHint @hint}} + + +
+{{/if}} diff --git a/addon/styles/fleetops-engine.css b/addon/styles/fleetops-engine.css index 36b53c4c9..160cb108b 100644 --- a/addon/styles/fleetops-engine.css +++ b/addon/styles/fleetops-engine.css @@ -629,39 +629,236 @@ body[data-theme='light'] .fleetops-pill-tabs > nav > a.ui-tab.active { max-width: 100px; } +.flow-activity { + fill: #1f2937; + stroke: #374151; + stroke-width: 1; + filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3)) drop-shadow(0 4px 10px rgba(0, 0, 0, 0.2)); +} + +.joint-type-fleetbase-activity { + cursor: pointer; +} + +.joint-type-fleetbase-activity:hover .flow-activity { + stroke: #3b82f6; +} + +.flow-activity-status { + fill: #f9fafb; +} + +.flow-activity-meta { + fill: #9ca3af; +} + +.flow-activity-tile { + fill: #374151; +} + +.flow-activity-tile-icon { + fill: none; + stroke: #cbd5e1; + stroke-width: 2.4; + stroke-linecap: round; + stroke-linejoin: round; +} + +.flow-activity-tile--start { + fill: #172554; +} + +.flow-activity-tile-icon--start { + fill: #dbeafe; + stroke: #dbeafe; +} + +.flow-activity-tile--complete { + fill: #052e16; +} + +.flow-activity-tile-icon--complete { + stroke: #86efac; +} + +.flow-activity-tile--end { + fill: #3f1212; +} + +.flow-activity-tile-icon--end { + fill: #fca5a5; + stroke: #fca5a5; +} + +.flow-activity-chip { + fill: #374151; +} + +.flow-activity-chip-icon { + fill: none; + stroke: #fde68a; + stroke-width: 2.2; + stroke-linecap: round; + stroke-linejoin: round; +} + +.flow-activity-link { + stroke: #64748b; +} + +.flow-activity-link-label { + fill: #1f2937; + stroke: #374151; +} + +.flow-activity-link-label-text { + fill: #9ca3af; +} + body[data-theme='light'] .flow-activity { + fill: #fff; stroke: #e5e7eb; - fill: rgba(249, 250, 251, 0.5); + filter: drop-shadow(0 1px 2px rgba(17, 24, 39, 0.06)) drop-shadow(0 2px 8px rgba(17, 24, 39, 0.05)); } -body[data-theme='light'] .flow-activity:hover, body[data-theme='light'] .joint-type-fleetbase-activity:hover .flow-activity { stroke: #2563eb; } -body[data-theme='light'] .joint-type-fleetbase-activity text { - fill: #030712; +body[data-theme='light'] .flow-activity-status { + fill: #111827; +} + +body[data-theme='light'] .flow-activity-meta { + fill: #6b7280; } -body[data-theme='light'] .flow-activity-status-pill { +body[data-theme='light'] .flow-activity-tile { fill: #f3f4f6; - stroke: #f3f4f6; } -body[data-theme='light'] .flow-activity-status-pill text { - fill: #030712; +body[data-theme='light'] .flow-activity-tile-icon { + stroke: #374151; } -.flow-activity:hover, -.flow-activity-add-button:hover, -.joint-type-fleetbase-activity:hover .flow-activity { - stroke: #2563eb; +body[data-theme='light'] .flow-activity-tile--start { + fill: #eff6ff; +} + +body[data-theme='light'] .flow-activity-tile-icon--start { + fill: #1e3a8a; + stroke: #1e3a8a; +} + +body[data-theme='light'] .flow-activity-tile--complete { + fill: #dcfce7; +} + +body[data-theme='light'] .flow-activity-tile-icon--complete { + stroke: #166534; +} + +body[data-theme='light'] .flow-activity-tile--end { + fill: #fee2e2; +} + +body[data-theme='light'] .flow-activity-tile-icon--end { + fill: #991b1b; + stroke: #991b1b; +} + +body[data-theme='light'] .flow-activity-chip { + fill: #fef3c7; +} + +body[data-theme='light'] .flow-activity-chip-icon { + stroke: #92400e; +} + +body[data-theme='light'] .flow-activity-link { + stroke: #94a3b8; +} + +body[data-theme='light'] .flow-activity-link-label { + fill: #fff; + stroke: #e5e7eb; +} + +body[data-theme='light'] .flow-activity-link-label-text { + fill: #6b7280; } .flow-activity-add-button:hover { fill: #3b82f6; } +.oc-flow-chip { + display: inline-flex; + align-items: center; + gap: 0.375rem; + height: 1.875rem; + padding: 0 0.625rem; + border-radius: 0.5rem; + font-size: 0.75rem; + color: var(--oc-muted); + background: var(--oc-surface); + border: 1px solid var(--oc-border); +} + +.oc-flow-events { + display: inline-flex; + align-items: center; + gap: 0.5rem; + height: 2rem; + padding: 0 0.75rem; + border-radius: 0.5rem; + font-size: 0.8125rem; + font-weight: 500; + color: var(--oc-text); + background: var(--oc-surface); + border: 1px solid var(--oc-border); + box-shadow: var(--oc-shadow); +} + +.oc-flow-events:hover { + border-color: var(--oc-accent-border); +} + +.oc-flow-events__count { + font-size: 0.75rem; + font-weight: 600; + color: var(--oc-accent-text); + background: var(--oc-pill); + padding: 0.0625rem 0.4375rem; + border-radius: 999px; +} + +.oc-flow-legend { + position: absolute; + left: 1.5rem; + bottom: 1rem; + z-index: 99; + display: flex; + gap: 0.75rem; + padding: 0.375rem 0.625rem; + font-size: 0.6875rem; + color: var(--oc-muted); + background: var(--oc-surface); + border: 1px solid var(--oc-border); + border-radius: 0.5rem; + box-shadow: var(--oc-shadow); +} + +.oc-flow-legend > span { + display: inline-flex; + align-items: center; + gap: 0.3rem; +} + +.oc-flow-legend__icon { + color: var(--oc-chip-fg); +} + .joint-js-paper { overflow: auto; } @@ -13820,3 +14017,982 @@ body[data-theme='dark'] .resource-list-pill .fleetbase-pill-body .resource-pill- transition: none; } } + +/* --------------------------------------------------------------------------------------------- + * Order config: sentence fields, inline controls, save bar, notices, cards. + * Dark first; light overrides below. Cards inside gray-800 panels are gray-800 with a border and + * a shadow, never gray-900. + * ------------------------------------------------------------------------------------------- */ +.oc-page { + --oc-surface: #1f2937; + --oc-border: #374151; + --oc-line: #2b3544; + --oc-text: #f9fafb; + --oc-text2: #e5e7eb; + --oc-sub: #cbd5e1; + --oc-muted: #9ca3af; + --oc-input: #374151; + --oc-input-border: #4b5563; + --oc-link: #93c5fd; + --oc-accent-bg: #172554; + --oc-accent-border: #3b82f6; + --oc-accent-soft: #1e40af; + --oc-accent-text: #dbeafe; + --oc-pill: #1e3a8a; + --oc-def-border: #8b95a5; + --oc-unsaved-bg: #1c1a10; + --oc-unsaved-bar: #f59e0b; + --oc-unsaved-text: #fde68a; + --oc-warn-bg: #422006; + --oc-warn-border: #a16207; + --oc-warn-text: #fde68a; + --oc-err-bg: #3f1212; + --oc-err-border: #f87171; + --oc-err-text: #fca5a5; + --oc-ok-bg: #052e16; + --oc-ok-text: #86efac; + --oc-end-bg: #3f1212; + --oc-end-text: #fca5a5; + --oc-step-bg: #374151; + --oc-step-text: #e5e7eb; + --oc-ext-bg: #3b0764; + --oc-ext-border: #6b21a8; + --oc-ext-text: #e9d5ff; + --oc-chip-fg: #fde68a; + --oc-shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 4px 14px rgba(0, 0, 0, 0.22); + --oc-menu-shadow: 0 12px 32px rgba(0, 0, 0, 0.45); + + color: var(--oc-text2); +} + +body[data-theme='light'] .oc-page { + --oc-surface: #fff; + --oc-border: #e5e7eb; + --oc-line: #f0f1f3; + --oc-text: #111827; + --oc-text2: #1f2937; + --oc-sub: #374151; + --oc-muted: #6b7280; + --oc-input: #fff; + --oc-input-border: #d1d5db; + --oc-link: #1d4ed8; + --oc-accent-bg: #eff6ff; + --oc-accent-border: #2563eb; + --oc-accent-soft: #bfdbfe; + --oc-accent-text: #1e3a8a; + --oc-pill: #dbeafe; + --oc-def-border: #6b7280; + --oc-unsaved-bg: #fffbeb; + --oc-unsaved-bar: #d97706; + --oc-unsaved-text: #92400e; + --oc-warn-bg: #fffbeb; + --oc-warn-border: #d97706; + --oc-warn-text: #78350f; + --oc-err-bg: #fef2f2; + --oc-err-border: #dc2626; + --oc-err-text: #b91c1c; + --oc-ok-bg: #dcfce7; + --oc-ok-text: #166534; + --oc-end-bg: #fee2e2; + --oc-end-text: #991b1b; + --oc-step-bg: #f3f4f6; + --oc-step-text: #1f2937; + --oc-ext-bg: #f5f3ff; + --oc-ext-border: #a78bfa; + --oc-ext-text: #5b21b6; + --oc-chip-fg: #92400e; + --oc-shadow: 0 1px 2px rgba(17, 24, 39, 0.06), 0 2px 8px rgba(17, 24, 39, 0.05); + --oc-menu-shadow: 0 12px 32px rgba(17, 24, 39, 0.12); +} + +.oc-card { + background: var(--oc-surface); + border: 1px solid var(--oc-border); + border-radius: 0.625rem; + box-shadow: var(--oc-shadow); +} + +.oc-section { + background: var(--oc-surface); + border: 1px solid var(--oc-border); + border-radius: 0.625rem; + box-shadow: var(--oc-shadow); + padding: 1.125rem 1.25rem 0.375rem; +} + +.oc-section__title { + margin: 0; + font-size: 1rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-section__description { + font-size: 0.8125rem; + color: var(--oc-muted); +} + +.oc-badge-ext { + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.04em; + color: var(--oc-ext-text); + background: var(--oc-ext-bg); + border: 1px solid var(--oc-ext-border); + padding: 0.125rem 0.5rem; + border-radius: 999px; +} + +/* sentence line */ +.oc-line { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding: 0.75rem; + margin: 0 -0.75rem; + border-radius: 0.375rem; +} + +.oc-line + .oc-line { + border-top: 1px solid var(--oc-line); +} + +.oc-line--unsaved { + background: var(--oc-unsaved-bg); + box-shadow: inset 3px 0 0 var(--oc-unsaved-bar); +} + +.oc-line--error { + background: var(--oc-err-bg); + box-shadow: inset 3px 0 0 var(--oc-err-border); +} + +.oc-line--dim .oc-line__sentence { + opacity: 0.55; +} + +.oc-line__row { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 1rem; +} + +.oc-line__sentence { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + font-size: 0.9375rem; + line-height: 1.6; + color: var(--oc-text2); +} + +.oc-line__status { + display: flex; + gap: 0.625rem; + align-items: center; + flex: none; + padding-top: 0.25rem; +} + +.oc-line__help { + font-size: 0.75rem; + line-height: 1.5; + color: var(--oc-muted); +} + +.oc-line__error { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.75rem; + font-weight: 500; + color: var(--oc-err-text); +} + +.oc-unsaved-dot { + display: inline-flex; + align-items: center; + gap: 0.3rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--oc-unsaved-text); +} + +.oc-unsaved-dot::before { + content: ''; + width: 0.5rem; + height: 0.5rem; + border-radius: 50%; + background: currentcolor; +} + +.oc-link { + border: 0; + background: none; + padding: 0; + color: var(--oc-link); + font-size: 0.75rem; + text-decoration: underline; + cursor: pointer; +} + +/* inline controls */ +.oc-ctl { + display: inline-flex; + align-items: center; + gap: 0.375rem; + height: 1.875rem; + padding: 0 0.625rem; + border-radius: 0.375rem; + font-size: 0.875rem; + line-height: 1; + cursor: pointer; + white-space: nowrap; +} + +.oc-ctl--default { + border: 1px dashed var(--oc-def-border); + background: transparent; + color: var(--oc-muted); + font-style: italic; +} + +.oc-ctl--set { + border: 1px solid var(--oc-accent-border); + background: var(--oc-accent-bg); + color: var(--oc-accent-text); + font-weight: 600; +} + +.oc-ctl--error { + border: 1px solid var(--oc-err-border); + background: var(--oc-err-bg); + color: var(--oc-err-text); + font-weight: 600; +} + +.oc-ctl--readonly { + cursor: default; +} + +.oc-ctl--add { + border: 1px dashed var(--oc-def-border); + background: transparent; + color: var(--oc-link); + font-style: normal; + font-weight: 500; +} + +.oc-ctl--input { + box-sizing: border-box; + cursor: text; + outline: none; +} + +.oc-ctl--input.oc-ctl--set { + font-style: normal; +} + +.oc-ctl--input::placeholder { + color: var(--oc-muted); + font-style: italic; + font-weight: 400; +} + +.oc-ctl:focus-visible, +.oc-menu__item:focus-visible, +.oc-link:focus-visible { + outline: 2px solid var(--oc-accent-border); + outline-offset: 2px; +} + +.oc-ctl__caret { + opacity: 0.8; +} + +.oc-inline-list { + display: inline-flex; + flex-wrap: wrap; + gap: 0.375rem; + align-items: center; +} + +.oc-chip { + padding-right: 0.375rem; + cursor: default; +} + +.oc-chip__remove { + border: 0; + background: transparent; + color: inherit; + padding: 0 0 0 0.125rem; + cursor: pointer; + display: inline-flex; +} + +.oc-menu { + z-index: 30; + min-width: 15rem; + margin-top: 0.375rem; + padding: 0.25rem; + background: var(--oc-surface, #1f2937); + border: 1px solid var(--oc-input-border, #4b5563); + border-radius: 0.5rem; + box-shadow: var(--oc-menu-shadow); +} + +.oc-menu__item { + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.75rem; + padding: 0.5rem 0.625rem; + border-radius: 0.375rem; + color: var(--oc-text2); + font-size: 0.875rem; + cursor: pointer; +} + +.oc-menu__item:hover { + background: var(--oc-line); +} + +.oc-menu__label { + display: flex; + flex-direction: column; + gap: 0.0625rem; +} + +.oc-menu__description { + font-size: 0.75rem; + color: var(--oc-muted); +} + +.oc-menu__meta { + display: flex; + gap: 0.5rem; + align-items: center; + font-size: 0.75rem; + color: var(--oc-muted); +} + +.oc-menu__check { + color: var(--oc-accent-border); +} + +/* notices */ +.oc-notice { + display: flex; + gap: 0.75rem; + align-items: flex-start; + padding: 0.75rem 0.875rem; + border-radius: 0.5rem; + font-size: 0.8125rem; + line-height: 1.5; +} + +.oc-notice__icon { + flex: none; + margin-top: 0.2rem; +} + +.oc-notice strong { + font-weight: 600; +} + +.oc-notice--info { + background: var(--oc-accent-bg); + border: 1px solid var(--oc-accent-soft); + color: var(--oc-accent-text); +} + +.oc-notice--warning { + background: var(--oc-warn-bg); + border: 1px solid var(--oc-warn-border); + color: var(--oc-warn-text); +} + +.oc-notice--neutral { + background: var(--oc-surface); + border: 1px solid var(--oc-border); + color: var(--oc-sub); +} + +/* save bar */ +.oc-save-bar { + position: sticky; + bottom: 1.5rem; + z-index: 20; + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; + margin-top: 1rem; + padding: 0.75rem 1rem 0.75rem 1.375rem; + border-radius: 0.625rem; + background: var(--oc-surface); + border: 1px solid var(--oc-unsaved-bar); + box-shadow: + var(--oc-menu-shadow), + inset 4px 0 0 var(--oc-unsaved-bar); +} + +.oc-save-bar__text { + display: flex; + flex-direction: column; + gap: 0.125rem; +} + +.oc-save-bar__title { + font-size: 0.875rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-save-bar__hint { + font-size: 0.75rem; + color: var(--oc-muted); +} + +.oc-save-bar__hint--error { + color: var(--oc-err-text); +} + +.oc-save-bar__actions { + display: flex; + gap: 0.625rem; +} + +.oc-policy-nav { + position: sticky; + top: 1rem; + width: 16rem; + flex: none; + display: flex; + flex-direction: column; + gap: 0.25rem; +} + +.oc-policy-nav__heading { + padding: 0 0.625rem 0.375rem; + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.06em; + color: var(--oc-muted); +} + +.oc-policy-nav__item { + display: flex; + justify-content: space-between; + align-items: center; + gap: 0.5rem; + padding: 0.5rem 0.625rem; + border-radius: 0.375rem; + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-policy-nav__item:hover { + background: var(--oc-surface); + color: var(--oc-text); +} + +.oc-policy-nav__count { + font-size: 0.75rem; + color: var(--oc-muted); + white-space: nowrap; +} + +.oc-policy-nav__count--unsaved { + color: var(--oc-unsaved-text); +} + +.oc-policy-legend { + margin-top: 0.875rem; + padding: 0.75rem; + display: flex; + flex-direction: column; + gap: 0.625rem; + font-size: 0.75rem; + line-height: 1.5; + color: var(--oc-sub); +} + +.oc-policy-legend__title { + font-weight: 600; + color: var(--oc-text); +} + +.oc-policy-legend__row { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 0.25rem; +} + +.oc-checks { + display: flex; + flex-direction: column; + gap: 0.625rem; + padding-bottom: 1rem; +} + +.oc-checks__title { + margin: 0; + font-size: 0.875rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-check { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; + padding: 0.5rem 0; +} + +.oc-check--warning { + padding: 0.75rem 0.875rem; + border-radius: 0.5rem; + background: var(--oc-warn-bg); + border: 1px solid var(--oc-warn-border); +} + +.oc-check__main { + display: flex; + gap: 0.625rem; + align-items: flex-start; +} + +.oc-check__icon { + flex: none; + margin-top: 0.2rem; + color: var(--oc-ok-text); +} + +.oc-check--warning .oc-check__icon { + color: var(--oc-warn-text); +} + +.oc-check__title { + font-size: 0.875rem; + font-weight: 500; + color: var(--oc-text); +} + +.oc-check__body { + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-glance { + position: sticky; + top: 1rem; + width: 22rem; + flex: none; + padding: 1rem; + display: flex; + flex-direction: column; + gap: 0.875rem; +} + +.oc-glance__title { + font-size: 0.875rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-glance__heading { + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--oc-muted); +} + +.oc-role-chip { + display: inline-flex; + align-items: center; + gap: 0.375rem; + height: 1.625rem; + padding: 0 0.5625rem; + border-radius: 999px; + font-size: 0.75rem; + font-weight: 600; + background: var(--oc-step-bg); + color: var(--oc-step-text); +} + +.oc-role-chip--start { + background: var(--oc-accent-bg); + color: var(--oc-accent-text); +} + +.oc-role-chip--complete { + background: var(--oc-ok-bg); + color: var(--oc-ok-text); +} + +.oc-role-chip--end { + background: var(--oc-end-bg); + color: var(--oc-end-text); +} + +.oc-role-chip__note { + font-weight: 400; + opacity: 0.85; +} + +.oc-ov-step { + display: flex; + gap: 0.875rem; + padding: 0.875rem 1rem; +} + +.oc-ov-step__title { + font-size: 0.875rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-ov-list { + list-style: none; + margin: 0; + padding: 0; + display: flex; + flex-direction: column; +} + +.oc-ov-item { + display: flex; + gap: 0.875rem; +} + +.oc-ov-rail { + width: 1.75rem; + flex: none; + display: flex; + flex-direction: column; + align-items: center; +} + +.oc-ov-line { + flex: 1; + width: 2px; + margin: 0.25rem 0; + background: var(--oc-border); +} + +.oc-ov-dot { + width: 1.75rem; + height: 1.75rem; + box-sizing: border-box; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + flex: none; + font-size: 0.75rem; + font-weight: 600; + background: var(--oc-accent-bg); + color: var(--oc-accent-text); + border: 2px solid var(--oc-accent-border); +} + +.oc-ov-dot--end { + background: var(--oc-end-bg); + color: var(--oc-text); + border-color: var(--oc-input-border); +} + +.oc-ov-dot--ghost { + background: transparent; + color: var(--oc-muted); + border: 2px dashed var(--oc-def-border); +} + +.oc-ov-card { + flex: 1; + min-width: 0; + margin-bottom: 0.75rem; + padding: 0.75rem 1rem; + display: flex; + flex-direction: column; + gap: 0.625rem; +} + +.oc-ov-card--branch { + margin-left: 2rem; +} + +.oc-ov-code { + font-family: ui-monospace, Menlo, monospace; + font-size: 0.75rem; + color: var(--oc-muted); +} + +.oc-ov-tag { + font-size: 0.6875rem; + font-weight: 600; + color: var(--oc-sub); + border: 1px solid var(--oc-input-border); + padding: 0 0.375rem; + border-radius: 999px; +} + +.oc-ov-rule { + display: flex; + gap: 0.5rem; + align-items: baseline; + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-ov-rule__icon { + flex: none; + color: var(--oc-muted); +} + +.oc-ov-rule__icon--action { + color: var(--oc-chip-fg); +} + +.oc-ov-none { + font-size: 0.8125rem; + font-style: italic; + color: var(--oc-muted); +} + +.oc-ov-event { + display: flex; + flex-direction: column; + gap: 0.1875rem; + padding-top: 0.625rem; + border-top: 1px solid var(--oc-line); +} + +.oc-ov-event__when { + display: flex; + gap: 0.375rem; + align-items: center; + font-size: 0.8125rem; + font-weight: 600; + color: var(--oc-text2); +} + +.oc-ov-event__then { + padding-left: 1.2rem; + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-ov-event__if { + padding-left: 1.2rem; + font-size: 0.75rem; + color: var(--oc-muted); +} + +.oc-panel-tabs { + display: flex; + gap: 0.25rem; + margin: 0 -1rem 1rem; + padding: 0 1rem; + border-bottom: 1px solid var(--oc-border); +} + +.oc-panel-tab { + height: 2.25rem; + padding: 0 0.75rem; + border: 0; + border-bottom: 2px solid transparent; + background: none; + font-size: 0.8125rem; + color: var(--oc-muted); +} + +.oc-panel-tab--active { + border-bottom-color: var(--oc-accent-border); + color: var(--oc-text); + font-weight: 600; +} + +.oc-step-lead { + margin: 0 0 0.75rem; + font-size: 0.9375rem; + color: var(--oc-text); +} + +.oc-developer-events { + display: flex; + flex-direction: column; + padding-top: 0.75rem; + border-top: 1px solid var(--oc-line); +} + +.oc-trigger-card { + display: flex; + gap: 0.75rem; + align-items: flex-start; + padding: 0.75rem 0.875rem; +} + +.oc-trigger-card--changed { + box-shadow: + inset 3px 0 0 var(--oc-unsaved-bar), + var(--oc-shadow); +} + +.oc-trigger-card__icon { + width: 2rem; + height: 2rem; + flex: none; + border-radius: 0.5rem; + background: var(--oc-pill); + color: var(--oc-accent-text); + display: flex; + align-items: center; + justify-content: center; +} + +.oc-trigger-card__title { + font-size: 0.875rem; + color: var(--oc-text); +} + +.oc-trigger-card__title strong { + font-weight: 600; +} + +.oc-trigger-card__message { + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-trigger-editor { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0.875rem; + border: 2px solid var(--oc-accent-border); +} + +.oc-trigger-editor--error { + border-color: var(--oc-err-border); +} + +.oc-new-badge { + font-size: 0.6875rem; + font-weight: 600; + letter-spacing: 0.04em; + color: var(--oc-unsaved-text); + background: var(--oc-unsaved-bg); + border: 1px solid var(--oc-unsaved-bar); + padding: 0.125rem 0.5rem; + border-radius: 999px; +} + +.oc-token { + height: 1.5rem; + padding: 0 0.5rem; + border-radius: 999px; + border: 1px solid var(--oc-input-border); + background: var(--oc-surface); + color: var(--oc-sub); + font-size: 0.75rem; + font-family: ui-monospace, Menlo, monospace; +} + +.oc-token--pill { + height: 1.625rem; + padding: 0 0.625rem; + font-family: inherit; +} + +.oc-preview { + display: flex; + flex-direction: column; + gap: 0.375rem; + padding: 0.625rem 0.75rem; + border-radius: 0.5rem; + border: 1px solid var(--oc-border); +} + +.oc-preview__body { + display: flex; + gap: 0.625rem; + align-items: flex-start; +} + +.oc-preview__icon { + width: 1.75rem; + height: 1.75rem; + flex: none; + border-radius: 0.375rem; + background: #2563eb; +} + +.oc-preview__title { + font-size: 0.8125rem; + font-weight: 600; + color: var(--oc-text); +} + +.oc-preview__message { + font-size: 0.8125rem; + color: var(--oc-sub); +} + +.oc-trigger-removed { + display: flex; + justify-content: space-between; + align-items: center; + padding: 0.625rem 0.875rem; + border: 1px dashed var(--oc-input-border); + border-radius: 0.625rem; + font-size: 0.8125rem; + color: var(--oc-muted); +} + +.oc-trigger-empty { + padding: 0.875rem; + border: 1px dashed var(--oc-input-border); + border-radius: 0.625rem; + font-size: 0.8125rem; + color: var(--oc-muted); +} + +.oc-add-button { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + width: 100%; + height: 2.5rem; + border-radius: 0.625rem; + border: 1px dashed var(--oc-def-border); + background: transparent; + color: var(--oc-text2); + font-size: 0.875rem; + font-style: normal; +} + +.oc-event-card { + display: flex; + flex-direction: column; + gap: 0.625rem; + padding: 0.875rem; +} + +.oc-event-card--new { + box-shadow: + inset 3px 0 0 var(--oc-unsaved-bar), + var(--oc-shadow); +} + +.oc-save-bar--panel { + bottom: 0.5rem; +} diff --git a/addon/utils/order-config-action-meta.js b/addon/utils/order-config-action-meta.js new file mode 100644 index 000000000..0384c16d3 --- /dev/null +++ b/addon/utils/order-config-action-meta.js @@ -0,0 +1,52 @@ +import humanize from '@fleetbase/ember-core/utils/humanize'; + +/** The icon each known action shows on the flow and in lists; extension actions get a bolt. */ +export const ACTION_ICONS = { + notify_customer: 'bell', + notify_driver: 'bell', + open_chat: 'comments', + close_chat: 'comment-slash', + send_invoice: 'file-invoice', + set_meta: 'tag', + cancel: 'ban', +}; + +/** What the legend calls each icon. */ +export const ICON_GROUPS = [ + { icon: 'bell', key: 'legend-notification', actions: ['notify_customer', 'notify_driver'] }, + { icon: 'comments', key: 'legend-chat', actions: ['open_chat', 'close_chat'] }, + { icon: 'file-invoice', key: 'legend-invoice', actions: ['send_invoice'] }, +]; + +export function actionIcon(name) { + return ACTION_ICONS[name] ?? 'bolt'; +} + +/** + * An action's label: the console's translation when there is one, else the label the server + * describes (an extension's own), else the name made readable. + */ +export function actionLabel(intl, name, described = []) { + for (const key of [`order-config-manager.actions.${name}`, `ledger.order-config-actions.${name}`]) { + if (intl.exists(key)) { + return intl.t(key); + } + } + return described.find((action) => action.name === name)?.label ?? humanize(name ?? ''); +} + +export function actionDescription(intl, name, described = []) { + for (const key of [`order-config-manager.actions.${name}-description`, `ledger.order-config-actions.${name}-description`]) { + if (intl.exists(key)) { + return intl.t(key); + } + } + return described.find((action) => action.name === name)?.description ?? ''; +} + +/** A one-line summary of a trigger: its action and, for notifications, the title in quotes. */ +export function triggerSummary(intl, trigger, described = []) { + const label = actionLabel(intl, trigger?.action, described); + const title = trigger?.params?.title; + return title ? `${label} “${title}”` : label; +} diff --git a/addon/utils/order-config-steps.js b/addon/utils/order-config-steps.js new file mode 100644 index 000000000..ea344778d --- /dev/null +++ b/addon/utils/order-config-steps.js @@ -0,0 +1,38 @@ +import { isArray } from '@ember/array'; +import normalizeOrderConfigFlow, { getOrderConfigFlowRootCode } from './normalize-order-config-flow'; + +/** + * A config's steps in reading order: from the first step, each step followed by the steps it + * leads to, breadth first. A step reached as a second (or later) way out of another is a branch, + * and says which step it branches from. Steps nothing leads to come last. + * + * @returns {Array<{code, label, details, activity, next: Array, branchFrom: ?String, index}>} + */ +export default function orderConfigSteps(config) { + const flow = normalizeOrderConfigFlow(config?.flow ?? {}); + const nextOf = (activity) => (isArray(activity?.activities) ? activity.activities : []).map((next) => (typeof next === 'string' ? next : (next?.code ?? next?.key))).filter(Boolean); + const root = getOrderConfigFlowRootCode(flow, config?.meta?.lifecycle?.initial); + const ordered = []; + const seen = new Set(); + const queue = root ? [{ code: root, branchFrom: null }] : []; + + while (queue.length) { + const { code, branchFrom } = queue.shift(); + if (seen.has(code) || !flow[code]) { + continue; + } + seen.add(code); + ordered.push({ code, branchFrom }); + nextOf(flow[code]).forEach((next, index) => queue.push({ code: next, branchFrom: index > 0 ? code : null })); + } + Object.keys(flow).forEach((code) => { + if (!seen.has(code)) { + ordered.push({ code, branchFrom: null }); + } + }); + + return ordered.map(({ code, branchFrom }, index) => { + const activity = flow[code]; + return { code, label: activity.status || code, details: activity.details, activity, next: nextOf(activity), branchFrom, index }; + }); +} diff --git a/addon/utils/sentence-parts.js b/addon/utils/sentence-parts.js new file mode 100644 index 000000000..f06f42587 --- /dev/null +++ b/addon/utils/sentence-parts.js @@ -0,0 +1,35 @@ +const MARK = '\u0000'; + +/** + * Turns a translated sentence with `{placeholders}` into parts for `OrderConfig::SentenceField`: + * text between the placeholders, and each placeholder replaced by its control. Translating with + * markers instead of splitting the source string keeps word order right in every language. + * + * @param {Service} intl the intl service + * @param {String} key the translation key of the sentence + * @param {Object} controls a part for each placeholder name, e.g. `{ choice: { kind: 'choice', ... } }` + * @param {Object} values other ICU values the sentence needs + * @returns {Array} parts in reading order + */ +export default function sentenceParts(intl, key, controls = {}, values = {}) { + const markers = Object.fromEntries(Object.keys(controls).map((name) => [name, `${MARK}${name}${MARK}`])); + const text = intl.t(key, { ...values, ...markers }); + const parts = []; + + text.split(MARK).forEach((chunk, index) => { + // Odd chunks are placeholder names; even chunks are text between them. + if (index % 2 === 1) { + if (controls[chunk]) { + parts.push(controls[chunk]); + } + return; + } + + const trimmed = chunk.trim(); + if (trimmed) { + parts.push({ kind: 'text', text: trimmed }); + } + }); + + return parts; +} diff --git a/app/components/order-config/inline-list.js b/app/components/order-config/inline-list.js new file mode 100644 index 000000000..48dbe995f --- /dev/null +++ b/app/components/order-config/inline-list.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-list'; diff --git a/app/components/order-config/inline-number.js b/app/components/order-config/inline-number.js new file mode 100644 index 000000000..9c47d1b21 --- /dev/null +++ b/app/components/order-config/inline-number.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-number'; diff --git a/app/components/order-config/inline-select.js b/app/components/order-config/inline-select.js new file mode 100644 index 000000000..663e9921e --- /dev/null +++ b/app/components/order-config/inline-select.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/inline-select'; diff --git a/app/components/order-config/notice.js b/app/components/order-config/notice.js new file mode 100644 index 000000000..43399f86a --- /dev/null +++ b/app/components/order-config/notice.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/notice'; diff --git a/app/components/order-config/order-events.js b/app/components/order-config/order-events.js new file mode 100644 index 000000000..ba7783ab8 --- /dev/null +++ b/app/components/order-config/order-events.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/order-events'; diff --git a/app/components/order-config/sentence-field.js b/app/components/order-config/sentence-field.js new file mode 100644 index 000000000..7c77fb6d2 --- /dev/null +++ b/app/components/order-config/sentence-field.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/sentence-field'; diff --git a/app/components/order-config/trigger-list.js b/app/components/order-config/trigger-list.js new file mode 100644 index 000000000..dfe4ad68c --- /dev/null +++ b/app/components/order-config/trigger-list.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/trigger-list'; diff --git a/app/components/order-config/unsaved-bar.js b/app/components/order-config/unsaved-bar.js new file mode 100644 index 000000000..e2cd32b48 --- /dev/null +++ b/app/components/order-config/unsaved-bar.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/components/order-config/unsaved-bar'; diff --git a/app/utils/order-config-action-meta.js b/app/utils/order-config-action-meta.js new file mode 100644 index 000000000..6dd8a439f --- /dev/null +++ b/app/utils/order-config-action-meta.js @@ -0,0 +1 @@ +export { ACTION_ICONS, ICON_GROUPS, actionIcon, actionLabel, actionDescription, triggerSummary } from '@fleetbase/fleetops-engine/utils/order-config-action-meta'; diff --git a/app/utils/order-config-steps.js b/app/utils/order-config-steps.js new file mode 100644 index 000000000..9d4af272d --- /dev/null +++ b/app/utils/order-config-steps.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/utils/order-config-steps'; diff --git a/app/utils/sentence-parts.js b/app/utils/sentence-parts.js new file mode 100644 index 000000000..f065bcdfa --- /dev/null +++ b/app/utils/sentence-parts.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/utils/sentence-parts'; From 37f76113cb28bf52c0589164bc0b0728230b7736 Mon Sep 17 00:00:00 2001 From: "Ronald A. Richardson" Date: Mon, 16 Nov 2026 12:49:12 +0800 Subject: [PATCH 29/29] feat(order-configs): template picker, entities catalog, dispatch settings and strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New order configs start from template cards that preview the steps and what each template sets up. Entities show as a catalog with size and weight, an empty state with starting points, and placeholders and a preview in the form. Settings → Dispatch gets placeholders, units, an offer-time check and the configs that rely on its defaults. Adds the en-us strings for the redesign and removes the Triggers tab's. --- addon/components/custom-entity/form.hbs | 41 +- addon/components/custom-entity/form.js | 12 + addon/components/modals/new-order-config.hbs | 125 +++- addon/components/order-config-manager.js | 54 +- .../order-config-manager/entities.hbs | 114 ++-- .../order-config-manager/entities.js | 19 + .../order-config-manager/policies.hbs | 2 +- addon/controllers/settings/dispatch.js | 40 ++ addon/helpers/entity-size.js | 12 + addon/helpers/entity-weight.js | 12 + addon/styles/fleetops-engine.css | 205 +++++++ addon/templates/settings/dispatch.hbs | 70 ++- app/helpers/entity-size.js | 1 + app/helpers/entity-weight.js | 1 + .../controllers/settings/dispatch-test.js | 26 + tests/unit/helpers/entity-size-test.js | 17 + tests/unit/utils/order-config-steps-test.js | 38 ++ tests/unit/utils/sentence-parts-test.js | 34 ++ translations/en-us.yaml | 553 +++++++++++++++--- 19 files changed, 1161 insertions(+), 215 deletions(-) create mode 100644 addon/helpers/entity-size.js create mode 100644 addon/helpers/entity-weight.js create mode 100644 app/helpers/entity-size.js create mode 100644 app/helpers/entity-weight.js create mode 100644 tests/unit/helpers/entity-size-test.js create mode 100644 tests/unit/utils/order-config-steps-test.js create mode 100644 tests/unit/utils/sentence-parts-test.js diff --git a/addon/components/custom-entity/form.hbs b/addon/components/custom-entity/form.hbs index 13fcf0027..924ad9653 100644 --- a/addon/components/custom-entity/form.hbs +++ b/addon/components/custom-entity/form.hbs @@ -1,9 +1,25 @@
- - - + + +
@@ -13,13 +29,14 @@ @name={{t "common.photos"}} @accept="image/*" @onFileAdded={{this.onFileAdded}} - @disabled={{not (and @resource.name @resource.description)}} - @helpText={{if (not (and @resource.name @resource.description)) "Input custom entity name and description first to upload image" ""}} + @disabled={{not @resource.name}} + @helpText={{if @resource.name (t "order-config-manager.entities.photo-help") (t "order-config-manager.entities.photo-needs-name")}} class="w-32" />
+

{{t "order-config-manager.entities.size-help"}}

@@ -42,4 +59,16 @@
- \ No newline at end of file +
+
+ {{t "order-config-manager.entities.preview"}} + + + + {{or @resource.name (t "order-config-manager.entities.name-preview")}} + {{this.previewMeta}} + + +
+
+ diff --git a/addon/components/custom-entity/form.js b/addon/components/custom-entity/form.js index 8709280cc..f30b0f8b5 100644 --- a/addon/components/custom-entity/form.js +++ b/addon/components/custom-entity/form.js @@ -7,8 +7,20 @@ import { dasherize } from '@ember/string'; export default class CustomEntityFormComponent extends Component { @service notifications; @service fetch; + @service intl; @tracked config; + /** How the entity reads when it's picked for an order: type, size and weight. */ + get previewMeta() { + const resource = this.args.resource; + const get = (key) => resource?.get?.(key) ?? resource?.[key]; + const size = [get('length'), get('width'), get('height')].every((value) => value !== undefined && value !== null && value !== '') + ? `${get('length')} × ${get('width')} × ${get('height')} ${get('dimensions_unit') ?? ''}`.trim() + : this.intl.t('order-config-manager.entities.no-size'); + const weight = get('weight') ? `${get('weight')} ${get('weight_unit') ?? ''}`.trim() : this.intl.t('order-config-manager.entities.no-weight'); + return [get('type') || this.intl.t('order-config-manager.entities.type-preview'), size, weight].join(' · '); + } + /** * Action method to save the custom entity. It triggers an optional onSave callback * with the current state of the custom entity. diff --git a/addon/components/modals/new-order-config.hbs b/addon/components/modals/new-order-config.hbs index da6b0f130..d8bc78118 100644 --- a/addon/components/modals/new-order-config.hbs +++ b/addon/components/modals/new-order-config.hbs @@ -1,32 +1,99 @@ - diff --git a/app/helpers/entity-size.js b/app/helpers/entity-size.js new file mode 100644 index 000000000..054e0497f --- /dev/null +++ b/app/helpers/entity-size.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/helpers/entity-size'; diff --git a/app/helpers/entity-weight.js b/app/helpers/entity-weight.js new file mode 100644 index 000000000..a524c4e61 --- /dev/null +++ b/app/helpers/entity-weight.js @@ -0,0 +1 @@ +export { default } from '@fleetbase/fleetops-engine/helpers/entity-weight'; diff --git a/tests/unit/controllers/settings/dispatch-test.js b/tests/unit/controllers/settings/dispatch-test.js index 61564bb8a..02ac5249f 100644 --- a/tests/unit/controllers/settings/dispatch-test.js +++ b/tests/unit/controllers/settings/dispatch-test.js @@ -71,4 +71,30 @@ module('Unit | Controller | settings/dispatch', function (hooks) { ]); assert.strictEqual(this.notified[0][0], 'success'); }); + + test('it lists the order configs that offer orders to drivers, and which set their own values', function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + controller.orderConfigs = [ + { id: '1', name: 'Passenger', policies: { dispatch: { adhoc: { customer_orders: true } } } }, + { id: '2', name: 'Shuttle', policies: { dispatch: { adhoc: { customer_orders: true, strategy: 'broadcast', offer_timeout: 45 } } } }, + { id: '3', name: 'Transport', policies: {} }, + ]; + + assert.deepEqual( + controller.adhocConfigs.map((config) => [config.name, config.own]), + [ + ['Passenger', false], + ['Shuttle', true], + ] + ); + assert.strictEqual(controller.overrideCount, 1); + }); + + test('it refuses an offer time outside 10 to 120 seconds', function (assert) { + const controller = this.owner.lookup('controller:settings/dispatch'); + controller.adhocOfferTimeout = 5; + assert.true(controller.timeoutInvalid); + controller.adhocOfferTimeout = 30; + assert.false(controller.timeoutInvalid); + }); }); diff --git a/tests/unit/helpers/entity-size-test.js b/tests/unit/helpers/entity-size-test.js new file mode 100644 index 000000000..b1840dd0a --- /dev/null +++ b/tests/unit/helpers/entity-size-test.js @@ -0,0 +1,17 @@ +import { module, test } from 'qunit'; +import { setupTest } from 'dummy/tests/helpers'; + +module('Unit | Helper | entity-size and entity-weight', function (hooks) { + setupTest(hooks); + + test('they read size and weight with units, or fall back', function (assert) { + const size = this.owner.factoryFor('helper:entity-size').class; + const weight = this.owner.factoryFor('helper:entity-weight').class; + const entity = { length: 120, width: 80, height: 14.4, dimensions_unit: 'cm', weight: 2300, weight_unit: 'kg' }; + + assert.strictEqual(size.compute([entity, 'No size']), '120 × 80 × 14.4 cm'); + assert.strictEqual(weight.compute([entity, 'No weight']), `${(2300).toLocaleString()} kg`); + assert.strictEqual(size.compute([{ length: 1, width: 2 }, 'No size']), 'No size'); + assert.strictEqual(weight.compute([{}, 'No weight']), 'No weight'); + }); +}); diff --git a/tests/unit/utils/order-config-steps-test.js b/tests/unit/utils/order-config-steps-test.js new file mode 100644 index 000000000..049c1a5a2 --- /dev/null +++ b/tests/unit/utils/order-config-steps-test.js @@ -0,0 +1,38 @@ +import { module, test } from 'qunit'; +import orderConfigSteps from 'dummy/utils/order-config-steps'; + +const step = (code, status, activities = [], extra = {}) => ({ code, key: code, status, activities, ...extra }); + +module('Unit | Utility | order-config-steps', function () { + test('it orders steps from the first one, breadth first, marking branches', function (assert) { + const config = { + flow: { + completed: step('completed', 'Trip completed', [], { complete: true }), + no_show: step('no_show', 'No show'), + arrived: step('arrived', 'Arrived', ['in_progress', 'no_show']), + in_progress: step('in_progress', 'In progress', ['completed']), + created: step('created', 'Requested', ['arrived']), + }, + }; + const steps = orderConfigSteps(config); + + assert.deepEqual( + steps.map((s) => s.code), + ['created', 'arrived', 'in_progress', 'no_show', 'completed'] + ); + assert.strictEqual(steps.find((s) => s.code === 'no_show').branchFrom, 'arrived'); + assert.strictEqual(steps.find((s) => s.code === 'in_progress').branchFrom, null); + }); + + test('it starts at the lifecycle initial step and lists unreachable steps last', function (assert) { + const config = { + meta: { lifecycle: { initial: 'booked' } }, + flow: { orphan: step('orphan', 'Orphan'), booked: step('booked', 'Booked', ['done']), done: step('done', 'Done') }, + }; + + assert.deepEqual( + orderConfigSteps(config).map((s) => s.code), + ['booked', 'done', 'orphan'] + ); + }); +}); diff --git a/tests/unit/utils/sentence-parts-test.js b/tests/unit/utils/sentence-parts-test.js new file mode 100644 index 000000000..bd6f59041 --- /dev/null +++ b/tests/unit/utils/sentence-parts-test.js @@ -0,0 +1,34 @@ +import { module, test } from 'qunit'; +import sentenceParts from 'dummy/utils/sentence-parts'; + +// A stand-in for ember-intl: fills `{name}` placeholders like ICU does. +const intl = (sentences) => ({ + t(key, values = {}) { + return sentences[key].replace(/\{(\w+)\}/g, (match, name) => (values[name] === undefined ? match : String(values[name]))); + }, +}); + +module('Unit | Utility | sentence-parts', function () { + test('it splits a sentence into text and its controls, in reading order', function (assert) { + const strategy = { kind: 'choice', value: 'sequential' }; + const seconds = { kind: 'number', value: 20 }; + const parts = sentenceParts(intl({ s: 'Offer them to {strategy}, giving each driver {seconds} seconds to accept.' }), 's', { strategy, seconds }); + + assert.deepEqual(parts, [{ kind: 'text', text: 'Offer them to' }, strategy, { kind: 'text', text: ', giving each driver' }, seconds, { kind: 'text', text: 'seconds to accept.' }]); + }); + + test('it keeps the word order of the translation', function (assert) { + const choice = { kind: 'choice' }; + const parts = sentenceParts(intl({ s: '{choice} sind die Bestellungen.' }), 's', { choice }); + + assert.strictEqual(parts[0], choice); + assert.deepEqual(parts[1], { kind: 'text', text: 'sind die Bestellungen.' }); + }); + + test('it passes other values through to the translation', function (assert) { + const control = { kind: 'number' }; + const parts = sentenceParts(intl({ s: '{label}: {control}' }), 's', { control }, { label: 'Timeout' }); + + assert.deepEqual(parts, [{ kind: 'text', text: 'Timeout:' }, control]); + }); +}); diff --git a/translations/en-us.yaml b/translations/en-us.yaml index 1f1ea562b..a7ced2218 100644 --- a/translations/en-us.yaml +++ b/translations/en-us.yaml @@ -1263,41 +1263,142 @@ order-config-manager: template-help-text: A ready-made configuration for one kind of operation, with its flow, policies and triggers. Change anything once it is created. blank-template: Blank configuration tabs: + overview: Overview details: Details custom-fields: Custom Fields activity-flow: Activity Flow lifecycle: Lifecycle entities: Entities policies: Policies - triggers: Triggers policies: - description: Policies decide how orders of this configuration behave. A setting you leave at its default follows Fleet-Ops' default or your company's dispatch settings. - default: Default - add-value: Add a value - use-default: Use the default - triggers: - title: Triggers - description: What this configuration does when something happens to its orders, such as notifying the customer when the driver arrives. - when: When - do: Do - add: Add Trigger - remove: Remove trigger - empty: No triggers yet. - conditions: This trigger runs only when its {count, plural, one {condition passes} other {# conditions pass}}. - reaches-activity: 'The order reaches: {activity}' - approaching-target: Approaching - approaching-distance: Within (meters) - pickup: Pickup - dropoff: Drop-off - events: - order: - created: The order is created - completed: The order is completed - canceled: The order is canceled - dispatch: - offer_exhausted: No driver accepted the offer - driver: - approaching: The driver is approaching + on-this-page: On this page + nav-defaults: defaults + nav-set: '{count} set' + nav-unsaved: '{count} unsaved' + legend-title: Reading this page + legend-default: 'Left alone: follows the default shown.' + legend-set: Set for this config. Reset brings back the default. + legend-click: Click any highlighted words to change them. + defaults-banner: 'Every policy here follows its default, so this config works like a standard Fleet-Ops order: your team assigns drivers and customers can cancel until it finishes. Change only what your operation needs.' + save-hint: Saved policies apply to new orders. Orders already running keep the policies they started with. + save-hint-errors: '{count, plural, one {Fix the highlighted setting to save.} other {Fix the highlighted settings to save.}}' + saved: Policies saved. New orders use them right away. + applies-when-offered: Applies only when customer orders are offered to nearby drivers. + offering: + title: How are orders offered to drivers? + nav: Offering to drivers + description: 'Whether customer orders go to drivers near the pickup, and how.' + customer-orders: + sentence: 'Orders customers place {choice}.' + wait: wait for an operator to assign them + offer: are offered to nearby drivers + customer-orders-aria: What happens to customer orders + customer-orders-help: Orders your team creates are always assigned or dispatched by your team. + strategy: + sentence: 'Offer them to {strategy}, giving each driver {seconds} seconds to accept.' + sequential: one driver at a time + broadcast: all nearby drivers at once + strategy-only: 'Offer them to {strategy}.' + strategy-aria: How orders are offered + seconds-aria: Seconds each driver has to accept + strategy-help: 'Left empty, these follow Settings → Dispatch: {strategy}, {seconds} seconds.' + radius: 'Look for drivers within {metres} metres of the pickup.' + radius-aria: Search radius in metres + radius-help: 'Left empty, this follows Settings → Dispatch ({metres} m).' + exhausted: + sentence: 'If no driver accepts, {choice}.' + keep-open: keep the order open for an operator + cancel: cancel the order + exhausted-aria: If no driver accepts + exhausted-help: Keeping it open lets your team assign it by hand. + drivers: + title: Which drivers can take them? + nav: Which drivers + description: Narrow down who an order is offered to. + vehicle: + sentence: 'Offer orders to drivers with {choice}.' + any: any vehicle + match: a vehicle that matches the service type + vehicle-aria: Vehicle matching + vehicle-help: The service type is the one the customer chose when ordering. + busy: + sentence: 'Drivers already on an order are {choice}.' + offered: still offered new orders + skipped: skipped + busy-aria: Busy drivers + busy-help: A driver is busy while any of their orders hasn’t reached a step that ends it. + ordering: + title: What do customers need to place an order? + nav: Ordering + description: For orders placed through a customer app or the customer API. + payment: 'Customers can pay by {methods}.' + payment-aria: Payment methods customers can choose + payment-empty: no choice + payment-help: 'Left empty, customers don’t choose how to pay.' + quote: + sentence: 'A price quote is {choice} before ordering.' + optional: optional + required: required + quote-aria: Quote before ordering + quote-help: Required means customers see and accept a price first. + settlement: 'Block new orders while an earlier order paid by {methods} is unpaid.' + settlement-aria: Payment methods that must be settled + settlement-empty: any method · never blocked + settlement-help: 'Usually card or bank transfer: cash is collected by the driver at the end.' + method: + cash: Cash + card: Card + bank_transfer: Bank transfer + wallet: Wallet + cancelling: + title: Can customers cancel? + nav: Cancelling + description: Customers canceling their own orders. + until: 'Customers {choice} their own orders until {step}.' + 'off': 'Customers {choice} their own orders. Your team still can.' + can: can cancel + cannot: can’t cancel + finishes: it finishes + reaches: 'it reaches {step}' + enabled-aria: Customers canceling + until-aria: Cancel until + cancelling-help: 'From that step on, only your team can cancel.' + interactions: + title: What can customers do with the driver? + nav: Customer and driver + description: Contact and feedback between a customer and the driver of their order. + sentence: 'Customers {message} the driver, {rate} them after completion, and {share} a live tracking link.' + message: + 'on': can message + 'off': can’t message + rate: + 'on': can rate + 'off': can’t rate + share: + 'on': can share + 'off': can’t share + message-aria: Messaging the driver + rate-aria: Rating the driver + share-aria: Sharing live tracking + interactions-help: The chat itself opens and closes with what happens at the steps you choose in Activity Flow. + price: + title: How is the price settled? + nav: Price + description: The final price once the order is complete. + reprice: 'On completion, {choice}, measured from {step}.' + no-reprice: 'On completion, {choice}.' + stands: the quoted price stands + recalculate: the price is recalculated from the actual distance and time + from-start: when the order starts + reprice-aria: Final price + from-aria: Measure from + price-help: Recalculating uses the service rate the order was quoted on and updates its invoice. + extension-badge: EXTENSION + extension-fallback: '{label}: {control}' + extension-on: 'on' + extension-off: 'off' + extension-none: not set + extension-aria: Setting details: details: Details name: Name @@ -1314,64 +1415,70 @@ order-config-manager: delete-body-message: Once this order config is deleted it will not be recoverable and you will lose all configurations. confirm-delete: Delete lifecycle: - title: Lifecycle - description: A configured lifecycle lets this order type start, complete and cancel at its own activities instead of the default dispatch lifecycle (created, dispatched, started, completed, canceled). - default-lifecycle: This order type uses the default dispatch lifecycle. Orders start at "created", can be dispatched to drivers and complete or cancel through the standard activities. - enable: Use a configured lifecycle - enable-help: Orders of this type start at the initial activity you choose and follow the activity flow instead of the dispatch lifecycle. - initial: Initial activity - initial-help: New orders of this type start here. Must be an activity in the flow. - completed: Completed activity - completed-help: Reaching this activity completes the order. - canceled: Canceled activity - canceled-help: Canceling an order moves it to this activity. - terminal: Terminal activities - terminal-help: No further transition is allowed after these. The completed and canceled activities are always terminal. - dispatch: Allow dispatch - dispatch-help: When off, orders of this type are never dispatched to drivers and the dispatch actions are refused. - strict-transitions: Strict transitions - strict-transitions-help: When on, an activity can only move to one of its configured next activities in the flow. - select-activity: Select activity - select-activities: Select activities - problems-title: Fix before saving - problem-initial-required: Choose the initial activity. - problem-no-activities: Add at least one activity. - problem-duplicate-code: 'An activity with the code "{code}" already exists.' - activities: Activities - activities-help: The statuses an order of this type can be in. Each activity lists the activities it can move to; the graph on the Activity Flow tab shows the same flow. Changes here are saved with the lifecycle. - activity-label: Label - activity-label-placeholder: e.g. Vehicle Assigned - activity-code: Code - activity-code-help: Stored status value. Derived from the label when left empty; cannot change once added. - activity-code-placeholder: e.g. vehicle_assigned - activity-details: Details - activity-details-placeholder: Shown with the activity in the timeline - activity-color: Colour - activity-next: Can move to - add-activity: Add activity - remove-activity: Remove activity - no-activities: No activities yet. Add the first one below; it becomes the initial activity. - blank-flow: Start from a blank flow - blank-flow-title: Remove all activities? - blank-flow-body: The default dispatch activities (created, dispatched, started, …) are removed so you can define your own. Nothing is saved until you click Save changes. - blank-flow-confirm: Remove activities - initial-short: initial - problem-missing-activity: '"{code}" is not an activity in the flow.' - summary: Summary - summary-initial: Orders start at - summary-completed: Completed at - summary-canceled: Canceled at - summary-terminal: Terminal - summary-dispatch: Dispatch - summary-strict: Strict transitions - 'yes': 'Yes' - 'no': 'No' - none: None - remove: Remove configured lifecycle - remove-title: Remove the configured lifecycle? - remove-body: Orders of this type will use the default dispatch lifecycle again. Existing orders keep their current status. - remove-confirm: Remove - saved: Lifecycle saved for {orderConfigName}. + title: How do orders start and end? + description: 'Which steps begin and finish an order, and how strictly orders follow the flow. The steps themselves are edited on Activity Flow.' + system-banner: 'Its steps come from a template, so how its orders start and end is read-only.' + mode: + sentence: 'Orders follow {choice}.' + standard: the standard dispatch steps + own: this config’s own steps + mode-aria: Which steps orders follow + mode-help-standard: 'Created → Dispatched → Started → Completed, or Canceled. Choose this config’s own steps to set where orders start and end.' + mode-help-own: Orders move through the steps on Activity Flow. + not-set: not set + initial: 'New orders start at {step}.' + initial-aria: Where new orders start + initial-help: 'Orders created by your team, customers or the API all begin here.' + completed: 'An order is complete when it reaches {step}.' + completed-aria: Step that completes the order + completed-help: Completing counts the order as done in reports and invoices. + canceled: 'Canceling an order moves it to {step}.' + canceled-aria: Step for canceled orders + canceled-help: Orders can be canceled from any step that hasn’t ended them. + terminal: 'These steps also end an order: {steps}' + terminal-aria: Other steps that end the order + terminal-none: none + terminal-help: An ended order can’t move again. The complete and cancel steps always end it. + dispatch: + sentence: 'Orders {choice}.' + 'on': can be dispatched to drivers + 'off': are never dispatched + dispatch-aria: Dispatch + dispatch-help: 'Turn dispatch off for orders that don’t need a driver, such as in-store pickups.' + strict: + sentence: 'An order can move {choice}.' + 'off': to any step + 'on': only along the flow’s arrows + strict-aria: Moving between steps + strict-help: Along the arrows stops drivers and your team skipping steps by mistake. + checks: Checks + check-completable: 'New orders can reach {step}' + check-no-dead-ends: Every step leads on or ends the order + check-dead-end: '{step} doesn’t lead anywhere' + check-dead-end-body: 'It has no next step and doesn’t end the order, so orders that reach it get stuck there.' + check-dead-end-fix: Make it end the order + problem-initial-required: Choose the step new orders start at. + problem-missing-activity: '“{code}” is not a step in the flow.' + save-blocked: Fix the highlighted rules to save. + save-hint: Orders already running keep their current status. New rules apply to their next status change. + saved: '{orderConfigName} lifecycle saved.' + at-a-glance: At a glance + glance-starts: Starts at + glance-along: Along the way + glance-ends: Ends at + glance-rules: Rules + glance-complete: complete + glance-canceled: canceled + glance-dispatched: Dispatched to drivers + glance-never-dispatched: Never dispatched + glance-strict: Follows the arrows + glance-any: Any step to any step + standard: + created: Created + dispatched: Dispatched + started: Started + completed: Completed + canceled: Canceled activity-flow: save-activity-flow: Save Activity Flow edit-activity-unique-code-warning: Activity code must be unique! @@ -1390,7 +1497,7 @@ order-config-manager: entities: new-custom-entity: New Custom Entity name: Name - description: Description + description: 'Things that often travel on this kind of order, such as containers, crates or pallets. Add one to an order’s payload in a click, with its size and weight already filled in.' type: Type length: Length width: Width @@ -1399,11 +1506,254 @@ order-config-manager: delete-custom-entity-title: Delete this custom entity? delete-custom-entity-body: Once this custom entity is deleted it will not be recoverable and you will lose all configurations. confirm-delete: Confirm + title: Entities + edit: 'Edit {name}' + no-size: No size + no-weight: No weight + empty-title: No entities on this config + empty-body: 'That’s fine: orders can still carry any item. Add entities for the things you move often, so nobody has to type their size and weight again.' + start-from: 'Start from:' + suggest: + pallet: Euro pallet + parcel: Small parcel + crate: Crate + container: 20 ft container + suitcase: Suitcase + name-placeholder: e.g. 20 ft container + name-help: Shown when adding it to an order. + name-required: Give the entity a name. + type-placeholder: e.g. Container + type-help: Groups entities in the picker. + description-placeholder: 'e.g. Standard dry container, weight when empty' + photo-help: Optional. Shown when picking it for an order. + photo-needs-name: Give the entity a name first. + size-help: Outside dimensions. Used for capacity and vehicle matching. + preview: When adding to an order’s payload + name-preview: Entity name + type-preview: Type types: no-order-installed: No order configurations installed! you-have-no-configs: You currently have no order configs installed, check at the extensions to install an order configuration to get started. view-extensions: View extensions + common: + default: Default + default-suffix: '{value} · default' + reset-to-default: Reset to default + unsaved: Unsaved + unsaved-changes: Unsaved changes + unsaved-count: '{count, plural, one {# unsaved change} other {# unsaved changes}}' + discard: Discard + save-changes: Save changes + add: + Add + edit: Edit + remove: Remove + remove-item: 'Remove {item}' + undo: Undo + done: Done + cancel: Cancel + only-if: Only if + or: or + system-title: System config. + system-banner: 'Made from a template, so it can’t be deleted and its steps are read-only. Its policies and what happens at each step can still be changed.' + readonly-title: View only. + readonly-banner: You can see how this config behaves but not change it. Ask an administrator for the “Update order configs” permission. + steps-readonly: Steps are read-only on this system config + number-range-error: 'Enter a number between {min} and {max}.' + new-config: + title: New order config + intro: 'Start from a template that already sets up the steps, policies and triggers for one kind of operation. You can change all of it afterwards.' + step-label: 'STEP {number}' + step-choose: Choose a starting point + step-name: Name it + selected: Selected + more-templates: 'More templates, such as parcel delivery and rental, will appear here as they’re added.' + preview-empty-title: Pick a template to see what it sets up + preview-empty-hint: Not sure? Transport fits most delivery and haulage work. + preview-title: 'What {template} sets up' + summary: '{steps, plural, =0 {No steps} one {# step} other {# steps}} · {policies, plural, =0 {policies at defaults} one {# policy} other {# policies}} · {triggers, plural, =0 {no triggers} one {# trigger} other {# triggers}}{fields, plural, =0 {} one { · # custom field} other { · # custom fields}}' + summary-blank: Standard steps · policies at defaults · no triggers + name: Name + name-help: Shown when creating orders. The key is made from it. + name-placeholder: e.g. Same-day delivery + name-placeholder-empty: Choose a starting point first + tags: Tags + tags-help: Optional. Helps you find configs later. + tags-placeholder: 'e.g. on-demand, city' + description: Description + create: Create config + create-from: 'Create from {template}' + templates: + transport: + name: Transport + description: 'Deliveries and haulage dispatched by your team, the default every company gets.' + name-placeholder: e.g. Same-day delivery + fact-1: Orders are assigned or dispatched by your team + fact-2: Every policy left at its Fleet-Ops default + fact-3: No automatic notifications yet + passenger: + name: Passenger + description: 'On-demand trips booked by customers, offered to nearby drivers and priced from the actual trip.' + name-placeholder: e.g. Airport shuttle + fact-1: Offered to one nearby driver at a time; canceled if nobody accepts + fact-2: 'Customers can cancel, message, rate and share; card trips settle before the next booking' + fact-3: Customer notified at each step; price recalculated on completion; adds a Passengers field + blank: + name: Blank + description: 'A configuration for a process you want to build yourself, step by step.' + name-placeholder: e.g. Equipment rental + fact-1: Starts with the standard steps; build your own in Activity Flow + fact-2: Every policy left at its Fleet-Ops default + fact-3: Add what happens at each step as you go + flow: + reset: Reset + click-a-step: Click a step to see and change what happens there. + order-events: Order events + legend: Legend + zoom-in: Zoom in + zoom-out: Zoom out + role-start: Start + role-complete: Completes order + role-end: Ends order + legend-notification: Notification + legend-chat: Chat + legend-invoice: Invoice + step: + sections: Step sections + kicker: 'Step {position} of {total}' + saved: Step saved. + tab-details: Details + tab-happens: 'What happens here · {count}' + tab-conditions: Conditions + when-reaches: 'When an order reaches {step}:' + then: Then + what-happens: What happens + choose-action: choose what happens + new: NEW + edited: Edited + no-action-error: Choose what should happen. + removed-note: removed when you save + every-time: Every time + only-if-count: '{count, plural, one {Only if # condition passes} other {Only if # conditions pass}}' + push-notification: Push notification + title: Title + title-placeholder: 'Leave empty to use: {status}' + title-placeholder-event: e.g. Your driver is almost there + message: Message + message-placeholder: Leave empty to use the step’s details + message-fallback: Uses the step’s details + insert: 'Insert:' + insert-token: 'Insert {token}' + preview: Preview with sample data + add-condition: Add a condition + condition-hint: Runs every time unless a condition is added. All conditions must pass. + add: Add something that happens here + quick-add: 'Quick add:' + empty: Nothing happens here yet. Orders just move on. + quick: + notify_customer: Notify customer + notify_driver: Notify driver + open_chat: Open chat + close_chat: Close chat + send_invoice: Send invoice + footnote: 'These run every time an order reaches this step, in this order, without holding the order up. For things that don’t belong to one step, such as an order being canceled, use Order events on the canvas.' + details-readonly: 'This step belongs to a system config or the standard dispatch steps, so its details are read-only.' + status-placeholder: e.g. Arrived at pickup + status-help: What customers and your team see. + code-placeholder: e.g. arrived + code-help: Used by the API and apps. + key-placeholder: e.g. arrived + details-placeholder: e.g. The driver is waiting at the pickup. + details-help: 'Shown in tracking, and used as a notification’s message when it has none of its own.' + completes-order: Completes the order + completes-order-help: Reaching this step marks the order complete. + requires-pod: Requires proof of delivery + requires-pod-help: 'The driver must capture proof, such as a photo or signature, to reach this step.' + developer-events: Developer events + developer-events-help: 'Webhook events sent when an order reaches this step, for integrations. For notifications and other actions, use What happens here.' + conditions-lead: 'Conditions decide whether an order can move to {step}, not what happens when it does.' + conditions-readonly: Read-only on system configs and the standard dispatch steps. + actions: + notify_customer: Notify the customer + notify_customer-description: Push notification to the customer’s app. + notify_driver: Notify the driver + notify_driver-description: Push notification to the driver’s app. + open_chat: Open the customer chat + open_chat-description: Customer and driver can message each other. + close_chat: Close the customer chat + close_chat-description: Ends the chat; its history is kept. + set_meta: Set order meta + set_meta-description: Store a value on the order for reports or integrations. + cancel: Cancel the order + cancel-description: Cancels with the reason you give. + events: + title: Order events + intro: 'What happens when something happens to an order outside its steps. For what happens when an order reaches a step, click the step.' + add: Add an order event + when: 'When {event}' + remove: Remove this order event + then-also: Then also… + empty: No order events yet. + empty-actions: Nothing happens yet. Add what should happen. + created: an order is created + created-menu: An order is created + created-description: 'As soon as it’s placed, by anyone.' + completed: an order is completed + completed-menu: An order is completed + completed-description: Whichever step completes it. + canceled: the order is canceled + canceled-menu: An order is canceled + canceled-description: 'By the customer, your team or a policy.' + exhausted: no driver accepts the order + exhausted-menu: No driver accepts the order + exhausted-description: Every nearby driver declined or let the offer run out. + approaching: 'When the driver is within {metres} metres of the {target}' + approaching-menu: The driver is approaching + approaching-description: Within a distance of the pickup or drop-off. + approaching-short: 'Driver within {metres} m of the {target}' + target-pickup: pickup + target-dropoff: drop-off + target-aria: Pickup or drop-off + distance-aria: Distance in metres + approaching-help: Checked as the driver’s location updates. Runs once per order. + approaching-help-dropoff: 'Checked as the driver’s location updates. Runs once per order, after pickup.' + save: Save order events + saved: Order events saved. + overview: + title: 'What happens to a {config} order' + readonly-hint: Read-only summary. Use the links to change anything. + before: Before the order is placed + edit-policies: Edit policies + edit-step: Edit what happens + edit-events: Edit order events + happens-here: Happens here + policies-apply: Policies that apply + nothing: Nothing + none: None + any-time: Any time + at-a-glance: At a glance + no-events: No order events. + has-condition: Only if its conditions pass + tag-completes: Completes the order + tag-ends: Ends the order + branch-from: 'Ends the order · branch from {step}' + rule-payment: 'Customers pay by {methods}' + rule-quote: Customers accept a price quote first + rule-settlement: 'Customers with an unpaid {methods} order can’t place a new one' + rule-interactions: 'Customers can {list}' + interaction-chat: message the driver + interaction-rating: rate the driver + interaction-share_tracking: share tracking + rule-offered: 'Offered to nearby drivers, not assigned by your team' + rule-vehicle: Only drivers whose vehicle matches the service type + rule-can-cancel: Customer can still cancel + rule-cannot-cancel: Customer can no longer cancel + rule-metering: Distance and time measured from here + rule-repriced: Price recalculated from the actual trip + rule-rating: Customer can rate the driver + glance-steps: '{count, plural, one {# step} other {# steps}} · {ends, plural, =0 {none end the order} one {# ends the order} other {# end the order}}' + glance-automatic: '{count, plural, =0 {Nothing happens automatically} one {# thing happens automatically} other {# things happen automatically}}' + glance-policies: '{count, plural, =0 {Every policy at its default} one {# policy setting changed from the defaults} other {# policy settings changed from the defaults}}' place: fields: details: Place Details @@ -2853,13 +3203,28 @@ route-list: settings: dispatch: title: Fleet-Ops Dispatch - adhoc-orders: Adhoc Orders - intro: How orders without an assigned driver are offered to drivers nearby. An order config or a single order can choose differently. - strategy: How Orders Are Offered - offer-timeout: Offer Time (seconds) - offer-timeout-help-text: How long each driver has to accept before the order goes to the next driver. - ping-radius: Radius (meters) - ping-radius-help-text: How far from the pickup drivers are offered an order. + adhoc-orders: Adhoc dispatch defaults + intro: Company-wide defaults for offering orders to nearby drivers. + override-banner: These apply to every order config that offers orders to nearby drivers and leaves these settings empty. An order config can set its own values on its Policies tab. + override-count: '{count, plural, one {# config sets its own values.} other {# configs set their own values.}}' + strategy: How orders are offered + strategy-placeholder: One driver at a time + strategy-help-text: 'One at a time offers the order to the nearest driver first, then the next if they decline or run out of time. All at once offers it to every nearby driver, and the first to accept gets it.' + offer-timeout: Time each driver has to accept + offer-timeout-placeholder: '20' + offer-timeout-help-text: Between 10 and 120. Leave empty for 20 seconds. + offer-timeout-error: Enter a number between 10 and 120. + ping-radius: Search radius around the pickup + ping-radius-placeholder: '6000' + ping-radius-help-text: 'Drivers farther from the pickup aren’t offered the order. Leave empty for 6,000 m.' + seconds: seconds + metres: metres + section-configs: Order configs that offer orders to drivers + uses-defaults: Uses these defaults + sets-own: 'Sets its own: {settings}' + setting-strategy: how orders are offered + setting-offer_timeout: time to accept + setting-radius: search radius saved: Dispatch settings saved. telematics: telematics-settings: Telematics Settings