A free open source IT asset/license management system
Added loads of comments - this is gnarly stuff
snipe62e5b71dc1fc
diff --git a/app/Models/Traits/Searchable.php b/app/Models/Traits/Searchable.phpindex 89e6ed96a2..1021d59583 100644--- a/app/Models/Traits/Searchable.php+++ b/app/Models/Traits/Searchable.php@@ -59,6 +59,8 @@ trait Searchable$filterOperator = $preparedSearch['filter_operator'];if (! empty($filters)) {+ // Structured advanced-search filters are mutually exclusive with free-text terms.+ // Once we detect structured payloads, we avoid the broad OR-based free-text path.return $this->applySearchFilters($query, $filters, $filterOperator);}@@ -135,6 +137,7 @@ trait Searchable$payload = $search;if (str_starts_with($search, 'filter:')) {+ // Some callers send filter payloads with an explicit "filter:" prefix.$payload = substr($search, 7);} elseif (! (str_starts_with($search, '{') && str_ends_with($search, '}'))) {return null;@@ -160,6 +163,7 @@ trait Searchable$normalizedValue = trim((string) ($value ?? ''));if ($normalizedValue === '') {+ // Ignore empty fields so clearing an input does not create noisy no-op filters.continue;}@@ -229,14 +233,17 @@ trait Searchable$lower = strtolower($raw);if ($lower === 'is:null') {+ // Reserved token: interpreted as null-check operator, not exact match string.return ['value' => '', 'negate' => false, 'operator' => 'is_null'];}if ($lower === 'is:not_null') {+ // Reserved token: interpreted as non-null check operator.return ['value' => '', 'negate' => false, 'operator' => 'is_not_null'];}if (str_starts_with($lower, 'is:')) {+ // Generic exact-match prefix. This is checked after reserved is:null/is:not_null tokens.$exactValue = substr($raw, 3);return ['value' => $exactValue, 'negate' => false, 'operator' => 'exact'];@@ -314,6 +321,8 @@ trait Searchable// Exact match on the full CONCAT'd value, e.g. "John Smith" matches only// users whose first_name + ' ' + last_name equals exactly "John Smith".$concatSql = $this->buildMultipleColumnSearch($qualifiedColumns);+ // buildMultipleColumnSearch intentionally returns a fragment ending in "LIKE ?";+ // for exact matches we rewrite only the operator and keep the same SQL scaffold.$concatSql = str_replace(' LIKE ?', ' = ?', $concatSql);$rawMethod = $boolean === 'or' ? 'orWhereRaw' : 'whereRaw';$query->{$rawMethod}($concatSql, [$value]);@@ -342,6 +351,8 @@ trait Searchable$dbColumn = $this->resolveCustomFieldDbColumn($filterKey);if ($dbColumn !== null) {+ // Structured custom-field filters currently support LIKE/NOT LIKE semantics only.+ // (No exact/is:null operators for custom fields yet.)$query->{$whereMethod}($table.'.'.$dbColumn, $likeOperator, '%'.$value.'%');return $query;@@ -358,7 +369,53 @@ trait Searchablereturn $this->applyAssignedToRelationFilter($query, $resolvedRelationKey, $value, $boolean, $negate);}- $relationColumns = (array) $searchableRelations[$resolvedRelationKey];+ $relationColumns = $this->getStructuredFilterRelationColumns(+ filterKey: $filterKey,+ resolvedRelationKey: $resolvedRelationKey,+ searchableRelations: $searchableRelations,+ );++ // For negated relation filters (e.g. location: !dam), include rows with+ // no related record as well as rows with related records that do not match.+ // This aligns advanced-search behavior with user expectation for "not X".+ if ($operator !== 'exact' && $likeOperator === 'NOT LIKE') {+ $compoundMethod = $boolean === 'or' ? 'orWhere' : 'where';++ $query->{$compoundMethod}(function (Builder $compoundQuery) use ($resolvedRelationKey, $relationColumns, $value): void {+ // Critical behavior: "not X" on relations should include records with no relation.+ // Example: location=!dam should include users without a location.+ $compoundQuery->doesntHave($resolvedRelationKey)+ ->orWhereHas($resolvedRelationKey, function (Builder $relationQuery) use ($resolvedRelationKey, $relationColumns, $value): void {+ $relationTable = $this->getRelationTable($resolvedRelationKey);+ $firstConditionAdded = false;++ foreach ($relationColumns as $relationColumn) {+ if (! $firstConditionAdded) {+ $relationQuery->where($relationTable.'.'.$relationColumn, 'NOT LIKE', '%'.$value.'%');+ $firstConditionAdded = true;++ continue;+ }++ // For negation we AND the NOT LIKE conditions so all columns must not match.+ $relationQuery->where($relationTable.'.'.$relationColumn, 'NOT LIKE', '%'.$value.'%');+ }++ if (($resolvedRelationKey === 'adminuser') || ($resolvedRelationKey === 'user')) {+ $concatSql = $this->buildMultipleColumnSearch([+ 'users.first_name',+ 'users.last_name',+ 'users.display_name',+ ]);++ $relationQuery->whereRaw(str_replace('LIKE', 'NOT LIKE', $concatSql), ["%{$value}%"]);+ }+ });+ });++ return $query;+ }+$relationMethod = $boolean === 'or' ? 'orWhereHas' : 'whereHas';$query->{$relationMethod}($resolvedRelationKey, function (Builder $relationQuery) use ($resolvedRelationKey, $relationColumns, $value, $likeOperator, $operator) {@@ -593,9 +650,9 @@ trait Searchableif (in_array($filterKey, $searchableAttributes, true)) {$method = match (true) {$isNull && $boolean === 'or' => 'orWhereNull',- $isNull => 'whereNull',- $boolean === 'or' => 'orWhereNotNull',- default => 'whereNotNull',+ $isNull => 'whereNull',+ $boolean === 'or' => 'orWhereNotNull',+ default => 'whereNotNull',};$query->{$method}($table.'.'.$filterKey);@@ -941,6 +998,36 @@ trait Searchablereturn $this->searchableRelationAliases ?? [];}+ /**+ * Get structured-filter relation columns for a given filter key.+ *+ * By default, this uses all configured searchable relation columns for the+ * resolved relation key. Models can narrow specific advanced-search fields+ * via $searchableRelationFilterColumns, keyed by the incoming filter key+ * shown in the UI/API (for example: 'location' => ['name']).+ *+ * @param array<string, array<int, string>> $searchableRelations+ * @return array<int, string>+ */+ private function getStructuredFilterRelationColumns(string $filterKey, string $resolvedRelationKey, array $searchableRelations): array+ {+ $defaultColumns = (array) ($searchableRelations[$resolvedRelationKey] ?? []);++ $overrides = $this->searchableRelationFilterColumns ?? [];++ if (! array_key_exists($filterKey, $overrides)) {+ return $defaultColumns;+ }++ $overrideColumns = array_values(array_filter((array) $overrides[$filterKey], 'is_string'));++ // Keep only columns that are actually searchable on the resolved relation,+ // so model-level overrides cannot accidentally reference unknown columns.+ $validColumns = array_values(array_intersect($overrideColumns, $defaultColumns));++ return $validColumns !== [] ? $validColumns : $defaultColumns;+ }+/*** Get the table name of a relation.*@@ -998,6 +1085,9 @@ trait Searchable*/private function buildMultipleColumnSearch(array $columns): string{+ // This method deliberately returns only an SQL fragment ending with "LIKE ?"+ // so callers can reuse it and swap operators (NOT LIKE / =) without duplicating+ // driver-specific CONCAT syntax.$mappedColumns = collect($columns)->map(fn ($column) => DB::getTablePrefix().$column)->toArray();$driver = config('database.connections.'.config('database.default').'.driver');diff --git a/tests/Feature/Search/SearchableTraitTest.php b/tests/Feature/Search/SearchableTraitTest.phpindex 0d58ed7f6b..5a5962dfd2 100644--- a/tests/Feature/Search/SearchableTraitTest.php+++ b/tests/Feature/Search/SearchableTraitTest.php@@ -357,7 +357,7 @@ class SearchableTraitTest extends TestCasepublic function test_user_name_virtual_column_filter_negation_bang_prefix(){$ts = now()->timestamp;- $negUser = User::factory()->create(['first_name' => 'NegFirst'.$ts, 'last_name' => 'NegLast'.$ts]);+ $negUser = User::factory()->create(['first_name' => 'NegFirst'.$ts, 'last_name' => 'NegLast'.$ts]);$safeUser = User::factory()->create(['first_name' => 'SafeFirst'.$ts, 'last_name' => 'SafeLast'.$ts]);$response = $this->actingAsForApi(User::factory()->superuser()->create())@@ -763,7 +763,7 @@ class SearchableTraitTest extends TestCase{$ts = now()->timestamp;- $withNotes = Asset::factory()->create(['notes' => 'Some notes '.$ts]);+ $withNotes = Asset::factory()->create(['notes' => 'Some notes '.$ts]);$withoutNotes = Asset::factory()->create(['notes' => null]);$superuser = User::factory()->viewAssets()->create();@@ -800,7 +800,7 @@ class SearchableTraitTest extends TestCase$userWithName = User::factory()->create(['first_name' => 'VirtNullFirst'.$ts,- 'last_name' => 'VirtNullLast'.$ts,+ 'last_name' => 'VirtNullLast'.$ts,]);$superuser = User::factory()->superuser()->create();@@ -828,8 +828,8 @@ class SearchableTraitTest extends TestCase{$ts = now()->timestamp;- $supplier = \App\Models\Supplier::factory()->create(['name' => 'RelNullSupplier'.$ts]);- $withSupplier = Asset::factory()->create(['supplier_id' => $supplier->id]);+ $supplier = Supplier::factory()->create(['name' => 'RelNullSupplier'.$ts]);+ $withSupplier = Asset::factory()->create(['supplier_id' => $supplier->id]);$withoutSupplier = Asset::factory()->create(['supplier_id' => null]);$superuser = User::factory()->viewAssets()->create();@@ -885,7 +885,7 @@ class SearchableTraitTest extends TestCase{$ts = now()->timestamp;- $exact = Asset::factory()->create(['notes' => 'ExactNote'.$ts]);+ $exact = Asset::factory()->create(['notes' => 'ExactNote'.$ts]);$partial = Asset::factory()->create(['notes' => 'ExactNote'.$ts.'SomeSuffix']);Asset::factory()->create(['notes' => 'Unrelated'.$ts]);@@ -910,10 +910,10 @@ class SearchableTraitTest extends TestCase{$ts = now()->timestamp;- $exactSupplier = \App\Models\Supplier::factory()->create(['name' => 'ExactSupplier'.$ts]);- $partialSupplier = \App\Models\Supplier::factory()->create(['name' => 'ExactSupplier'.$ts.'Extra']);+ $exactSupplier = Supplier::factory()->create(['name' => 'ExactSupplier'.$ts]);+ $partialSupplier = Supplier::factory()->create(['name' => 'ExactSupplier'.$ts.'Extra']);- $exactAsset = Asset::factory()->create(['supplier_id' => $exactSupplier->id]);+ $exactAsset = Asset::factory()->create(['supplier_id' => $exactSupplier->id]);$partialAsset = Asset::factory()->create(['supplier_id' => $partialSupplier->id]);$superuser = User::factory()->viewAssets()->create();@@ -938,7 +938,7 @@ class SearchableTraitTest extends TestCase{$ts = now()->timestamp;- $exactUser = User::factory()->create(['first_name' => 'John'.$ts, 'last_name' => 'Smith'.$ts]);+ $exactUser = User::factory()->create(['first_name' => 'John'.$ts, 'last_name' => 'Smith'.$ts]);$partialUser = User::factory()->create(['first_name' => 'John'.$ts, 'last_name' => 'Smithson'.$ts]);$response = $this->actingAsForApi(User::factory()->superuser()->create())@@ -959,7 +959,7 @@ class SearchableTraitTest extends TestCase*/public function test_is_null_tokens_still_work_after_exact_match_addition(){- $withNotes = Asset::factory()->create(['notes' => 'SomeValue'.now()->timestamp]);+ $withNotes = Asset::factory()->create(['notes' => 'SomeValue'.now()->timestamp]);$withoutNotes = Asset::factory()->create(['notes' => null]);$superuser = User::factory()->viewAssets()->create();@@ -1076,4 +1076,73 @@ class SearchableTraitTest extends TestCase->assertOk()->assertJson(fn (AssertableJson $json) => $json->has('rows', 1)->etc());}++ /**+ * Negation filter "!blah" on the "location" relation key for Assets+ * should exclude assets with a location name containing "blah".+ */+ public function test_negation_filter_on_asset_location_relation()+ {+ $ts = now()->timestamp;++ $blahLocation = Location::factory()->create(['name' => 'Blah Office '.$ts]);+ $safeLocation = Location::factory()->create(['name' => 'Safe Office '.$ts]);++ $blahAsset = Asset::factory()->create(['location_id' => $blahLocation->id]);+ $safeAsset = Asset::factory()->create(['location_id' => $safeLocation->id]);++ $response = $this->actingAsForApi(User::factory()->viewAssets()->create())+ ->getJson(route('api.assets.index', [+ 'filter' => json_encode(['location' => '!Blah']),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ // Asset in the "blah" location must NOT appear.+ $this->assertNotContains((int) $blahAsset->id, $returnedIds);+ // Asset in a different location MUST appear.+ $this->assertContains((int) $safeAsset->id, $returnedIds);+ }++ /**+ * Negation filter "!blah" on the "location" relation key for Users+ * should exclude users whose location name contains "blah".+ *+ * The User model stores location via the "userloc" Eloquent relation+ * (not "location"), so a "location" → "userloc" alias must be registered.+ */+ public function test_negation_filter_on_user_location_relation()+ {+ $ts = now()->timestamp;++ $blahLocation = Location::factory()->create([+ 'name' => 'Blah Floor '.$ts,+ 'address' => 'Safe Address '.$ts,+ ]);+ $safeLocation = Location::factory()->create([+ 'name' => 'Safe Floor '.$ts,+ // Regression guard: structured filter on "location" should not inspect address.+ 'address' => 'Blah Address '.$ts,+ ]);++ $blahUser = User::factory()->create(['location_id' => $blahLocation->id]);+ $safeUser = User::factory()->create(['location_id' => $safeLocation->id]);+ $nullLocationUser = User::factory()->create(['location_id' => null]);++ $response = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.users.index', [+ 'filter' => json_encode(['location' => '!Blah']),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ // The user in the "blah" location must NOT appear.+ $this->assertNotContains((int) $blahUser->id, $returnedIds);+ // The user in a safe location MUST appear.+ $this->assertContains((int) $safeUser->id, $returnedIds);+ // Users with no location should also be included for negated filters.+ $this->assertContains((int) $nullLocationUser->id, $returnedIds);+ }}