Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ember.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
tags:
- 'v*'
pull_request:
branches: [ main, 'dev-v*' ]
branches: [ main, 'release/v*', 'dev-v*' ]

env:
NODE_VERSION: 22.x
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/postman.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ on:
push:
branches: [main]
pull_request:
branches: [main, 'dev-v*']
branches: [main, 'release/v*', 'dev-v*']
workflow_dispatch:
permissions:
contents: read
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ on:
tags:
- 'v*'
pull_request:
branches: [ main, 'dev-v*' ]
branches: [ main, 'release/v*', 'dev-v*' ]

jobs:
build:
Expand Down
31 changes: 23 additions & 8 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,38 @@
> v0.6.61 ~ "A grid view for drivers, a sequenceable order flow, and two silent API no-ops closed"
> v0.6.62 ~ "The public Fleet, Vehicle and Driver APIs now expose what the records actually hold"

---
## Highlights
Two API defects in this release were silent: both answered `200` and neither did what the caller asked. A vehicle odometer update was discarded, and a driver-scoped list came back unscoped. Alongside them, the order config flow now publishes enough of its shape to be sequenced, and Drivers Management gains a card layout.
The public v1 API exposed a small subset of what the Fleet, Vehicle and Driver records can hold, and the gaps were silent: a caller sending a field the controller did not copy received a `200` and a response body that looked correct while the value was discarded. This release closes that gap, adds fleet hierarchies and fleet membership to the public API, and makes it possible to record a driver who has no email address or phone number.

---
## Features
- **Drivers Management has a card view.** A layout toggle switches the index between the table and a card grid, and the choice is remembered across visits.
- **The order config flow publishes its graph.** `activities`, `sequence` and `logic` now ride along with each activity, so a consumer can order the flow and offer a next step instead of rendering an unordered set. Transitions are normalised to a list of codes regardless of which of the two stored shapes a flow was authored in.
- **Fleet create and update accept every safe field.** `name`, `color`, `task`, `status`, and the `service_area`, `zone`, `vendor` and `parent_fleet` relationships. Only `name` and `service_area` were reachable before, so a fleet hierarchy could not be built through the API at all. `"parent_fleet": null` clears a parent; a fleet may not be its own parent, nor sit beneath one of its own descendants.
- **Fleet membership has public endpoints.** `POST` and `DELETE` on `/v1/fleets/{fleet}/vehicles/{vehicle}` and `/v1/fleets/{fleet}/drivers/{driver}`, all four taking public IDs and sharing one response shape. Assignment is idempotent and restores a soft-deleted membership rather than duplicating it; removal is a safe no-op and touches only the pivot, never the driver, the vehicle, the driver's current vehicle, or any other fleet.
- **The Vehicle contract covers the whole record.** The input projection accepted 21 of the model's 99 fields; it now accepts all 90 safe ones — identity, odometer and measurement, body, capacity and dimensions, lifecycle and financing, regulatory and engine specifications, structured `specs`/`details`/`meta`, and orchestrator constraints — each with type-appropriate validation. `vendor`, `category`, `warranty` and `photo` resolve from public IDs.
- **A driver can be recorded without credentials.** `email` and `phone` are optional on create; an operational record may legitimately have neither. Nothing is invented to fill the gap and no invitation is sent when there is nowhere to send one. Such a driver cannot sign in to Navigator until credentials are supplied.
- **Relationships are readable back as public IDs.** A caller that writes `parent_fleet: "fleet_abc"` can now read the assignment back. Asking for a relation through `?with=` still returns the nested object it always did, and internal console responses are unchanged.

---
## Bug Fixes
- **`PUT /v1/vehicles/{id}` silently discarded the odometer.** The field is fillable on the model but was missing from the controller's input projection, so a driver app recording mileage received a `200` and a correct-looking body while the reading was dropped. `odometer` and `odometer_unit` are now accepted and validated.
- **Issue and fuel-report lists scoped by `driver_uuid` came back scoped by nothing.** The base filter silently ignores a query parameter it cannot match to a method, so the filter was dropped and the response was narrowed only by company — every driver's records, with no sign the request had been narrowed at all. `driver_uuid`, `driver_assigned` and `vehicle_uuid` are now recognised on both filters.
- **Leaflet marker icons are served from the leaflet package** rather than resolving to a broken URL.
- **`Driver::$fillable` listed `'meta,'`** — a trailing comma inside the string — so driver metadata was never mass assignable and never persisted through the public API.
- **Driver input was a blocklist, not an allowlist.** Anything nobody had thought to exclude reached `Driver::create()` intact, including `auth_token`, `user_uuid` and `company_uuid`, while `location`, `heading`, `altitude`, `speed` and `meta` were dropped on every write.
- **Driver photo upload wrote `photo_uuid` to `users`,** which has no such column. `User` guards mass assignment by fillable, so every photo uploaded through the public API was discarded without a word. It now writes `avatar_uuid`.
- **A partial vehicle update took the vehicle offline.** The create-time `online` default was applied on update too, so a plate correction or an odometer reading silently reset it.
- **Relationship filters could never match.** `?vendor=`, `?fleet=`, `?driver=` and the fleet hierarchy filters compared caller-supplied public IDs against uuid columns. `FleetFilter::query()` searched a `user` relation Fleet does not have, `DriverFilter::phone()` a `phone` relation that does not exist, and `FleetFilter::zone()` a `zone_uuid` column `zones` does not have — the last three raised rather than filtered.
- **`VehicleFilter` had no `internal_id` filter,** which is the lookup an importer keys on to decide whether a vehicle already exists.
- **Cross-company relationship IDs were accepted and silently dropped.** Relationship inputs were validated with unscoped `exists` rules, so another organization's public ID passed validation and then resolved to nothing. They are now scoped at validation and again at resolution, and a cross-company ID is answered exactly as a missing one — so a response cannot be used to probe another organization's data.
- **The Fleet resource ran four `count()` queries per fleet on every public request** and discarded the results, because `when()` evaluates a plain value argument eagerly.
- **The Fleet webhook payload gated `parent_fleet` on `serviceArea`,** so a subfleet with no service area never reported its parent.

---
## Testing
- Coverage held at 100% across the vehicle input projection, both driver-scoped filters, and the order config flow projection.
- Coverage held at 100% on all three metrics — 34670/34670 statements, 4428/4428 methods, 530/530 classes.
- New database-backed coverage of the fleet membership pivots: idempotent assignment, restore of a soft-deleted membership, repeated removal as a no-op, and preservation of the driver's vehicle and of unrelated fleet memberships.
- Data-driven parity tests prove every newly exposed Fleet, Vehicle and Driver field is accepted and persisted, and that tenancy, authentication and generated columns still are not.

---
## Continuous Integration
- The PHP, Ember and Postman contract workflows now run on pull requests targeting `release/v*`. `release.yml` learned that branch name in v0.6.61's follow-up, but the three check workflows did not — so a PR retargeted onto a release branch ran no checks at all.

---
## Need help?
Expand Down
5 changes: 4 additions & 1 deletion addon/services/map-settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ export default class MapSettingsService extends Service {
@service fetch;
@tracked settings = { ...DEFAULT_SETTINGS };
@tracked isLoaded = false;
@tracked loadPromise = null;
// Internal request deduplication state is not rendered. Keeping this tracked
// makes load() read and then dirty the same tag when called during component
// construction, which Ember correctly rejects as a render-time mutation.
loadPromise = null;

get mapProvider() {
return this.settings.mapProvider ?? 'leaflet';
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fleetbase/fleetops-api",
"version": "0.6.61",
"version": "0.6.62",
"description": "Fleet & Transport Management Extension for Fleetbase",
"keywords": [
"fleetbase-extension",
Expand Down
2 changes: 1 addition & 1 deletion extension.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "Fleet-Ops",
"version": "0.6.61",
"version": "0.6.62",
"description": "Fleet & Transport Management Extension for Fleetbase",
"repository": "https://github.com/fleetbase/fleetops",
"license": "AGPL-3.0-or-later",
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@fleetbase/fleetops-engine",
"version": "0.6.61",
"version": "0.6.62",
"description": "Fleet & Transport Management Extension for Fleetbase",
"fleetbase": {
"route": "fleet-ops"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
* One logical membership per (fleet, vehicle) and (fleet, driver) pair, enforced
* by the database rather than by a read-then-write in the controller.
*
* The public membership endpoints are idempotent by checking for an existing
* pivot and creating one only if there is none. That holds for sequential calls
* and fails for concurrent ones: two requests can both find nothing and both
* insert, leaving a fleet with the same vehicle twice. An importer that retries
* a timed-out request is exactly the caller that produces this.
*
* The index deliberately covers soft-deleted rows too. Unlike the SKU and
* provider-transaction keys — where a tombstone must free the key, and does so
* through a generated column that is NULL when deleted — a removed membership
* here must keep occupying its key, because re-assigning restores that row
* rather than inserting a second one. Letting a tombstone free the key would
* reintroduce the duplicate it is meant to prevent.
*
* Rows with a NULL fleet_uuid or subject_uuid are left alone: MySQL permits any
* number of NULLs in a unique index, and such a row is orphaned data rather than
* a membership.
*/
return new class extends Migration {
/**
* The pivots, and the column naming the member on each.
*
* @var array<string, array{0: string, 1: string}>
*/
private array $pivots = [
'fleet_vehicles' => ['vehicle_uuid', 'fleet_vehicles_fleet_vehicle_unique'],
'fleet_drivers' => ['driver_uuid', 'fleet_drivers_fleet_driver_unique'],
];

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
foreach ($this->pivots as $table => [$memberColumn, $indexName]) {
if (!Schema::hasTable($table)) {
continue;
}

$this->removeDuplicateMemberships($table, $memberColumn);

if (!$this->indexExists($table, $indexName)) {
Schema::table($table, function (Blueprint $blueprint) use ($memberColumn, $indexName) {
$blueprint->unique(['fleet_uuid', $memberColumn], $indexName);
});
}
}
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
foreach ($this->pivots as $table => [$memberColumn, $indexName]) {
if (Schema::hasTable($table) && $this->indexExists($table, $indexName)) {
Schema::table($table, function (Blueprint $blueprint) use ($indexName) {
$blueprint->dropUnique($indexName);
});
}
}
}

/**
* Collapse every duplicated pair down to the one row worth keeping.
*
* An active row wins over a tombstone, because that is the membership the
* fleet actually has today. Among equals the lowest id wins, so the outcome
* is deterministic and a re-run is a no-op. When every row for a pair is
* soft-deleted, one is still kept — removing them all would turn a later
* re-assignment into a new row and lose the original membership's history.
*
* Only redundant pivot rows are removed. No fleet, vehicle or driver is
* touched, and no surviving membership changes state.
*/
private function removeDuplicateMemberships(string $table, string $memberColumn): void
{
$duplicatePairs = DB::table($table)
->select('fleet_uuid', $memberColumn)
->whereNotNull('fleet_uuid')
->whereNotNull($memberColumn)
->groupBy('fleet_uuid', $memberColumn)
->havingRaw('COUNT(*) > 1')
->get();

foreach ($duplicatePairs as $pair) {
$pair = (array) $pair;

$rows = DB::table($table)
->where('fleet_uuid', $pair['fleet_uuid'])
->where($memberColumn, $pair[$memberColumn])
// Active rows first, then oldest first.
->orderByRaw('CASE WHEN deleted_at IS NULL THEN 0 ELSE 1 END')
->orderBy('id')
->pluck('id');

$redundant = $rows->slice(1)->values();

if ($redundant->isNotEmpty()) {
DB::table($table)->whereIn('id', $redundant->all())->delete();
}
}
}

private function indexExists(string $table, string $index): bool
{
$database = DB::connection()->getDatabaseName();

return DB::table('information_schema.statistics')
->where('table_schema', $database)
->where('table_name', $table)
->where('index_name', $index)
->exists();
}
};
47 changes: 47 additions & 0 deletions server/src/Exceptions/PublicRelationNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Fleetbase\FleetOps\Exceptions;

/**
* Thrown when a public relationship input — `vendor`, `parent_fleet`, `zone`,
* and friends — names a resource that does not exist inside the authenticated
* company.
*
* A cross-company identifier is deliberately indistinguishable from a missing
* one: both raise this, so the response cannot be used to probe whether some
* other organization holds a given public id.
*/
class PublicRelationNotFoundException extends \Exception
{
/**
* The request key that failed to resolve, e.g. `parent_fleet`.
*/
private string $relation;

/**
* The public identifier that was supplied for that key.
*/
private ?string $identifier;

public function __construct(string $relation, ?string $identifier = null, ?\Throwable $previous = null)
{
$this->relation = $relation;
$this->identifier = $identifier;

parent::__construct(
sprintf('No %s resource found for the identifier provided.', str_replace('_', ' ', $relation)),
0,
$previous
);
}

public function getRelation(): string
{
return $this->relation;
}

public function getIdentifier(): ?string
{
return $this->identifier;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Fleetbase\FleetOps\Http\Controllers\Api\v1\Concerns;

use Fleetbase\FleetOps\Exceptions\PublicRelationNotFoundException;
use Fleetbase\FleetOps\Models\Contact;
use Fleetbase\FleetOps\Models\Device;
use Fleetbase\FleetOps\Models\Driver;
Expand All @@ -23,16 +24,20 @@

trait ResolvesFleetOpsApiResources
{
protected function resolveUuid(string $modelClass, ?string $id): ?string
protected function resolveUuid(string $modelClass, ?string $id, ?string $companyUuid = null): ?string
{
if (empty($id)) {
return null;
}

return $this->resolveModel($modelClass, $id)->uuid;
return $this->resolveModel($modelClass, $id, $companyUuid)->uuid;
}

protected function resolveModel(string $modelClass, string $id): Model
/**
* @param string|null $companyUuid the company to scope the lookup to; defaults
* to the session company
*/
protected function resolveModel(string $modelClass, string $id, ?string $companyUuid = null): Model
{
$instance = new $modelClass();
$query = $modelClass::query()->where(function ($query) use ($id, $instance) {
Expand All @@ -47,8 +52,10 @@ protected function resolveModel(string $modelClass, string $id): Model
}
});

if (session('company') && $this->modelHasColumn($instance, 'company_uuid')) {
$query->where($instance->qualifyColumn('company_uuid'), session('company'));
$companyUuid = $companyUuid ?? session('company');

if ($companyUuid && $this->modelHasColumn($instance, 'company_uuid')) {
$query->where($instance->qualifyColumn('company_uuid'), $companyUuid);
}

$model = $query->first();
Expand Down Expand Up @@ -114,17 +121,45 @@ protected function isUuidIdentifierKey(string $key): bool
return preg_match('/(^uuid$|_uuid$|Uuid$|UUID$)/', $key) === 1;
}

protected function applyPublicIdRelation(array &$input, string $requestKey, string $column, string $modelClass, $request): void
protected function applyPublicIdRelation(array &$input, string $requestKey, string $column, string $modelClass, $request, ?string $companyUuid = null): void
{
if (!$request->exists($requestKey)) {
return;
}

$input[$column] = filled($request->input($requestKey))
? $this->resolveUuid($modelClass, $request->input($requestKey))
? $this->resolveUuid($modelClass, $request->input($requestKey), $companyUuid)
: null;
}

/**
* Apply a set of public-ID relationship inputs in one pass.
*
* `$map` is keyed by the public request key and holds `[column, modelClass]`,
* e.g. `['parent_fleet' => ['parent_fleet_uuid', Fleet::class]]`. A key that is
* absent from the request is left untouched; a key sent empty clears the column.
*
* Resolution failures are rethrown as a PublicRelationNotFoundException so the
* caller can say which input was at fault rather than answering with a bare
* "not found" that names no field.
*
* @param array<string, array{0: string, 1: class-string}> $map
*
* @throws PublicRelationNotFoundException
*/
protected function applyPublicIdRelations(array &$input, array $map, $request, ?string $companyUuid = null): void
{
foreach ($map as $requestKey => [$column, $modelClass]) {
try {
$this->applyPublicIdRelation($input, $requestKey, $column, $modelClass, $request, $companyUuid);
} catch (ModelNotFoundException $exception) {
$identifier = $request->input($requestKey);

throw new PublicRelationNotFoundException($requestKey, is_scalar($identifier) ? (string) $identifier : null, $exception);
}
}
}

protected function allowedMorphTypes(): array
{
return [
Expand Down
Loading
Loading