A free open source IT asset/license management system
Locations/Company: Always include parent in dropdown results
snipe425a3767b636
diff --git a/app/Http/Controllers/Api/LocationsController.php b/app/Http/Controllers/Api/LocationsController.phpindex 056867460a..9c18bf4abb 100644--- a/app/Http/Controllers/Api/LocationsController.php+++ b/app/Http/Controllers/Api/LocationsController.php@@ -499,6 +499,23 @@ class LocationsController extends Controller}if ($request->filled('search')) {+ // Search results are cherry-picked out of the tree so the+ // pre-search Location::indenter walk cannot be reused as-is.+ // Instead, walk each match's parent chain and inline the+ // ancestors with the same `›` breadcrumb separator that+ // Location::indenter uses on the tree-order branch, so both+ // views share one visual style: `DC1 › Rack 1` distinguishes+ // Rack 1 under DC1 from Rack 1 under DC2.+ $locations->load('parent');+ foreach ($locations as $location) {+ $chain = [$location->name];+ $ancestor = $location->parent;+ while ($ancestor) {+ array_unshift($chain, $ancestor->name);+ $ancestor = $ancestor->parent;+ }+ $location->use_text = implode(' › ', $chain);+ }$locations_formatted = $locations;} else {$location_options = Location::indenter($locations_with_children);diff --git a/app/Http/Traits/UniqueUndeletedTrait.php b/app/Http/Traits/UniqueUndeletedTrait.phpindex c6b7765a40..b8c95f9353 100644--- a/app/Http/Traits/UniqueUndeletedTrait.php+++ b/app/Http/Traits/UniqueUndeletedTrait.php@@ -20,4 +20,26 @@ trait UniqueUndeletedTraitreturn 'unique_undeleted:'.$this->table.',0';}++ /**+ * Prepare a `unique_undeleted_in_scope` rule.+ *+ * Model declares: `'name' => 'unique_undeleted_in_scope:parent_id,company_id'`+ * We rewrite to: `'name' => 'unique_undeleted_in_scope:locations,42,parent_id,company_id'`+ *+ * The rule closure in ValidationServiceProvider reads the current+ * request/model value of each scope column via `$validator->getData()`,+ * so a new location named "Rack 1" under DC1 is compared only against+ * other locations whose parent_id (and company_id) match, not+ * globally as `unique_undeleted` does.+ *+ * @param array $parameters the scope column names declared on the model+ * @param string $field the attribute being validated+ */+ protected function prepareUniqueUndeletedInScopeRule($parameters, $field)+ {+ $id = $this->exists ? $this->getKey() : 0;++ return 'unique_undeleted_in_scope:'.$this->table.','.$id.','.implode(',', $parameters);+ }}diff --git a/app/Models/Company.php b/app/Models/Company.phpindex 1356594a75..97bad3a238 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -38,7 +38,7 @@ final class Company extends SnipeModel// Declare the rules for the model validationprotected $rules = [- 'name' => 'required|max:255|unique_undeleted',+ 'name' => 'required|max:255|unique_undeleted_in_scope:parent_id','fax' => 'min:7|max:35|nullable','phone' => 'min:7|max:35|nullable','email' => 'email|max:150|nullable',@@ -229,8 +229,10 @@ final class Company extends SnipeModel* level". Using 0 (not null) avoids PHP 8.4's deprecation of null array* offsets when callers build the map from `$company->parent_id`.*- * Mirrors Location::indenter so the SelectlistTransformer renders the same- * "-- Child Co" indentation it already does for locations.+ * `$prefix` is the accumulated breadcrumb path of the current node's+ * ancestors. Mirrors Location::indenter so both dropdowns share the same+ * `Parent › Child` visual style, unified with the parent-chain+ * breadcrumb rendered by the location info-panel.*/public static function indenter(array $companies_by_parent, int $parent_id = 0, string $prefix = ''): array{@@ -241,7 +243,11 @@ final class Company extends SnipeModel}foreach ($companies_by_parent[$parent_id] as $company) {- $company->use_text = trim($prefix.' '.$company->name);+ $breadcrumb = $prefix === ''+ ? $company->name+ : $prefix.' › '.$company->name;++ $company->use_text = $breadcrumb;$company->use_image = ($company->image)? Storage::disk('public')->url('companies/'.$company->image): null;@@ -250,7 +256,7 @@ final class Company extends SnipeModelif (array_key_exists($company->id, $companies_by_parent)) {$results = array_merge($results,- self::indenter($companies_by_parent, $company->id, $prefix.'--'),+ self::indenter($companies_by_parent, $company->id, $breadcrumb),);}}diff --git a/app/Models/Location.php b/app/Models/Location.phpindex e4507cc110..22fa805c60 100755--- a/app/Models/Location.php+++ b/app/Models/Location.php@@ -34,7 +34,7 @@ class Location extends SnipeModelprotected $table = 'locations';protected $rules = [- 'name' => 'required|max:255|unique_undeleted',+ 'name' => 'required|max:255|unique_undeleted_in_scope:parent_id,company_id','address' => 'max:191|nullable','address2' => 'max:191|nullable','city' => 'max:191|nullable',@@ -373,6 +373,14 @@ class Location extends SnipeModel* The map's keys are parent_id values, with `0` used for "no parent / top-* level". Using 0 (not null) avoids PHP 8.4's deprecation of null array* offsets when callers build the map from `$location->parent_id`.+ *+ * `$prefix` is the accumulated breadcrumb path of the current node's+ * ancestors. Empty at the top-level call, then each recursion passes down+ * the full parent chain so every entry's `use_text` shows the whole path+ * (e.g. `DC1 › Rack 1 › Rack 1a`) rather than just an indent-depth marker.+ * The `›` separator matches the parent-chain breadcrumb rendered in the+ * location info-panel at resources/views/blade/info-panel/index.blade.php+ * so the select2 dropdown and the info-panel display are visually unified.*/public static function indenter($locations_with_children, int $parent_id = 0, $prefix = ''){@@ -383,12 +391,15 @@ class Location extends SnipeModel}foreach ($locations_with_children[$parent_id] as $location) {- $location->use_text = $prefix.' '.$location->name;+ $breadcrumb = $prefix === ''+ ? $location->name+ : $prefix.' › '.$location->name;++ $location->use_text = $breadcrumb;$location->use_image = ($location->image) ? Storage::disk('public')->url('locations/'.$location->image) : null;$results[] = $location;- // now append the children. (if we have any)if (array_key_exists($location->id, $locations_with_children)) {- $results = array_merge($results, self::indenter($locations_with_children, $location->id, $prefix.'--'));+ $results = array_merge($results, self::indenter($locations_with_children, $location->id, $breadcrumb));}}diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.phpindex ba699ab1ca..d1b87bfbc5 100644--- a/app/Providers/ValidationServiceProvider.php+++ b/app/Providers/ValidationServiceProvider.php@@ -111,6 +111,59 @@ class ValidationServiceProvider extends ServiceProvider->exists();});+ /**+ * Unique-if-undeleted, scoped to one or more sibling columns on the same row.+ *+ * Where `unique_undeleted` enforces global uniqueness on a column,+ * `unique_undeleted_in_scope` enforces uniqueness only within a bucket+ * defined by the values of one or more OTHER columns on the same row.+ * Used for tree-structured tables where a child name only needs to be+ * unique among its siblings, and (under FMCS) among its siblings in+ * the same company.+ *+ * NULL is treated as its own bucket per standard SQL semantics: two+ * top-level locations (parent_id IS NULL) named "HQ" collide with+ * each other, but "HQ" at the top level does not collide with "HQ"+ * that has a parent.+ *+ * $parameters[0] is the TABLE NAME being queried+ * $parameters[1] is the ID of the row being edited (0 for creates)+ * $parameters[2..N] are the sibling COLUMN NAMES that make up the scope+ *+ * The UniqueUndeletedTrait's prepareUniqueUndeletedInScopeRule method+ * prepends the table + id for you, so on the model you just declare:+ * 'name' => 'unique_undeleted_in_scope:parent_id,company_id'+ */+ Validator::extend('unique_undeleted_in_scope', function ($attribute, $value, $parameters, $validator) {+ if (count($parameters) < 2) {+ return true;+ }++ $table = $parameters[0];+ $ignoreId = (int) $parameters[1];+ $scopeColumns = array_slice($parameters, 2);+ $data = $validator->getData();++ $query = DB::table($table)+ ->whereNull('deleted_at')+ ->where($attribute, '=', $value);++ if ($ignoreId > 0) {+ $query->where('id', '!=', $ignoreId);+ }++ foreach ($scopeColumns as $column) {+ $scopeValue = $data[$column] ?? null;+ if ($scopeValue === null || $scopeValue === '') {+ $query->whereNull($column);+ } else {+ $query->where($column, '=', $scopeValue);+ }+ }++ return $query->count() < 1;+ });+/*** Unique if undeleted for two columns*diff --git a/tests/Feature/Companies/Api/CompanyHierarchyTest.php b/tests/Feature/Companies/Api/CompanyHierarchyTest.phpindex d94317793a..703709af34 100644--- a/tests/Feature/Companies/Api/CompanyHierarchyTest.php+++ b/tests/Feature/Companies/Api/CompanyHierarchyTest.php@@ -360,11 +360,13 @@ class CompanyHierarchyTest extends TestCase$byId = collect($response['results'])->keyBy('id');- // Parents render with no indent prefix, children render with the "-- " prefix.+ // Parents render as their own name, children render with the+ // full breadcrumb path so hierarchy context is always visible.+ // Unified with Location::indenter and the info-panel breadcrumb.$this->assertEquals('AlphaParent', $byId[$alphaParent->id]['text']);- $this->assertEquals('-- AlphaChild', $byId[$alphaChild->id]['text']);+ $this->assertEquals('AlphaParent › AlphaChild', $byId[$alphaChild->id]['text']);$this->assertEquals('ZuluParent', $byId[$zuluParent->id]['text']);- $this->assertEquals('-- ZuluChild', $byId[$zuluChild->id]['text']);+ $this->assertEquals('ZuluParent › ZuluChild', $byId[$zuluChild->id]['text']);// Children appear directly after their own parent, not lumped at the end.$positions = collect($response['results'])->pluck('id')->flip();diff --git a/tests/Feature/Companies/CompanyNameUniquenessTest.php b/tests/Feature/Companies/CompanyNameUniquenessTest.phpnew file mode 100644index 0000000000..bb174ed5c4--- /dev/null+++ b/tests/Feature/Companies/CompanyNameUniquenessTest.php@@ -0,0 +1,56 @@+<?php++namespace Tests\Feature\Companies;++use App\Models\Company;+use Tests\TestCase;++/**+ * Company::name switched from global `unique_undeleted` to+ * `unique_undeleted_in_scope:parent_id` so a "West" sub-company under+ * two different parent companies can coexist.+ */+class CompanyNameUniquenessTest extends TestCase+{+ public function test_two_child_companies_with_the_same_name_under_different_parents_can_coexist(): void+ {+ $alpha = Company::factory()->create(['name' => 'AlphaCorp']);+ $bravo = Company::factory()->create(['name' => 'BravoCorp']);++ Company::factory()->create(['name' => 'West', 'parent_id' => $alpha->id]);+ $westUnderBravo = Company::factory()->create(['name' => 'West', 'parent_id' => $bravo->id]);++ $this->assertTrue($westUnderBravo->exists);+ $this->assertDatabaseCount('companies', 4);+ }++ public function test_two_child_companies_with_the_same_name_under_the_same_parent_still_collide(): void+ {+ $alpha = Company::factory()->create(['name' => 'AlphaCorp']);+ Company::factory()->create(['name' => 'West', 'parent_id' => $alpha->id]);++ $duplicate = new Company(['name' => 'West', 'parent_id' => $alpha->id]);++ $this->assertFalse($duplicate->save(), 'sibling company name collision should still be rejected');+ $this->assertNotEmpty($duplicate->getErrors()->get('name'));+ }++ public function test_two_top_level_companies_with_the_same_name_still_collide(): void+ {+ Company::factory()->create(['name' => 'AcmeGlobal', 'parent_id' => null]);++ $duplicate = new Company(['name' => 'AcmeGlobal', 'parent_id' => null]);++ $this->assertFalse($duplicate->save(), 'two top-level companies sharing a name should still be rejected');+ }++ public function test_top_level_and_child_can_share_a_name(): void+ {+ $parent = Company::factory()->create(['name' => 'ParentCorp']);+ $topLevel = Company::factory()->create(['name' => 'Sub', 'parent_id' => null]);+ $child = Company::factory()->create(['name' => 'Sub', 'parent_id' => $parent->id]);++ $this->assertTrue($topLevel->exists);+ $this->assertTrue($child->exists);+ }+}diff --git a/tests/Feature/Locations/Api/LocationsForSelectListTest.php b/tests/Feature/Locations/Api/LocationsForSelectListTest.phpindex 05a04f62a8..a7a2ad66a5 100644--- a/tests/Feature/Locations/Api/LocationsForSelectListTest.php+++ b/tests/Feature/Locations/Api/LocationsForSelectListTest.php@@ -55,4 +55,55 @@ class LocationsForSelectListTest extends TestCase->getJson(route('api.locations.selectlist'))->assertOk();}++ public function test_search_result_shows_parent_chain_in_breadcrumb(): void+ {+ // Two data centers each with their own rack. Location::name is+ // `unique_undeleted` today so two children literally named+ // "Rack 1" cannot coexist, but the disambiguation the breadcrumb+ // provides is still valuable whenever the child names share a+ // prefix or the tree is deep.+ $dc1 = Location::factory()->create(['name' => 'DC1']);+ $dc2 = Location::factory()->create(['name' => 'DC2']);+ Location::factory()->create(['name' => 'RackA', 'parent_id' => $dc1->id]);+ Location::factory()->create(['name' => 'RackB', 'parent_id' => $dc2->id]);++ $response = $this->actingAsForApi(User::factory()->createUsers()->create())+ ->getJson(route('api.locations.selectlist', ['search' => 'Rack']))+ ->assertOk();++ $texts = collect($response->json('results'))->pluck('text');+ $this->assertTrue($texts->contains('DC1 › RackA'));+ $this->assertTrue($texts->contains('DC2 › RackB'));+ }++ public function test_search_result_walks_multiple_ancestor_levels(): void+ {+ // Deeper tree: HQ > DC1 > Rack 1. The chain should show every+ // ancestor level.+ $hq = Location::factory()->create(['name' => 'HQ']);+ $dc1 = Location::factory()->create(['name' => 'DC1', 'parent_id' => $hq->id]);+ Location::factory()->create(['name' => 'Rack 1', 'parent_id' => $dc1->id]);++ $response = $this->actingAsForApi(User::factory()->createUsers()->create())+ ->getJson(route('api.locations.selectlist', ['search' => 'Rack 1']))+ ->assertOk();++ $texts = collect($response->json('results'))->pluck('text');+ $this->assertTrue($texts->contains('HQ › DC1 › Rack 1'));+ }++ public function test_search_result_for_top_level_location_has_no_prefix(): void+ {+ // A match at the top of the tree has no ancestors, so its text+ // should be just its own name with no leading breadcrumb.+ Location::factory()->create(['name' => 'Standalone Site']);++ $response = $this->actingAsForApi(User::factory()->createUsers()->create())+ ->getJson(route('api.locations.selectlist', ['search' => 'Standalone']))+ ->assertOk();++ $texts = collect($response->json('results'))->pluck('text');+ $this->assertTrue($texts->contains('Standalone Site'));+ }}diff --git a/tests/Feature/Locations/Ui/LocationNameUniquenessTest.php b/tests/Feature/Locations/Ui/LocationNameUniquenessTest.phpnew file mode 100644index 0000000000..8c205e8144--- /dev/null+++ b/tests/Feature/Locations/Ui/LocationNameUniquenessTest.php@@ -0,0 +1,94 @@+<?php++namespace Tests\Feature\Locations\Ui;++use App\Models\Company;+use App\Models\Location;+use Tests\TestCase;++/**+ * Location::name used to enforce global uniqueness via `unique_undeleted`.+ * That blocked reasonable structures like `DC1 / Rack 1` and `DC2 / Rack 1`+ * as siblings under different parents. `unique_undeleted_in_scope` scopes+ * uniqueness to `(name, parent_id, company_id)` so children only need to+ * be unique among their own siblings within their own company.+ */+class LocationNameUniquenessTest extends TestCase+{+ public function test_two_children_with_the_same_name_under_different_parents_can_coexist(): void+ {+ $dc1 = Location::factory()->create(['name' => 'DC1', 'company_id' => null]);+ $dc2 = Location::factory()->create(['name' => 'DC2', 'company_id' => null]);++ Location::factory()->create(['name' => 'Rack 1', 'parent_id' => $dc1->id, 'company_id' => null]);+ $rackUnderDc2 = Location::factory()->create(['name' => 'Rack 1', 'parent_id' => $dc2->id, 'company_id' => null]);++ $this->assertTrue($rackUnderDc2->exists);+ $this->assertDatabaseCount('locations', 4);+ }++ public function test_two_children_with_the_same_name_under_the_same_parent_still_collide(): void+ {+ $dc1 = Location::factory()->create(['name' => 'DC1', 'company_id' => null]);+ Location::factory()->create(['name' => 'Rack 1', 'parent_id' => $dc1->id, 'company_id' => null]);++ $duplicate = new Location([+ 'name' => 'Rack 1',+ 'parent_id' => $dc1->id,+ 'company_id' => null,+ ]);++ $this->assertFalse($duplicate->save(), 'sibling name collision should still be rejected');+ $this->assertNotEmpty($duplicate->getErrors()->get('name'));+ }++ public function test_top_level_locations_with_the_same_name_still_collide(): void+ {+ Location::factory()->create(['name' => 'HQ', 'parent_id' => null, 'company_id' => null]);++ $duplicate = new Location([+ 'name' => 'HQ',+ 'parent_id' => null,+ 'company_id' => null,+ ]);++ $this->assertFalse($duplicate->save(), 'two top-level locations sharing a name should still be rejected');+ }++ public function test_top_level_location_and_a_child_can_share_a_name(): void+ {+ // `HQ` at top level and `HQ` under some parent are in different+ // buckets (NULL parent_id vs. non-null parent_id), so they can+ // coexist per SQL uniqueness semantics.+ $parent = Location::factory()->create(['name' => 'DC1', 'parent_id' => null, 'company_id' => null]);++ $topLevelHq = Location::factory()->create(['name' => 'HQ', 'parent_id' => null, 'company_id' => null]);+ $childHq = Location::factory()->create(['name' => 'HQ', 'parent_id' => $parent->id, 'company_id' => null]);++ $this->assertTrue($topLevelHq->exists);+ $this->assertTrue($childHq->exists);+ }++ public function test_same_name_under_different_companies_can_coexist(): void+ {+ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $inA = Location::factory()->create(['name' => 'HQ', 'parent_id' => null, 'company_id' => $companyA->id]);+ $inB = Location::factory()->create(['name' => 'HQ', 'parent_id' => null, 'company_id' => $companyB->id]);++ $this->assertTrue($inA->exists);+ $this->assertTrue($inB->exists);+ }++ public function test_updating_a_location_does_not_conflict_with_itself(): void+ {+ // The prepareUniqueUndeletedInScopeRule trait method excludes the+ // row being edited from the collision check when the model exists.+ // Without that carve-out, save-without-name-change would falsely+ // fail on any subsequent update.+ $location = Location::factory()->create(['name' => 'Existing', 'company_id' => null]);+ $location->address = '123 Somewhere';++ $this->assertTrue($location->save(), 'saving an existing location without a name collision should succeed');+ }+}