Skip to content

A free open source IT asset/license management system

Advanced search: Fixed #19708 - sorting/filtering on jobtitle

snipea424be87f838
diff --git a/app/Models/Asset.php b/app/Models/Asset.php
index 594b254553..beae8ce1c5 100644
--- a/app/Models/Asset.php
+++ b/app/Models/Asset.php
@@ -282,6 +282,12 @@ class Asset extends Depreciable
'rtd_location' => 'defaultLoc',
];
+
+ protected $searchableRelationColumns = [
+ 'jobtitle' => ['relation' => 'assignedTo', 'column' => 'jobtitle', 'types' => [\App\Models\User::class]],
+ 'employee_num' => ['relation' => 'assignedTo', 'column' => 'employee_num', 'types' => [\App\Models\User::class]],
+ ];
+
protected static function booted(): void
{
static::forceDeleted(function (Asset $asset) {
@@ -2240,7 +2246,14 @@ class Asset extends Depreciable
*/
public function scopeOrderAssigned($query, $order)
{
- return $query->leftJoin('users as users_sort', 'assets.assigned_to', '=', 'users_sort.id')->select('assets.*')->orderBy('users_sort.first_name', $order)->orderBy('users_sort.last_name', $order);
+ return $query
+ ->leftJoin('users as users_sort', function ($join) {
+ $join->on('assets.assigned_to', '=', 'users_sort.id')
+ ->where('assets.assigned_type', '=', User::class);
+ })
+ ->addSelect('assets.*')
+ ->orderBy('users_sort.first_name', $order)
+ ->orderBy('users_sort.last_name', $order);
}
/**
@@ -2394,7 +2407,13 @@ class Asset extends Depreciable
*/
public function scopeOrderByJobTitle($query, $order)
{
- return $query->leftJoin('users as users_sort', 'assets.assigned_to', '=', 'users_sort.id')->select('assets.*')->orderBy('users_sort.jobtitle', $order);
+ return $query
+ ->leftJoin('users as users_sort', function ($join) {
+ $join->on('assets.assigned_to', '=', 'users_sort.id')
+ ->where('assets.assigned_type', '=', User::class);
+ })
+ ->addSelect('assets.*')
+ ->orderBy('users_sort.jobtitle', $order);
}
/**
diff --git a/app/Models/Traits/Searchable.php b/app/Models/Traits/Searchable.php
index 71aa349fb2..aea9328648 100644
--- a/app/Models/Traits/Searchable.php
+++ b/app/Models/Traits/Searchable.php
@@ -371,6 +371,22 @@ trait Searchable
}
}
+ // Columns that live on a related table but surface as a
+ // top-level filter key (e.g. the "Title" column on the hardware
+ // list renders users.jobtitle but admins expect to filter it
+ // like a native asset attribute). Falls through to the normal
+ // relation-key path if no mapping is defined.
+ $relationColumnMap = $this->getSearchableRelationColumns();
+ if (array_key_exists($filterKey, $relationColumnMap)) {
+ return $this->applyRelationColumnFilter(
+ query: $query,
+ mapping: $relationColumnMap[$filterKey],
+ value: $value,
+ boolean: $boolean,
+ operator: $operator,
+ );
+ }
+
$resolvedRelationKey = $this->resolveSearchableRelationKey($filterKey, $searchableRelations);
if ($resolvedRelationKey === null) {
@@ -777,6 +793,20 @@ trait Searchable
return $query;
}
+ // Relation column: filter key is a column on a related table
+ // surfaced as a top-level filter (e.g. jobtitle = users.jobtitle
+ // via assignedTo on assets). Dispatched the same way as regular
+ // relation-column filtering above (#19708).
+ $relationColumnMap = $this->getSearchableRelationColumns();
+ if (array_key_exists($filterKey, $relationColumnMap)) {
+ return $this->applyRelationColumnNullFilter(
+ query: $query,
+ mapping: $relationColumnMap[$filterKey],
+ isNull: $isNull,
+ boolean: $boolean,
+ );
+ }
+
// Relation key: no related record = "null", has a related record = "not null".
$searchableRelations = $this->getSearchableRelations();
$resolvedRelationKey = $this->resolveSearchableRelationKey($filterKey, $searchableRelations);
@@ -1108,6 +1138,144 @@ trait Searchable
return $this->searchableRelationAliases ?? [];
}
+ /**
+ * Columns that live on a related table but surface as a top-level
+ * filter key on the current model's advanced-search UI. The hardware
+ * list's "Title" column (= users.jobtitle via the assignedTo
+ * polymorphic morph) is the first case: admins filter it like a
+ * native attribute, but it isn't in $searchableAttributes and
+ * doesn't match the $searchableRelations key dispatch. Define it
+ * here and both the LIKE / exact filter path and the is:null /
+ * is:not_null null-check path will route through whereHas /
+ * whereHasMorph on the right table (#19708).
+ *
+ * Shape: `[filter_key => ['relation' => string, 'column' => string, 'types' => ?array<class-string>]]`.
+ * `types` is only required for polymorphic morphs so the trait
+ * knows which concrete morph classes host the column. For plain
+ * belongsTo / hasOne relations, leave it unset.
+ *
+ * @return array<string, array{relation: string, column: string, types?: array<int, class-string>}>
+ */
+ protected function getSearchableRelationColumns(): array
+ {
+ return $this->searchableRelationColumns ?? [];
+ }
+
+ /**
+ * @param array{relation: string, column: string, types?: array<int, class-string>} $mapping
+ */
+ private function applyRelationColumnFilter(Builder $query, array $mapping, string $value, string $boolean, string $operator): Builder
+ {
+ $isExact = in_array($operator, ['exact', 'exact_not'], true);
+ $isNegate = in_array($operator, ['not_like', 'exact_not'], true);
+ $comparison = match (true) {
+ $operator === 'exact' => '=',
+ $operator === 'exact_not' => '!=',
+ $isNegate => 'NOT LIKE',
+ default => 'LIKE',
+ };
+ $compareValue = $isExact ? $value : '%'.$value.'%';
+
+ $apply = function (Builder $relationQuery) use ($mapping, $comparison, $compareValue): void {
+ $relationQuery->where($mapping['column'], $comparison, $compareValue);
+ };
+
+ if (! empty($mapping['types'])) {
+ // Polymorphic morph: constrain to the listed concrete
+ // classes so the inner where runs against the right table.
+ // Negated filters additionally include records whose morph
+ // target is a different class (or no target at all), so
+ // "jobtitle NOT LIKE X" doesn't silently drop every
+ // asset assigned to a non-user.
+ if ($isNegate) {
+ $compoundMethod = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$compoundMethod}(function (Builder $compound) use ($mapping, $apply): void {
+ $compound->doesntHaveMorph($mapping['relation'], $mapping['types'])
+ ->orWhereHasMorph($mapping['relation'], $mapping['types'], $apply);
+ });
+ } else {
+ $method = $boolean === 'or' ? 'orWhereHasMorph' : 'whereHasMorph';
+ $query->{$method}($mapping['relation'], $mapping['types'], $apply);
+ }
+
+ return $query;
+ }
+
+ if ($isNegate) {
+ $compoundMethod = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$compoundMethod}(function (Builder $compound) use ($mapping, $apply): void {
+ $compound->doesntHave($mapping['relation'])
+ ->orWhereHas($mapping['relation'], $apply);
+ });
+ } else {
+ $method = $boolean === 'or' ? 'orWhereHas' : 'whereHas';
+ $query->{$method}($mapping['relation'], $apply);
+ }
+
+ return $query;
+ }
+
+ /**
+ * @param array{relation: string, column: string, types?: array<int, class-string>} $mapping
+ */
+ private function applyRelationColumnNullFilter(Builder $query, array $mapping, bool $isNull, string $boolean): Builder
+ {
+ // is:not_null = "a related record exists whose column is
+ // non-null and (for text columns) non-empty".
+ // is:null = exactly the complement: unassigned, assigned to
+ // a different morph type, or related record
+ // with a null / empty column. The UI column
+ // renders those identically, so admins expect
+ // them to filter identically too.
+ //
+ // Using whereDoesntHaveMorph with the "non-empty" constraint
+ // expresses "null" without having to enumerate the three
+ // sub-cases by hand, and the empty-string flip matches the
+ // isTextTypeColumn fix on attribute columns (#19708).
+ $visiblyPresent = function (Builder $relationQuery) use ($mapping): void {
+ $table = $relationQuery->getModel()->getTable();
+ $column = $mapping['column'];
+ $qualified = $table.'.'.$column;
+
+ $relationQuery->whereNotNull($qualified);
+ if ($this->isTextTypeColumn($table, $column)) {
+ $relationQuery->where($qualified, '!=', '');
+ }
+ };
+
+ if (! empty($mapping['types'])) {
+ if ($isNull) {
+ // whereDoesntHaveMorph adds `assigned_type = <Type>`
+ // to the outer WHERE, which excludes unassigned rows
+ // (assigned_type IS NULL) and rows whose morph type
+ // isn't in the list. Wrap it with an explicit
+ // null-or-mismatched-type branch so the three ways
+ // the UI column reads as "empty" all match.
+ $table = $query->getModel()->getTable();
+ $compoundMethod = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$compoundMethod}(function (Builder $compound) use ($table, $mapping, $visiblyPresent): void {
+ $compound->whereNull($table.'.assigned_type')
+ ->orWhereNotIn($table.'.assigned_type', $mapping['types'])
+ ->orWhereDoesntHaveMorph($mapping['relation'], $mapping['types'], $visiblyPresent);
+ });
+ } else {
+ $method = $boolean === 'or' ? 'orWhereHasMorph' : 'whereHasMorph';
+ $query->{$method}($mapping['relation'], $mapping['types'], $visiblyPresent);
+ }
+
+ return $query;
+ }
+
+ if ($isNull) {
+ $method = $boolean === 'or' ? 'orWhereDoesntHave' : 'whereDoesntHave';
+ } else {
+ $method = $boolean === 'or' ? 'orWhereHas' : 'whereHas';
+ }
+ $query->{$method}($mapping['relation'], $visiblyPresent);
+
+ return $query;
+ }
+
/**
* Get structured-filter relation columns for a given filter key.
*
diff --git a/tests/Feature/Assets/OrderByJobTitleTest.php b/tests/Feature/Assets/OrderByJobTitleTest.php
new file mode 100644
index 0000000000..054addd78d
--- /dev/null
+++ b/tests/Feature/Assets/OrderByJobTitleTest.php
@@ -0,0 +1,132 @@
+<?php
+
+namespace Tests\Feature\Assets;
+
+use App\Models\Asset;
+use App\Models\Location;
+use App\Models\User;
+use Tests\TestCase;
+
+class OrderByJobTitleTest extends TestCase
+{
+ public function test_location_assigned_asset_does_not_borrow_jobtitle_from_a_coincidentally_numbered_user(): void
+ {
+ // Seed a user and a location whose IDs happen to collide. The
+ // unconstrained leftJoin would match the location-assigned
+ // asset against this user's jobtitle. The constrained join
+ // leaves it as NULL and sorts it to the end on DESC.
+ $sharedId = $this->firstFreeIdSharedBy(User::class, Location::class);
+
+ $decoyUser = User::factory()->create([
+ 'id' => $sharedId,
+ 'jobtitle' => 'ZZZ Should Not Leak',
+ ]);
+ $location = Location::factory()->create([
+ 'id' => $sharedId,
+ 'name' => 'Headquarters',
+ ]);
+
+ $alphaAssignee = User::factory()->create(['jobtitle' => 'Alpha Analyst']);
+ $zuluAssignee = User::factory()->create(['jobtitle' => 'Zulu Zoologist']);
+
+ $alphaAsset = Asset::factory()->assignedToUser($alphaAssignee)->create();
+ $zuluAsset = Asset::factory()->assignedToUser($zuluAssignee)->create();
+ $locationAsset = Asset::factory()->assignedToLocation($location)->create();
+
+ $ordered = Asset::OrderByJobTitle('desc')
+ ->whereIn('assets.id', [$alphaAsset->id, $zuluAsset->id, $locationAsset->id])
+ ->get();
+
+ $this->assertSame(
+ [
+ (int) $zuluAsset->id,
+ (int) $alphaAsset->id,
+ (int) $locationAsset->id,
+ ],
+ $ordered->pluck('id')->map(fn($id) => (int) $id)->all(),
+ 'Location-assigned asset must sort as NULL (last on DESC), not borrow the jobtitle of the user whose id happens to match the location id.',
+ );
+ }
+
+ public function test_null_jobtitles_sort_last_on_desc(): void
+ {
+ $titled = User::factory()->create(['jobtitle' => 'Mid-level Something']);
+ $untitled = User::factory()->create(['jobtitle' => null]);
+
+ $titledAsset = Asset::factory()->assignedToUser($titled)->create();
+ $untitledAsset = Asset::factory()->assignedToUser($untitled)->create();
+
+ $ordered = Asset::OrderByJobTitle('desc')
+ ->whereIn('assets.id', [$titledAsset->id, $untitledAsset->id])
+ ->get();
+
+ $this->assertSame(
+ [(int) $titledAsset->id, (int) $untitledAsset->id],
+ $ordered->pluck('id')->map(fn($id) => (int) $id)->all(),
+ );
+ }
+
+ public function test_order_assigned_location_asset_does_not_borrow_name_from_a_coincidentally_numbered_user(): void
+ {
+ // Same shape of bug as the OrderByJobTitle case: the assigned-to
+ // sort was leftJoining on assets.assigned_to = users_sort.id
+ // without the assigned_type guard, so a Location-assigned asset
+ // would pick up a user's name as the sort key when the ids
+ // coincided. Fix must send location-assigned rows to the end
+ // on DESC (NULL last), not interleave them with real users.
+ $sharedId = $this->firstFreeIdSharedBy(User::class, Location::class);
+
+ $decoyUser = User::factory()->create([
+ 'id' => $sharedId,
+ 'first_name' => 'ZZZ',
+ 'last_name' => 'Decoy',
+ ]);
+ $location = Location::factory()->create([
+ 'id' => $sharedId,
+ 'name' => 'Field Office',
+ ]);
+
+ $alphaUser = User::factory()->create(['first_name' => 'Alpha', 'last_name' => 'Analyst']);
+ $zuluUser = User::factory()->create(['first_name' => 'Zulu', 'last_name' => 'Zoologist']);
+
+ $alphaAsset = Asset::factory()->assignedToUser($alphaUser)->create();
+ $zuluAsset = Asset::factory()->assignedToUser($zuluUser)->create();
+ $locationAsset = Asset::factory()->assignedToLocation($location)->create();
+
+ $ordered = Asset::OrderAssigned('desc')
+ ->whereIn('assets.id', [$alphaAsset->id, $zuluAsset->id, $locationAsset->id])
+ ->get();
+
+ $this->assertSame(
+ [
+ (int) $zuluAsset->id,
+ (int) $alphaAsset->id,
+ (int) $locationAsset->id,
+ ],
+ $ordered->pluck('id')->map(fn($id) => (int) $id)->all(),
+ 'Location-assigned asset must sort as NULL (last on DESC), not borrow the name of the user whose id happens to match the location id.',
+ );
+ }
+
+ /**
+ * Find an id value that both factories can assign so we can create
+ * a user and a location with the same numeric id, which is what
+ * reproduces the bogus-join sort bug.
+ */
+ private function firstFreeIdSharedBy(string $classA, string $classB): int
+ {
+ $candidate = max(
+ (int) $classA::max('id'),
+ (int) $classB::max('id'),
+ ) + 100;
+
+ while (
+ $classA::whereKey($candidate)->exists()
+ || $classB::whereKey($candidate)->exists()
+ ) {
+ $candidate++;
+ }
+
+ return $candidate;
+ }
+}
diff --git a/tests/Feature/Search/SearchableTraitTest.php b/tests/Feature/Search/SearchableTraitTest.php
index 98148599dc..71969bf147 100644
--- a/tests/Feature/Search/SearchableTraitTest.php
+++ b/tests/Feature/Search/SearchableTraitTest.php
@@ -982,6 +982,107 @@ class SearchableTraitTest extends TestCase
$this->assertNotContains((int) $unassignedAsset->id, $returnedNotNullIds);
}
+ /**
+ * Regression coverage for the follow-up half of #19708. The "Title"
+ * column on the hardware list renders users.jobtitle via the
+ * assignedTo polymorphic morph, but the trait had no plumbing for
+ * "column on a related table surfaced as a top-level filter key",
+ * so is:null / is:not_null (and plain LIKE) silently dropped the
+ * filter and returned every row. The fix routes `jobtitle` through
+ * whereHasMorph on assignedTo so all three operators work the way
+ * the UI implies.
+ */
+ public function test_jobtitle_filter_matches_assigned_user_jobtitle()
+ {
+ $ts = now()->timestamp;
+
+ $engineer = User::factory()->create(['jobtitle' => 'Site Engineer '.$ts]);
+ $designer = User::factory()->create(['jobtitle' => 'Senior Designer '.$ts]);
+
+ $engineerAsset = Asset::factory()->assignedToUser($engineer)->create();
+ $designerAsset = Asset::factory()->assignedToUser($designer)->create();
+
+ $superuser = User::factory()->viewAssets()->create();
+
+ $response = $this->actingAsForApi($superuser)
+ ->getJson(route('api.assets.index', ['filter' => json_encode(['jobtitle' => 'Engineer'])]))
+ ->assertOk();
+
+ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();
+
+ $this->assertContains((int) $engineerAsset->id, $returnedIds);
+ $this->assertNotContains((int) $designerAsset->id, $returnedIds);
+ }
+
+ public function test_is_not_null_filter_on_jobtitle_relation_column_matches_assets_with_titled_assignee()
+ {
+ $ts = now()->timestamp;
+
+ $withTitle = User::factory()->create(['jobtitle' => 'VP Operations '.$ts]);
+ $withoutTitle = User::factory()->create(['jobtitle' => null]);
+ $withEmptyTitle = User::factory()->create(['jobtitle' => '']);
+
+ $titledAsset = Asset::factory()->assignedToUser($withTitle)->create();
+ $nullTitleAsset = Asset::factory()->assignedToUser($withoutTitle)->create();
+ $emptyTitleAsset = Asset::factory()->assignedToUser($withEmptyTitle)->create();
+ $unassignedAsset = Asset::factory()->create([
+ 'assigned_to' => null,
+ 'assigned_type' => null,
+ ]);
+
+ $superuser = User::factory()->viewAssets()->create();
+
+ $response = $this->actingAsForApi($superuser)
+ ->getJson(route('api.assets.index', ['filter' => json_encode(['jobtitle' => 'is:not_null'])]))
+ ->assertOk();
+
+ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();
+
+ $this->assertContains((int) $titledAsset->id, $returnedIds);
+ $this->assertNotContains(
+ (int) $nullTitleAsset->id,
+ $returnedIds,
+ 'Assignee with a NULL jobtitle must not surface as "has title".'
+ );
+ $this->assertNotContains(
+ (int) $emptyTitleAsset->id,
+ $returnedIds,
+ 'Assignee with an empty-string jobtitle must not surface as "has title", the way admins read the UI column.',
+ );
+ $this->assertNotContains((int) $unassignedAsset->id, $returnedIds);
+ }
+
+ public function test_is_null_filter_on_jobtitle_relation_column_matches_untitled_and_unassigned()
+ {
+ $ts = now()->timestamp;
+
+ $withTitle = User::factory()->create(['jobtitle' => 'Director of Something '.$ts]);
+ $withoutTitle = User::factory()->create(['jobtitle' => null]);
+
+ $titledAsset = Asset::factory()->assignedToUser($withTitle)->create();
+ $nullTitleAsset = Asset::factory()->assignedToUser($withoutTitle)->create();
+ $unassignedAsset = Asset::factory()->create([
+ 'assigned_to' => null,
+ 'assigned_type' => null,
+ ]);
+
+ $superuser = User::factory()->viewAssets()->create();
+
+ $response = $this->actingAsForApi($superuser)
+ ->getJson(route('api.assets.index', ['filter' => json_encode(['jobtitle' => 'is:null'])]))
+ ->assertOk();
+
+ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();
+
+ $this->assertNotContains((int) $titledAsset->id, $returnedIds);
+ $this->assertContains((int) $nullTitleAsset->id, $returnedIds);
+ $this->assertContains(
+ (int) $unassignedAsset->id,
+ $returnedIds,
+ 'An asset with no assignee should present as "no title" from the UI column standpoint.',
+ );
+ }
+
/**
* Test custom field partial match via filter.
*/