A free open source IT asset/license management system
Added more filter options
snipe9131dbf09b24
diff --git a/app/Models/Traits/Searchable.php b/app/Models/Traits/Searchable.phpindex 69296ba775..89e6ed96a2 100644--- a/app/Models/Traits/Searchable.php+++ b/app/Models/Traits/Searchable.php@@ -207,28 +207,50 @@ trait Searchable}/**- * Parse a raw filter value for an optional negation prefix.+ * Parse a raw filter value for an optional negation, null-check, or exact-match prefix.*- * Supported negation syntax (case-insensitive prefix):- * - "!flarb" → negate = true, value = "flarb"- * - "not:flarb" → negate = true, value = "flarb"+ * Supported syntax:+ * - "!flarb" → operator = not_like, value = "flarb"+ * - "not:flarb" → operator = not_like, value = "flarb"+ * - "is:null" → operator = is_null, value = "" (reserved token)+ * - "is:not_null" → operator = is_not_null, value = "" (reserved token)+ * - "is:flarb" → operator = exact, value = "flarb" (exact equality)*- * Used by applySingleSearchFilter so callers can pass values like- * {"gleeb": "!flarb"} or {"gleeb": "not:flarb"} in the filter JSON.+ * `is:null` and `is:not_null` are checked before the generic `is:` prefix so they always+ * resolve to their dedicated null-check operators regardless of casing.*- * @return array{value: string, negate: bool}+ * The legacy `negate` boolean is preserved alongside `operator` so that+ * existing callers that only check `negate` still work correctly.+ *+ * @return array{value: string, negate: bool, operator: string}*/private function parseFilterValue(string $raw): array{+ $lower = strtolower($raw);++ if ($lower === 'is:null') {+ return ['value' => '', 'negate' => false, 'operator' => 'is_null'];+ }++ if ($lower === 'is:not_null') {+ return ['value' => '', 'negate' => false, 'operator' => 'is_not_null'];+ }++ if (str_starts_with($lower, 'is:')) {+ $exactValue = substr($raw, 3);++ return ['value' => $exactValue, 'negate' => false, 'operator' => 'exact'];+ }+if (str_starts_with($raw, '!')) {- return ['value' => substr($raw, 1), 'negate' => true];+ return ['value' => substr($raw, 1), 'negate' => true, 'operator' => 'not_like'];}- if (str_starts_with(strtolower($raw), 'not:')) {- return ['value' => substr($raw, 4), 'negate' => true];+ if (str_starts_with($lower, 'not:')) {+ return ['value' => substr($raw, 4), 'negate' => true, 'operator' => 'not_like'];}- return ['value' => $raw, 'negate' => false];+ return ['value' => $raw, 'negate' => false, 'operator' => 'like'];}/**@@ -248,6 +270,13 @@ trait Searchable$parsed = $this->parseFilterValue($filterValue);$value = $parsed['value'];$negate = $parsed['negate'];+ $operator = $parsed['operator'];++ // IS NULL / IS NOT NULL are handled before value-based filtering,+ // because there is no meaningful value to pass to LIKE for them.+ if ($operator === 'is_null' || $operator === 'is_not_null') {+ return $this->applyNullFilter($query, $filterKey, $operator === 'is_null', $boolean);+ }// Skip gracefully if stripping the prefix leaves an empty value.if ($value === '') {@@ -262,7 +291,42 @@ trait Searchable$likeOperator = $negate ? 'NOT LIKE' : 'LIKE';if (in_array($filterKey, $searchableAttributes, true)) {- $query->{$whereMethod}($table.'.'.$filterKey, $likeOperator, '%'.$value.'%');+ if ($operator === 'exact') {+ $query->{$whereMethod}($table.'.'.$filterKey, '=', $value);+ } else {+ $query->{$whereMethod}($table.'.'.$filterKey, $likeOperator, '%'.$value.'%');+ }++ return $query;+ }++ // Handle virtual columns — keys that are not real DB columns but map to a set+ // of real columns searched via CONCAT (e.g. "name" → first_name + last_name on User).+ $virtualColumns = $this->getSearchableVirtualColumns();++ if (array_key_exists($filterKey, $virtualColumns)) {+ $qualifiedColumns = array_map(+ fn ($col) => $table.'.'.$col,+ $virtualColumns[$filterKey]+ );++ if ($operator === 'exact') {+ // 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);+ $concatSql = str_replace(' LIKE ?', ' = ?', $concatSql);+ $rawMethod = $boolean === 'or' ? 'orWhereRaw' : 'whereRaw';+ $query->{$rawMethod}($concatSql, [$value]);+ } else {+ $concatSql = $this->buildMultipleColumnSearch($qualifiedColumns);++ if ($negate) {+ $concatSql = str_replace(' LIKE ?', ' NOT LIKE ?', $concatSql);+ }++ $rawMethod = $boolean === 'or' ? 'orWhereRaw' : 'whereRaw';+ $query->{$rawMethod}($concatSql, ['%'.$value.'%']);+ }return $query;}@@ -297,23 +361,33 @@ trait Searchable$relationColumns = (array) $searchableRelations[$resolvedRelationKey];$relationMethod = $boolean === 'or' ? 'orWhereHas' : 'whereHas';- $query->{$relationMethod}($resolvedRelationKey, function (Builder $relationQuery) use ($resolvedRelationKey, $relationColumns, $value, $likeOperator) {+ $query->{$relationMethod}($resolvedRelationKey, function (Builder $relationQuery) use ($resolvedRelationKey, $relationColumns, $value, $likeOperator, $operator) {$relationTable = $this->getRelationTable($resolvedRelationKey);$firstConditionAdded = false;foreach ($relationColumns as $relationColumn) {if (! $firstConditionAdded) {- $relationQuery->where($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%');+ if ($operator === 'exact') {+ $relationQuery->where($relationTable.'.'.$relationColumn, '=', $value);+ } else {+ $relationQuery->where($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%');+ }$firstConditionAdded = true;continue;}- // For negation we AND the NOT LIKE conditions so all columns must not match.- // For normal LIKE we OR them so any column matching is sufficient.- $likeOperator === 'NOT LIKE'- ? $relationQuery->where($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%')- : $relationQuery->orWhere($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%');+ if ($operator === 'exact') {+ // For exact matches across multiple columns, OR them — any column matching+ // the exact value is sufficient (e.g. name OR slug).+ $relationQuery->orWhere($relationTable.'.'.$relationColumn, '=', $value);+ } elseif ($likeOperator === 'NOT LIKE') {+ // For negation we AND the NOT LIKE conditions so all columns must not match.+ $relationQuery->where($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%');+ } else {+ // For normal LIKE we OR them so any column matching is sufficient.+ $relationQuery->orWhere($relationTable.'.'.$relationColumn, $likeOperator, '%'.$value.'%');+ }}if (($resolvedRelationKey === 'adminuser') || ($resolvedRelationKey === 'user')) {@@ -323,9 +397,14 @@ trait Searchable'users.display_name',]);- $likeOperator === 'NOT LIKE'- ? $relationQuery->whereRaw(str_replace('LIKE', 'NOT LIKE', $concatSql), ["%{$value}%"])- : $relationQuery->orWhereRaw($concatSql, ["%{$value}%"]);+ if ($operator === 'exact') {+ $concatSql = str_replace(' LIKE ?', ' = ?', $concatSql);+ $relationQuery->orWhereRaw($concatSql, [$value]);+ } elseif ($likeOperator === 'NOT LIKE') {+ $relationQuery->whereRaw(str_replace('LIKE', 'NOT LIKE', $concatSql), ["%{$value}%"]);+ } else {+ $relationQuery->orWhereRaw($concatSql, ["%{$value}%"]);+ }}});@@ -490,6 +569,85 @@ trait Searchablereturn $query->{$havingMethod}($countAlias, $likeOperator, '%'.$filterValue.'%');}+ /**+ * Apply an IS NULL / IS NOT NULL filter for the given filter key.+ *+ * Supported targets:+ *+ * Direct attributes → WHERE col IS [NOT] NULL+ *+ * Virtual columns → IS NULL: all constituent columns must be null+ * IS NOT NULL: at least one constituent column must not be null+ *+ * Relation keys → IS NULL: doesntHave (no related record)+ * IS NOT NULL: whereHas (has a related record)+ *+ * Any unrecognised key is silently ignored.+ */+ private function applyNullFilter(Builder $query, string $filterKey, bool $isNull, string $boolean = 'and'): Builder+ {+ $table = $this->getTable();+ $searchableAttributes = $this->getSearchableAttributes();++ // Direct attribute column.+ if (in_array($filterKey, $searchableAttributes, true)) {+ $method = match (true) {+ $isNull && $boolean === 'or' => 'orWhereNull',+ $isNull => 'whereNull',+ $boolean === 'or' => 'orWhereNotNull',+ default => 'whereNotNull',+ };++ $query->{$method}($table.'.'.$filterKey);++ return $query;+ }++ // Virtual columns (e.g. 'name' → ['first_name', 'last_name'] on User).+ $virtualColumns = $this->getSearchableVirtualColumns();++ if (array_key_exists($filterKey, $virtualColumns)) {+ $qualifiedColumns = array_map(+ fn ($col) => $table.'.'.$col,+ $virtualColumns[$filterKey]+ );++ if ($isNull) {+ // All constituent columns must be null (= no name at all).+ foreach ($qualifiedColumns as $col) {+ $query->whereNull($col);+ }+ } else {+ // At least one constituent column must have a value.+ $query->where(function (Builder $sub) use ($qualifiedColumns): void {+ foreach ($qualifiedColumns as $col) {+ $sub->orWhereNotNull($col);+ }+ });+ }++ return $query;+ }++ // Relation key: no related record = "null", has a related record = "not null".+ $searchableRelations = $this->getSearchableRelations();+ $resolvedRelationKey = $this->resolveSearchableRelationKey($filterKey, $searchableRelations);++ if ($resolvedRelationKey !== null && ! $this->isAssignedToRelationKey($resolvedRelationKey)) {+ if ($isNull) {+ $method = $boolean === 'or' ? 'orDoesntHave' : 'doesntHave';+ $query->{$method}($resolvedRelationKey);+ } else {+ $method = $boolean === 'or' ? 'orWhereHas' : 'whereHas';+ $query->{$method}($resolvedRelationKey);+ }++ return $query;+ }++ return $query;+ }+/*** Searches the models attributes for the search terms*@@ -750,6 +908,20 @@ trait Searchablereturn $this->searchableCounts ?? [];}+ /**+ * Get virtual column aliases defined on the model.+ *+ * These are filter keys that map to a set of real columns searched via+ * CONCAT — for example, "name" → ['first_name', 'last_name'] on User,+ * because "name" is not a real database column on that table.+ *+ * @return array<string, list<string>>+ */+ private function getSearchableVirtualColumns(): array+ {+ return $this->searchableVirtualColumns ?? [];+ }+/*** Get the relation aliases defined on the model.*diff --git a/app/Models/User.php b/app/Models/User.phpindex fe1062da3b..379819f084 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -181,6 +181,20 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo'manages_locations_count',];+ /**+ * Virtual column aliases that map a single filter key to a set of real columns+ * searched via CONCAT (SQL) so that, for example, filtering by "name" searches+ * across both first_name and last_name together.+ *+ * Because "name" is not a real column on the users table we cannot add it to+ * $searchableAttributes; this map bridges that gap for structured filter queries.+ *+ * @var array<string, list<string>>+ */+ protected $searchableVirtualColumns = [+ 'name' => ['first_name', 'last_name'],+ ];+/*** This sets the name property on the user. It's not a real field in the database* (since we use first_name and last_name), but the Laravel mailable methoddiff --git a/tests/Feature/Search/SearchableTraitTest.php b/tests/Feature/Search/SearchableTraitTest.phpindex 3f9c6171f1..0d58ed7f6b 100644--- a/tests/Feature/Search/SearchableTraitTest.php+++ b/tests/Feature/Search/SearchableTraitTest.php@@ -332,6 +332,71 @@ class SearchableTraitTest extends TestCase->assertJson(fn (AssertableJson $json) => $json->has('rows', 1)->etc());}+ /**+ * "name" is a virtual column on User (CONCAT of first_name + last_name).+ * A positive filter should match on concatenated full name.+ */+ public function test_user_name_virtual_column_filter_positive()+ {+ $ts = now()->timestamp;+ User::factory()->create(['first_name' => 'VirtFirst'.$ts, 'last_name' => 'VirtLast'.$ts]);+ User::factory()->create(['first_name' => 'Other'.$ts, 'last_name' => 'Person'.$ts]);++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.users.index', [+ 'filter' => json_encode(['name' => 'VirtFirst'.$ts]),+ ]))+ ->assertOk()+ ->assertJson(fn (AssertableJson $json) => $json->has('rows', 1)->etc());+ }++ /**+ * A negated "name" filter using the "!" prefix should exclude matching users,+ * returning only those whose full name does NOT contain the term.+ */+ public 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]);+ $safeUser = User::factory()->create(['first_name' => 'SafeFirst'.$ts, 'last_name' => 'SafeLast'.$ts]);++ $response = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.users.index', [+ 'filter' => json_encode(['name' => '!NegFirst'.$ts]),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ // The matched (negated) user must not appear in results.+ $this->assertNotContains((int) $negUser->id, $returnedIds);++ // The safe user should appear in results.+ $this->assertContains((int) $safeUser->id, $returnedIds);+ }++ /**+ * A negated "name" filter using the "not:" prefix should behave identically to "!".+ */+ public function test_user_name_virtual_column_filter_negation_not_colon_prefix()+ {+ $ts = now()->timestamp;+ User::factory()->create(['first_name' => 'NotFirst'.$ts, 'last_name' => 'NotLast'.$ts]);++ $response = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.users.index', [+ 'filter' => json_encode(['name' => 'not:NotFirst'.$ts]),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertNotContains(+ (int) User::where('first_name', 'NotFirst'.$ts)->value('id'),+ $returnedIds+ );+ }+/*** Test Category free-text search on attributes*/@@ -690,6 +755,106 @@ class SearchableTraitTest extends TestCase->assertJson(fn (AssertableJson $json) => $json->has('rows', 0)->etc());}+ /**+ * "is:null" on a direct nullable attribute should match rows where that column is NULL.+ * "is:not_null" should match rows where it is not NULL.+ */+ public function test_is_null_filter_on_nullable_attribute()+ {+ $ts = now()->timestamp;++ $withNotes = Asset::factory()->create(['notes' => 'Some notes '.$ts]);+ $withoutNotes = Asset::factory()->create(['notes' => null]);++ $superuser = User::factory()->viewAssets()->create();++ // is:null → only the asset with no notes+ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['notes' => 'is:null'])]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $withoutNotes->id, $returnedIds);+ $this->assertNotContains((int) $withNotes->id, $returnedIds);++ // is:not_null → only the asset with notes+ $response2 = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['notes' => 'is:not_null'])]))+ ->assertOk();++ $returnedIds2 = collect($response2->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $withNotes->id, $returnedIds2);+ $this->assertNotContains((int) $withoutNotes->id, $returnedIds2);+ }++ /**+ * "is:not_null" on the User virtual "name" column should match users where+ * at least one constituent column (first_name, last_name) is not null.+ * All factory-created users have a first_name, so they should all appear.+ */+ public function test_is_null_filter_on_virtual_name_column()+ {+ $ts = now()->timestamp;++ $userWithName = User::factory()->create([+ 'first_name' => 'VirtNullFirst'.$ts,+ 'last_name' => 'VirtNullLast'.$ts,+ ]);++ $superuser = User::factory()->superuser()->create();++ // is:not_null → users with at least first_name set should be returned.+ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.users.index', ['filter' => json_encode(['name' => 'is:not_null'])]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ // The user with an actual name must appear.+ $this->assertContains((int) $userWithName->id, $returnedIds);++ // The acting superuser itself also has a name, so it should appear too.+ $this->assertContains((int) $superuser->id, $returnedIds);+ }++ /**+ * "is:null" on a searchable relation key should return records that have no+ * related record (equivalent to doesntHave).+ * "is:not_null" should return only records that have a related record.+ */+ public function test_is_null_filter_on_relation_key()+ {+ $ts = now()->timestamp;++ $supplier = \App\Models\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();++ // is:null on supplier → assets with no supplier+ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['supplier' => 'is:null'])]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $withoutSupplier->id, $returnedIds);+ $this->assertNotContains((int) $withSupplier->id, $returnedIds);++ // is:not_null on supplier → assets with a supplier+ $response2 = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['supplier' => 'is:not_null'])]))+ ->assertOk();++ $returnedIds2 = collect($response2->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $withSupplier->id, $returnedIds2);+ $this->assertNotContains((int) $withoutSupplier->id, $returnedIds2);+ }+/*** Test custom field partial match via filter.*/@@ -712,6 +877,104 @@ class SearchableTraitTest extends TestCase->assertJson(fn (AssertableJson $json) => $json->has('rows', 1)->etc());}+ /**+ * "is:{value}" on a direct attribute should match records where the column equals+ * the value exactly — no partial/wildcard matching.+ */+ public function test_exact_match_filter_on_direct_attribute()+ {+ $ts = now()->timestamp;++ $exact = Asset::factory()->create(['notes' => 'ExactNote'.$ts]);+ $partial = Asset::factory()->create(['notes' => 'ExactNote'.$ts.'SomeSuffix']);+ Asset::factory()->create(['notes' => 'Unrelated'.$ts]);++ $superuser = User::factory()->viewAssets()->create();++ // is:ExactNote{ts} should only return the exact match, not the partial one.+ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['notes' => 'is:ExactNote'.$ts])]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $exact->id, $returnedIds);+ $this->assertNotContains((int) $partial->id, $returnedIds);+ }++ /**+ * "is:{value}" on a relation key should match records where the related model's+ * column equals the value exactly.+ */+ public function test_exact_match_filter_on_relation()+ {+ $ts = now()->timestamp;++ $exactSupplier = \App\Models\Supplier::factory()->create(['name' => 'ExactSupplier'.$ts]);+ $partialSupplier = \App\Models\Supplier::factory()->create(['name' => 'ExactSupplier'.$ts.'Extra']);++ $exactAsset = Asset::factory()->create(['supplier_id' => $exactSupplier->id]);+ $partialAsset = Asset::factory()->create(['supplier_id' => $partialSupplier->id]);++ $superuser = User::factory()->viewAssets()->create();++ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', [+ 'filter' => json_encode(['supplier' => 'is:ExactSupplier'.$ts]),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $exactAsset->id, $returnedIds);+ $this->assertNotContains((int) $partialAsset->id, $returnedIds);+ }++ /**+ * "is:{value}" on the User virtual "name" column should match only users whose+ * CONCAT(first_name, ' ', last_name) equals the value exactly.+ */+ public function test_exact_match_filter_on_virtual_name_column()+ {+ $ts = now()->timestamp;++ $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())+ ->getJson(route('api.users.index', [+ 'filter' => json_encode(['name' => 'is:John'.$ts.' Smith'.$ts]),+ ]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $exactUser->id, $returnedIds);+ $this->assertNotContains((int) $partialUser->id, $returnedIds);+ }++ /**+ * Confirm that the reserved "is:null" and "is:not_null" tokens are still honoured+ * as null checks even after adding generic "is:{value}" exact-match support.+ */+ public function test_is_null_tokens_still_work_after_exact_match_addition()+ {+ $withNotes = Asset::factory()->create(['notes' => 'SomeValue'.now()->timestamp]);+ $withoutNotes = Asset::factory()->create(['notes' => null]);++ $superuser = User::factory()->viewAssets()->create();++ // is:null should still mean IS NULL, not exact match on the string "null".+ $response = $this->actingAsForApi($superuser)+ ->getJson(route('api.assets.index', ['filter' => json_encode(['notes' => 'is:null'])]))+ ->assertOk();++ $returnedIds = collect($response->json('rows'))->pluck('id')->map(fn ($id) => (int) $id)->all();++ $this->assertContains((int) $withoutNotes->id, $returnedIds);+ $this->assertNotContains((int) $withNotes->id, $returnedIds);+ }+/*** Test negation filter using "!" prefix on a direct attribute.* filter={"name":"!Dell"} should return all assets whose name does NOT contain "Dell".