A free open source IT asset/license management system
Handle parent+children users, etc
snipe888b63ba4c0c
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.phpindex c175140c50..2a9be43ff8 100644--- a/app/Http/Controllers/Api/AccessoriesController.php+++ b/app/Http/Controllers/Api/AccessoriesController.php@@ -83,7 +83,13 @@ class AccessoriesController extends Controller}if ($request->filled('company_id')) {- $accessories->where('accessories.company_id', '=', $request->input('company_id'));+ // expand_company_hierarchy=1 opts the company show-page tabs into the+ // parent/child rollup so a child shows items inherited from its parent.+ if ($request->boolean('expand_company_hierarchy')) {+ $accessories->whereIn('accessories.company_id', Company::reachableCompanyIds($request->input('company_id')));+ } else {+ $accessories->where('accessories.company_id', '=', $request->input('company_id'));+ }}if ($request->filled('order_number')) {diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.phpindex 63446092f5..2f1ced473d 100644--- a/app/Http/Controllers/Api/AssetsController.php+++ b/app/Http/Controllers/Api/AssetsController.php@@ -352,7 +352,13 @@ class AssetsController extends Controller}if ($request->filled('company_id')) {- $assets->where('assets.company_id', '=', $request->input('company_id'));+ // expand_company_hierarchy=1 opts the company show-page tabs into the+ // parent/child rollup so a child shows items inherited from its parent.+ if ($request->boolean('expand_company_hierarchy')) {+ $assets->whereIn('assets.company_id', Company::reachableCompanyIds($request->input('company_id')));+ } else {+ $assets->where('assets.company_id', '=', $request->input('company_id'));+ }}if ($request->filled('manufacturer_id')) {diff --git a/app/Http/Controllers/Api/CompaniesController.php b/app/Http/Controllers/Api/CompaniesController.phpindex e8e31ee8a8..2d94cd6e4d 100644--- a/app/Http/Controllers/Api/CompaniesController.php+++ b/app/Http/Controllers/Api/CompaniesController.php@@ -30,7 +30,7 @@ class CompaniesController extends Controller$allowed_columns = ['id','name',- 'parent_id',+ 'parent','phone','fax','email',@@ -51,7 +51,19 @@ class CompaniesController extends Controller$query->AssetsForShow();}])->with('adminuser', 'parent')- ->withCount('licenses as licenses_count', 'accessories as accessories_count', 'consumables as consumables_count', 'components as components_count', 'users as users_count', 'children as children_count');+ ->withCount('licenses as licenses_count')+ ->withCount('accessories as accessories_count')+ ->withCount('consumables as consumables_count')+ ->withCount('components as components_count')+ ->withCount('users as users_count')+ // children is a self-relation. Laravel aliases the related table to+ // `laravel_reserved_0` for the count subquery, but CompanyableScope+ // hardcodes `companies.id` in its where clause — that clashes with+ // the alias and produces "Unknown column 'laravel_reserved_0.parent_id'".+ // The closure form lets us strip the global scope on the subquery.+ ->withCount(['children as children_count' => function ($query) {+ $query->withoutGlobalScopes();+ }]);// This invokes the Searchable model trait scopeTextSearch and will handle input by search or by advanced search filterif ($request->filled('filter') || $request->filled('search')) {@@ -95,6 +107,9 @@ class CompaniesController extends Controllercase 'created_by':$companies = $companies->OrderByCreatedBy($order);break;+ case 'parent':+ $companies = $companies->OrderParent($order);+ break;default:$companies = $companies->orderBy($column_sort, $order);break;diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.phpindex bf754ba1a5..b10ab8872c 100644--- a/app/Http/Controllers/Api/ComponentsController.php+++ b/app/Http/Controllers/Api/ComponentsController.php@@ -85,7 +85,13 @@ class ComponentsController extends Controller}if ($request->filled('company_id')) {- $components->where('components.company_id', '=', $request->input('company_id'));+ // expand_company_hierarchy=1 opts the company show-page tabs into the+ // parent/child rollup so a child shows items inherited from its parent.+ if ($request->boolean('expand_company_hierarchy')) {+ $components->whereIn('components.company_id', Company::reachableCompanyIds($request->input('company_id')));+ } else {+ $components->where('components.company_id', '=', $request->input('company_id'));+ }}if ($request->filled('order_number')) {diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.phpindex 83758d47b9..3e6c941282 100644--- a/app/Http/Controllers/Api/ConsumablesController.php+++ b/app/Http/Controllers/Api/ConsumablesController.php@@ -73,7 +73,13 @@ class ConsumablesController extends Controller}if ($request->filled('company_id')) {- $consumables->where('consumables.company_id', '=', $request->input('company_id'));+ // expand_company_hierarchy=1 opts the company show-page tabs into the+ // parent/child rollup so a child shows items inherited from its parent.+ if ($request->boolean('expand_company_hierarchy')) {+ $consumables->whereIn('consumables.company_id', Company::reachableCompanyIds($request->input('company_id')));+ } else {+ $consumables->where('consumables.company_id', '=', $request->input('company_id'));+ }}if ($request->filled('order_number')) {diff --git a/app/Http/Controllers/Api/LicensesController.php b/app/Http/Controllers/Api/LicensesController.phpindex 808c3e5c7c..ab30038cb9 100644--- a/app/Http/Controllers/Api/LicensesController.php+++ b/app/Http/Controllers/Api/LicensesController.php@@ -50,7 +50,13 @@ class LicensesController extends Controller}if ($request->filled('company_id')) {- $licenses->where('licenses.company_id', '=', $request->input('company_id'));+ // expand_company_hierarchy=1 opts the company show-page tabs into the+ // parent/child rollup so a child shows items inherited from its parent.+ if ($request->boolean('expand_company_hierarchy')) {+ $licenses->whereIn('licenses.company_id', Company::reachableCompanyIds($request->input('company_id')));+ } else {+ $licenses->where('licenses.company_id', '=', $request->input('company_id'));+ }}if ($request->filled('name')) {diff --git a/app/Http/Controllers/Api/UsersController.php b/app/Http/Controllers/Api/UsersController.phpindex a2395beda6..b0af0c7d73 100644--- a/app/Http/Controllers/Api/UsersController.php+++ b/app/Http/Controllers/Api/UsersController.php@@ -191,7 +191,15 @@ class UsersController extends Controller}if ($request->filled('company_id')) {- $users = $users->whereHas('companies', fn ($q) => $q->where('companies.id', $request->input('company_id')));+ // When the caller is the company show-page (expand_company_hierarchy=1),+ // include users who belong to the company's parent or any of its+ // direct children — they inherit access via the one-level hierarchy.+ // Other callers (select2 dropdowns, etc.) keep exact-id semantics.+ $companyIds = $request->boolean('expand_company_hierarchy')+ ? Company::reachableCompanyIds($request->input('company_id'))+ : [(int) $request->input('company_id')];++ $users = $users->whereHas('companies', fn ($q) => $q->whereIn('companies.id', $companyIds));}if ($request->filled('phone')) {diff --git a/app/Http/Controllers/CompaniesController.php b/app/Http/Controllers/CompaniesController.phpindex 8f98415d49..6562718549 100644--- a/app/Http/Controllers/CompaniesController.php+++ b/app/Http/Controllers/CompaniesController.php@@ -3,7 +3,13 @@namespace App\Http\Controllers;use App\Http\Requests\ImageUploadRequest;+use App\Models\Accessory;+use App\Models\Asset;use App\Models\Company;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\License;+use App\Models\User;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;@@ -61,7 +67,7 @@ final class CompaniesController extends Controller$company = new Company;$company->name = $request->input('name');- $company->parent_id = $request->input('parent_id') ?: null;+ $company->parent_id = $request->input('parent_id');$company->phone = $request->input('phone');$company->fax = $request->input('fax');$company->email = $request->input('email');@@ -109,7 +115,7 @@ final class CompaniesController extends Controller$this->authorize('update', $company);$company->name = $request->input('name');- $company->parent_id = $request->input('parent_id') ?: null;+ $company->parent_id = $request->input('parent_id');$company->phone = $request->input('phone');$company->fax = $request->input('fax');$company->email = $request->input('email');@@ -167,6 +173,20 @@ final class CompaniesController extends Controller{$this->authorize('view', Company::class);- return view('companies/view')->with('company', $company);+ // Counts on the tab badges include hierarchy (the row + parent + children)+ // to match the tab contents the API serves under expand_company_hierarchy=1.+ // Computed here so the Blade can stay free of @php blocks.+ $reachableIds = Company::reachableCompanyIds($company->id);++ return view('companies/view')+ ->with('company', $company)+ ->with('tabCounts', [+ 'users' => User::whereHas('companies', fn ($q) => $q->whereIn('companies.id', $reachableIds))->count(),+ 'assets' => Asset::whereIn('company_id', $reachableIds)->AssetsForShow()->count(),+ 'licenses' => License::whereIn('company_id', $reachableIds)->count(),+ 'accessories' => Accessory::whereIn('company_id', $reachableIds)->count(),+ 'consumables' => Consumable::whereIn('company_id', $reachableIds)->count(),+ 'components' => Component::whereIn('company_id', $reachableIds)->count(),+ ]);}}diff --git a/app/Models/Company.php b/app/Models/Company.phpindex abb9321c86..3748ba379c 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -46,6 +46,18 @@ final class Company extends SnipeModel'parent_id' => 'integer',];+ /**+ * A company with no parent stores NULL, never 0 — the empty string from an+ * unselected select2 and a literal 0 would otherwise survive the integer+ * cast and break the `exists:` validation + parent/child queries.+ */+ public function setParentIdAttribute($value): void+ {+ $this->attributes['parent_id'] = ($value === '' || $value === null || (int) $value === 0)+ ? null+ : (int) $value;+ }+protected $presenter = CompanyPresenter::class;use Presentable;@@ -101,6 +113,17 @@ final class Company extends SnipeModel'notes',];+ /**+ * Per-request memoization for getCurrentUserCompanyIds(), keyed by user id.+ * CompanyableScope::apply() calls that method on every Eloquent query against+ * a Companyable model, and the index/transformer hot path runs hundreds of+ * such queries per page — without memoization we issue thousands of redundant+ * pivot reads. Cleared explicitly in tests via flushCompanyIdsCache().+ *+ * @var array<int, array<int>>+ */+ private static array $companyIdsCache = [];+/*** Return the current user's company IDs by querying the pivot table directly.*@@ -119,13 +142,19 @@ final class Company extends SnipeModelreturn [];}+ $userId = auth()->id();++ if (array_key_exists($userId, self::$companyIdsCache)) {+ return self::$companyIdsCache[$userId];+ }+$directIds = DB::table('company_user')- ->where('user_id', auth()->id())+ ->where('user_id', $userId)->pluck('company_id')->toArray();if (empty($directIds)) {- return [];+ return self::$companyIdsCache[$userId] = [];}$childIds = DB::table('companies')@@ -133,7 +162,57 @@ final class Company extends SnipeModel->pluck('id')->toArray();- return array_values(array_unique(array_merge($directIds, $childIds)));+ return self::$companyIdsCache[$userId] = array_values(array_unique(array_merge($directIds, $childIds)));+ }++ /**+ * Reset the per-user company-ids memoization. Called from TestCase::setUp()+ * so that test isolation isn't broken by static state surviving across tests+ * (RefreshDatabase rolls back the DB but not PHP static properties).+ */+ public static function flushCompanyIdsCache(): void+ {+ self::$companyIdsCache = [];+ }++ /**+ * Return the set of company IDs a user viewing $companyId should see items+ * from when "hierarchy expansion" is requested — the company itself, its+ * direct parent (if any), and any of its direct children.+ *+ * Used by the company show-page tabs (users / assets / licenses / etc.) so+ * that viewing a child company also surfaces items inherited from the+ * parent, and viewing a parent surfaces items from its children. The+ * one-level-deep validator caps the chain at depth 2, so this is at most+ * three rows.+ *+ * Returns the original id alone if the company can't be found, so callers+ * can pass the result straight into a whereIn without special-casing.+ */+ public static function reachableCompanyIds(int|string $companyId): array+ {+ $companyId = (int) $companyId;+ if ($companyId <= 0) {+ return [];+ }++ $row = DB::table('companies')->where('id', $companyId)->first(['id', 'parent_id']);+ if (! $row) {+ return [$companyId];+ }++ $ids = [(int) $row->id];+ if ($row->parent_id) {+ $ids[] = (int) $row->parent_id;+ }++ $childIds = DB::table('companies')+ ->where('parent_id', $companyId)+ ->pluck('id')+ ->map(fn ($v) => (int) $v)+ ->all();++ return array_values(array_unique(array_merge($ids, $childIds)));}public static function isFullMultipleCompanySupportEnabled()@@ -333,7 +412,6 @@ final class Company extends SnipeModel&& (($this->licenses_count ?? $this->licenses()->count()) === 0)&& (($this->components_count ?? $this->components()->count()) === 0)&& (($this->consumables_count ?? $this->consumables()->count()) === 0)- && (($this->accessories_count ?? $this->accessories()->count()) === 0)&& (($this->users_count ?? $this->users()->count()) === 0)&& (($this->children_count ?? $this->children()->count()) === 0);}@@ -357,19 +435,42 @@ final class Company extends SnipeModel/*** Parent company (one level only — children cannot themselves have children).+ *+ * Bypasses CompanyableScope because the scope hardcodes `companies.id` in its+ * where clause, which collides with Eloquent's self-relation auto-alias+ * (`laravel_reserved_0`) and produces "Unknown column 'laravel_reserved_0.parent_id'"+ * on the index page. Hierarchy is metadata about a row the user already sees,+ * not an access decision, so unscoping here is semantically correct too.*/public function parent(){- return $this->belongsTo(self::class, 'parent_id');+ return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScopes();}/*** Child companies. The one-level-deep validator on parent_id guarantees* children of a child cannot be created, so this is the full descendant set.+ * See parent() above for why the global scope is dropped.*/public function children(){- return $this->hasMany(self::class, 'parent_id');+ return $this->hasMany(self::class, 'parent_id')->withoutGlobalScopes();+ }++ /**+ * Sort the company list by the parent company's name. Left join so that+ * top-level companies (parent_id IS NULL) still appear in the results.+ *+ * Use addSelect (not select) so prior withCount subqueries on the query+ * survive — select() replaces the whole columns list and would strip the+ * eager *_count columns, forcing isDeletable() and the transformer into a+ * 7-query-per-row N+1.+ */+ public function scopeOrderParent($query, $order)+ {+ return $query->leftJoin('companies as parent_co', 'companies.parent_id', '=', 'parent_co.id')+ ->addSelect('companies.*')+ ->orderBy('parent_co.name', $order);}public function assets()@@ -562,10 +663,16 @@ final class Company extends SnipeModel}/**- * Query builder scope to order on the user that created it+ * Query builder scope to order on the user that created it.+ *+ * Use addSelect (not select) so prior withCount subqueries on the query+ * survive — see scopeOrderParent() for the same rationale.*/public function scopeOrderByCreatedBy($query, $order){- return $query->leftJoin('users as admin_sort', 'companies.created_by', '=', 'admin_sort.id')->select('companies.*')->orderBy('admin_sort.first_name', $order)->orderBy('admin_sort.last_name', $order);+ return $query->leftJoin('users as admin_sort', 'companies.created_by', '=', 'admin_sort.id')+ ->addSelect('companies.*')+ ->orderBy('admin_sort.first_name', $order)+ ->orderBy('admin_sort.last_name', $order);}}diff --git a/app/Presenters/CompanyPresenter.php b/app/Presenters/CompanyPresenter.phpindex 6d2af89291..fe77148b2d 100644--- a/app/Presenters/CompanyPresenter.php+++ b/app/Presenters/CompanyPresenter.php@@ -30,6 +30,21 @@ class CompanyPresenter extends Presenter'title' => trans('admin/companies/table.name'),'visible' => true,'formatter' => 'companiesLinkFormatter',+ ], [+ 'field' => 'parent',+ 'searchable' => false,+ 'sortable' => true,+ 'switchable' => true,+ 'title' => trans('admin/companies/table.parent'),+ 'visible' => true,+ 'formatter' => 'companiesLinkObjFormatter',+ ], [+ 'field' => 'children_count',+ 'searchable' => false,+ 'sortable' => true,+ 'switchable' => true,+ 'title' => trans('admin/companies/table.children'),+ 'visible' => true,], ['field' => 'phone','searchable' => true,diff --git a/app/Providers/BreadcrumbsServiceProvider.php b/app/Providers/BreadcrumbsServiceProvider.phpindex 7445009884..c746c6bff0 100644--- a/app/Providers/BreadcrumbsServiceProvider.php+++ b/app/Providers/BreadcrumbsServiceProvider.php@@ -170,14 +170,16 @@ class BreadcrumbsServiceProvider extends ServiceProvider->push(trans('general.create'), route('companies.create')));- Breadcrumbs::for('companies.show', fn (Trail $trail, Company $company) => $trail->parent('companies.index', route('companies.index'))- ->push($company->name, route('companies.show', $company))- );+ Breadcrumbs::for('companies.show', function (Trail $trail, Company $company) {+ $trail->parent('companies.index', route('companies.index'));+ $this->pushCompanyHierarchy($trail, $company);+ });- Breadcrumbs::for('companies.edit', fn (Trail $trail, Company $company) => $trail->parent('companies.index', route('companies.index'))- ->push($company->display_name, route('companies.show', $company))- ->push(trans('general.update'))- );+ Breadcrumbs::for('companies.edit', function (Trail $trail, Company $company) {+ $trail->parent('companies.index', route('companies.index'));+ $this->pushCompanyHierarchy($trail, $company);+ $trail->push(trans('general.update'));+ });/*** Components Breadcrumbs@@ -591,4 +593,18 @@ class BreadcrumbsServiceProvider extends ServiceProvider$trail->push($node->name, route('locations.show', $node));}}++ /**+ * Append parent -> child breadcrumbs for a company. The one-level-deep+ * validator on parent_id caps the chain at depth 2, so this is always+ * either [company] or [parent, company].+ */+ private function pushCompanyHierarchy(Trail $trail, Company $company): void+ {+ if ($company->parent) {+ $trail->push($company->parent->name, route('companies.show', $company->parent));+ }++ $trail->push($company->display_name, route('companies.show', $company));+ }}diff --git a/resources/lang/en-US/admin/companies/table.php b/resources/lang/en-US/admin/companies/table.phpindex 50bab54c02..752f2b1b26 100644--- a/resources/lang/en-US/admin/companies/table.php+++ b/resources/lang/en-US/admin/companies/table.php@@ -11,4 +11,7 @@ return ['id' => 'ID','parent' => 'Parent Company','parent_help' => 'Optional. If set, this company is a child of the selected parent. Users assigned to the parent automatically have access to this company. Only one level of nesting is allowed.',+ 'children' => 'Child Companies',+ 'inherited' => 'Inherited',+ 'inherited_help' => 'This item belongs to a related company in the hierarchy (parent or child), not this company directly.',];diff --git a/resources/views/companies/index.blade.php b/resources/views/companies/index.blade.phpindex 4bd579ed37..d9ff133350 100644--- a/resources/views/companies/index.blade.php+++ b/resources/views/companies/index.blade.php@@ -8,9 +8,7 @@{{-- Page content --}}@section('content')- <x-container columns="2">-- <x-page-column class="col-md-9">+ <x-container><x-box><tabledata-columns="{{ \App\Presenters\CompanyPresenter::dataTableLayout() }}"@@ -29,14 +27,6 @@}'></table></x-box>- </x-page-column>--- <!-- side address column -->- <x-page-column class="col-md-3">- <h2>{{ trans('admin/companies/general.about_companies') }}</h2>- <p>{{ trans('admin/companies/general.about_companies_description') }}</p>- </x-page-column></x-container>@stopdiff --git a/resources/views/companies/view.blade.php b/resources/views/companies/view.blade.phpindex 7ef109c729..6916a2661e 100644--- a/resources/views/companies/view.blade.php+++ b/resources/views/companies/view.blade.php@@ -16,12 +16,12 @@<x-page-column class="col-md-9 main-panel"><x-tabs><x-slot:tabnav>- <x-tabs.user-tab count="{{ $company->users->count() }}"/>- <x-tabs.asset-tab count="{{ $company->assets()->AssetsForShow()->count() }}"/>- <x-tabs.license-tab count="{{ $company->licenses->count() }}"/>- <x-tabs.accessory-tab count="{{ $company->accessories->count() }}"/>- <x-tabs.consumable-tab count="{{ $company->consumables->count() }}"/>- <x-tabs.component-tab count="{{ $company->components->count() }}"/>+ <x-tabs.user-tab count="{{ $tabCounts['users'] }}"/>+ <x-tabs.asset-tab count="{{ $tabCounts['assets'] }}"/>+ <x-tabs.license-tab count="{{ $tabCounts['licenses'] }}"/>+ <x-tabs.accessory-tab count="{{ $tabCounts['accessories'] }}"/>+ <x-tabs.consumable-tab count="{{ $tabCounts['consumables'] }}"/>+ <x-tabs.component-tab count="{{ $tabCounts['components'] }}"/><x-tabs.files-tab :item="$company" count="{{ $company->uploads()->count() }}"/><x-tabs.upload-tab :item="$company"/></x-slot:tabnav>@@ -29,37 +29,37 @@<x-slot:tabpanes><!-- start users tab pane --><x-tabs.pane name="users">- <x-table.users name="users" :route="route('api.users.index', ['company_id' => $company->id])"/>+ <x-table.users name="users" :route="route('api.users.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- end users tab pane --><!-- start assets tab pane --><x-tabs.pane name="assets">- <x-table.assets name="assets" :route="route('api.assets.index', ['company_id' => $company->id])"/>+ <x-table.assets name="assets" :route="route('api.assets.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- end assets tab pane --><!-- start licenses tab pane --><x-tabs.pane name="licenses">- <x-table.licenses name="licenses" :route="route('api.licenses.index', ['company_id' => $company->id])"/>+ <x-table.licenses name="licenses" :route="route('api.licenses.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- end licenses tab pane --><!-- start accessory tab pane --><x-tabs.pane name="accessories">- <x-table.accessories name="accessories" :route="route('api.accessories.index', ['company_id' => $company->id])"/>+ <x-table.accessories name="accessories" :route="route('api.accessories.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- end accessory tab pane --><!-- start consumables tab pane --><x-tabs.pane name="consumables">- <x-table.consumables name="consumables" :route="route('api.consumables.index', ['company_id' => $company->id])"/>+ <x-table.consumables name="consumables" :route="route('api.consumables.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- end components tab pane --><!-- start components tab pane --><x-tabs.pane name="components">- <x-table.components name="components" :route="route('api.components.index', ['company_id' => $company->id])"/>+ <x-table.components name="components" :route="route('api.components.index', ['company_id' => $company->id, 'expand_company_hierarchy' => 1])"/></x-tabs.pane><!-- start files tab pane -->@@ -93,6 +93,13 @@@can('files', $company)@include ('modals.upload-file', ['item_type' => 'companies', 'item_id' => $company->id])@endcan+ <script>+ // Bootstrap-table formatters read this to decorate rows whose company+ // doesn't match the company being viewed (i.e. inherited from parent+ // or child via the FMCS hierarchy expansion). See companiesLinkObj+ // Formatter and companiesArrayLinkFormatter in partials/bootstrap-table.+ window.viewingCompanyId = {{ (int) $company->id }};+ </script>@include ('partials.bootstrap-table')@endsectiondiff --git a/resources/views/partials/bootstrap-table.blade.php b/resources/views/partials/bootstrap-table.blade.phpindex be098e7db0..d27b12d9f6 100644--- a/resources/views/partials/bootstrap-table.blade.php+++ b/resources/views/partials/bootstrap-table.blade.php@@ -2250,22 +2250,45 @@}}+ // Renders a small "Inherited" badge when the company shown in a row doesn't+ // match the company whose page we're on (window.viewingCompanyId, set by+ // companies/view.blade.php). On every other page the global is undefined+ // and this returns an empty string — formatters are unchanged elsewhere.+ // Dark background + white text keeps contrast above WCAG AAA (≈12.6:1).+ function inheritedCompanyBadge(matched) {+ if (typeof window.viewingCompanyId === 'undefined' || window.viewingCompanyId === null) {+ return '';+ }+ if (matched) {+ return '';+ }+ return ' <span class="label" style="background:#1a4480;color:#fff;margin-left:4px;" title="{{ trans('admin/companies/table.inherited_help') }}">'+ + '<i class="fa-solid fa-link" aria-hidden="true"></i> {{ trans('admin/companies/table.inherited') }}'+ + '</span>';+ }+function companiesLinkObjFormatter(value, row) {if (!value) {return '';}var icon = (value.tag_color) ? '<i class="fa-solid fa-square" style="color: ' + value.tag_color + ';" aria-hidden="true"></i> ' : '';- return '<a href="{{ config('app.url') }}/companies/' + value.id + '" class="label label-light">' + icon + value.name + '</a>';+ var link = '<a href="{{ config('app.url') }}/companies/' + value.id + '" class="label label-light">' + icon + value.name + '</a>';+ var matched = (typeof window.viewingCompanyId !== 'undefined') && (parseInt(value.id, 10) === parseInt(window.viewingCompanyId, 10));+ return link + inheritedCompanyBadge(matched);}function companiesArrayLinkFormatter(value, row) {if (!value || !value.length) {return '';}- return value.map(function (c) {+ var matched = (typeof window.viewingCompanyId !== 'undefined') && value.some(function (c) {+ return parseInt(c.id, 10) === parseInt(window.viewingCompanyId, 10);+ });+ var links = value.map(function (c) {var icon = (c.tag_color) ? '<i class="fa-solid fa-square" style="color: ' + c.tag_color + ';" aria-hidden="true"></i> ' : '';return '<a href="{{ config('app.url') }}/companies/' + c.id + '" class="label label-light">' + icon + c.name + '</a></span>';}).join(' ');+ return links + inheritedCompanyBadge(matched);}function locationCompanyObjFilterFormatter(value, row) {diff --git a/tests/Feature/Companies/Api/CompanyHierarchyTest.php b/tests/Feature/Companies/Api/CompanyHierarchyTest.phpindex aa8f828d51..ac0eb78989 100644--- a/tests/Feature/Companies/Api/CompanyHierarchyTest.php+++ b/tests/Feature/Companies/Api/CompanyHierarchyTest.php@@ -111,6 +111,38 @@ class CompanyHierarchyTest extends TestCase$this->assertNull($child->fresh()->parent_id);}+ public function test_parent_id_of_zero_is_stored_as_null()+ {+ $this->actingAsForApi(User::factory()->createCompanies()->create())+ ->postJson(route('api.companies.store'), [+ 'name' => 'TopLevelViaZero',+ 'parent_id' => 0,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('success');++ $this->assertDatabaseHas('companies', [+ 'name' => 'TopLevelViaZero',+ 'parent_id' => null,+ ]);+ }++ public function test_parent_id_of_empty_string_is_stored_as_null()+ {+ $this->actingAsForApi(User::factory()->createCompanies()->create())+ ->postJson(route('api.companies.store'), [+ 'name' => 'TopLevelViaEmpty',+ 'parent_id' => '',+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('success');++ $this->assertDatabaseHas('companies', [+ 'name' => 'TopLevelViaEmpty',+ 'parent_id' => null,+ ]);+ }+public function test_parent_id_must_reference_existing_company(){$this->actingAsForApi(User::factory()->createCompanies()->create())@@ -152,6 +184,45 @@ class CompanyHierarchyTest extends TestCase$this->assertEquals(2, $parentRow['children_count']);}+ public function test_index_loads_for_fmcs_scoped_non_superuser()+ {+ // Regression: CompanyableScope hardcodes `companies.id`, which clashes with+ // the alias Eloquent picks for the children-count self-relation subquery.+ // Reproduce the original "Unknown column laravel_reserved_0.parent_id" by+ // hitting the index as a non-superuser with FMCS enabled.+ $this->settings->enableMultipleFullCompanySupport();++ $parent = Company::factory()->create();+ Company::factory()->count(2)->childOf($parent)->create();++ $user = $parent->users()->save(User::factory()->viewCompanies()->make());++ $this->actingAsForApi($user)+ ->getJson(route('api.companies.index'))+ ->assertOk();+ }++ public function test_index_can_sort_by_parent_company_name()+ {+ $alpha = Company::factory()->create(['name' => 'AlphaParent']);+ $zulu = Company::factory()->create(['name' => 'ZuluParent']);+ $alphaChild = Company::factory()->childOf($alpha)->create(['name' => 'AlphaChild']);+ $zuluChild = Company::factory()->childOf($zulu)->create(['name' => 'ZuluChild']);++ $response = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.companies.index', ['sort' => 'parent', 'order' => 'asc', 'limit' => 200]))+ ->assertOk()+ ->json();++ $ids = collect($response['rows'])->pluck('id')->all();+ $alphaChildPos = array_search($alphaChild->id, $ids);+ $zuluChildPos = array_search($zuluChild->id, $ids);++ $this->assertNotFalse($alphaChildPos);+ $this->assertNotFalse($zuluChildPos);+ $this->assertLessThan($zuluChildPos, $alphaChildPos, 'AlphaParent child should sort before ZuluParent child when sorting by parent name asc');+ }+public function test_show_exposes_parent_block_for_child_company(){$parent = Company::factory()->create();@@ -233,6 +304,63 @@ class CompanyHierarchyTest extends TestCase$this->assertNotContains($unrelated->id, $ids);}+ public function test_expand_company_hierarchy_on_assets_includes_parent_and_children()+ {+ $parent = Company::factory()->create();+ $child = Company::factory()->childOf($parent)->create();+ $unrelated = Company::factory()->create();++ $parentAsset = Asset::factory()->create(['company_id' => $parent->id]);+ $childAsset = Asset::factory()->create(['company_id' => $child->id]);+ $unrelatedAsset = Asset::factory()->create(['company_id' => $unrelated->id]);++ // Without the flag: only exact-company match+ $exact = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.assets.index', ['company_id' => $child->id]))+ ->assertOk()+ ->json();+ $exactIds = collect($exact['rows'])->pluck('id')->all();+ $this->assertContains($childAsset->id, $exactIds);+ $this->assertNotContains($parentAsset->id, $exactIds);++ // With expand_company_hierarchy=1: child page includes parent's items+ $expanded = $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.assets.index', ['company_id' => $child->id, 'expand_company_hierarchy' => 1]))+ ->assertOk()+ ->json();+ $expandedIds = collect($expanded['rows'])->pluck('id')->all();+ $this->assertContains($childAsset->id, $expandedIds);+ $this->assertContains($parentAsset->id, $expandedIds, 'Parent asset should appear on the child page when hierarchy is expanded');+ $this->assertNotContains($unrelatedAsset->id, $expandedIds);+ }++ public function test_expand_company_hierarchy_on_users_includes_parent_and_children_members()+ {+ $parent = Company::factory()->create();+ $child = Company::factory()->childOf($parent)->create();++ $parentMember = $parent->users()->save(User::factory()->create());+ $childMember = $child->users()->save(User::factory()->create());++ // Without the flag: child page only shows direct child members+ $exact = $this->actingAsForApi(User::factory()->superuser()->viewUsers()->create())+ ->getJson(route('api.users.index', ['company_id' => $child->id]))+ ->assertOk()+ ->json();+ $exactIds = collect($exact['rows'])->pluck('id')->all();+ $this->assertContains($childMember->id, $exactIds);+ $this->assertNotContains($parentMember->id, $exactIds);++ // With the flag: child page also shows users inherited from the parent+ $expanded = $this->actingAsForApi(User::factory()->superuser()->viewUsers()->create())+ ->getJson(route('api.users.index', ['company_id' => $child->id, 'expand_company_hierarchy' => 1]))+ ->assertOk()+ ->json();+ $expandedIds = collect($expanded['rows'])->pluck('id')->all();+ $this->assertContains($childMember->id, $expandedIds);+ $this->assertContains($parentMember->id, $expandedIds, 'Parent member should appear on the child page when hierarchy is expanded');+ }+public function test_fmcs_floater_mode_still_works_with_hierarchy(){// Floater mode: items with NULL company_id are visible to everyone.diff --git a/tests/Feature/Companies/Ui/ShowCompanyTest.php b/tests/Feature/Companies/Ui/ShowCompanyTest.phpindex 58b7bfeb51..9df4705cd8 100644--- a/tests/Feature/Companies/Ui/ShowCompanyTest.php+++ b/tests/Feature/Companies/Ui/ShowCompanyTest.php@@ -14,4 +14,18 @@ class ShowCompanyTest extends TestCase->get(route('companies.show', Company::factory()->create()))->assertOk();}++ public function test_show_page_includes_parent_company_breadcrumb_hierarchy()+ {+ $parent = Company::factory()->create(['name' => 'Parent Breadcrumb Company']);+ $child = Company::factory()->childOf($parent)->create(['name' => 'Child Breadcrumb Company']);++ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('companies.show', $child))+ ->assertOk()+ ->assertSeeInOrder([+ route('companies.show', $parent),+ route('companies.show', $child),+ ]);+ }}diff --git a/tests/TestCase.php b/tests/TestCase.phpindex 784f459107..53dc5b63ad 100644--- a/tests/TestCase.php+++ b/tests/TestCase.php@@ -4,6 +4,7 @@ namespace Tests;use App\Http\Middleware\SecurityHeaders;use App\Models\Asset;+use App\Models\Company;use Illuminate\Foundation\Testing\LazilyRefreshDatabase;use Illuminate\Foundation\Testing\TestCase as BaseTestCase;use RuntimeException;@@ -44,6 +45,12 @@ abstract class TestCase extends BaseTestCase// Flush the custom field filter map cache between tests so that// dynamically-created custom fields are always picked up fresh.Asset::flushCustomFieldFilterMap();++ // Per-request memoization keyed by user id leaks across tests because+ // RefreshDatabase rolls back the DB but not PHP static state. Auto-+ // increment may hand the same id to a different test's user with a+ // different pivot set.+ Company::flushCompanyIdsCache();}// ...existing code...