A free open source IT asset/license management system
Added dedicated maintenance permission (related right now just to assets)
snipe0daec32ddd52
diff --git a/app/Http/Controllers/Api/MaintenancesController.php b/app/Http/Controllers/Api/MaintenancesController.phpindex 1f14ffa08a..656d06370b 100644--- a/app/Http/Controllers/Api/MaintenancesController.php+++ b/app/Http/Controllers/Api/MaintenancesController.php@@ -257,9 +257,7 @@ class MaintenancesController extends Controllerpublic function history(Request $request, Maintenance $maintenance): JsonResponse|array{- $this->authorize('view', Asset::class);- $asset = $maintenance->asset;- $this->authorize('history', $asset);+ $this->authorize('history', $maintenance);$historyQuery = $maintenance->getHistory($request);$total = (clone $historyQuery)->count();$offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');diff --git a/app/Http/Transformers/UploadedFilesTransformer.php b/app/Http/Transformers/UploadedFilesTransformer.phpindex 4983de03fc..b153a23291 100644--- a/app/Http/Transformers/UploadedFilesTransformer.php+++ b/app/Http/Transformers/UploadedFilesTransformer.php@@ -6,6 +6,7 @@ use App\Helpers\Helper;use App\Helpers\StorageHelper;use App\Models\Actionlog;use Illuminate\Database\Eloquent\Collection;+use Illuminate\Database\Eloquent\SoftDeletes;use Illuminate\Support\Facades\Gate;use Illuminate\Support\Facades\Storage;@@ -24,6 +25,17 @@ class UploadedFilesTransformerpublic function transformFile(Actionlog $file){$snipeModel = $file->item_type;+ $item = null;++ if (is_string($snipeModel) && class_exists($snipeModel)) {+ $itemQuery = $snipeModel::query();++ if (in_array(SoftDeletes::class, class_uses_recursive($snipeModel), true)) {+ $itemQuery->withTrashed();+ }++ $item = $itemQuery->find($file->item_id);+ }$array = ['id' => (int) $file->id,@@ -49,7 +61,7 @@ class UploadedFilesTransformer];$permissions_array['available_actions'] = [- 'delete' => (Gate::allows('update', $snipeModel) && ($file->deleted_at == '')),+ 'delete' => (Gate::allows('update', $item ?? $snipeModel) && ($file->deleted_at == '')),];$array += $permissions_array;diff --git a/app/Models/Maintenance.php b/app/Models/Maintenance.phpindex 66b04b2050..3b466d931c 100644--- a/app/Models/Maintenance.php+++ b/app/Models/Maintenance.php@@ -32,6 +32,9 @@ class Maintenance extends SnipeModel implements ICompanyableChildprotected $presenter = MaintenancesPresenter::class;+ protected $with = ['asset', 'asset.company'];++protected $table = 'maintenances';protected $rules = [diff --git a/app/Models/Traits/Loggable.php b/app/Models/Traits/Loggable.phpindex 319bffe8ad..5ae4fdca07 100644--- a/app/Models/Traits/Loggable.php+++ b/app/Models/Traits/Loggable.php@@ -4,6 +4,7 @@ namespace App\Models\Traits;use App\Models\Actionlog;use App\Models\Asset;+use App\Models\ICompanyableChild;use App\Models\License;use App\Models\LicenseSeat;use App\Models\Location;@@ -235,7 +236,22 @@ trait Loggablereturn $this->license?->company_id;}- return $this->company_id ?? null;+ if (isset($this->company_id)) {+ return $this->company_id;+ }++ // Companyable children (like Maintenance) inherit company visibility from parents.+ if ($this instanceof ICompanyableChild) {+ foreach ((array) $this->getCompanyableParents() as $parentRelation) {+ $parent = $this->{$parentRelation} ?? null;++ if (isset($parent?->company_id)) {+ return $parent->company_id;+ }+ }+ }++ return null;}/**@@ -515,6 +531,7 @@ trait Loggable$log->created_by = auth()->id();$log->note = $note;$log->target_id = null;+ $log->company_id = $this->resolveLoggableCompanyId();$log->created_at = date('Y-m-d H:i:s');$log->action_date = date('Y-m-d H:i:s');$log->filename = $filename;diff --git a/app/Observers/MaintenanceObserver.php b/app/Observers/MaintenanceObserver.phpindex 47462d10cd..392cb6bcd7 100644--- a/app/Observers/MaintenanceObserver.php+++ b/app/Observers/MaintenanceObserver.php@@ -13,8 +13,25 @@ class MaintenanceObserver** @return void*/- public function updated(Maintenance $maintenance)+ public function updating(Maintenance $maintenance){+ $changed = [];++ foreach ($maintenance->getRawOriginal() as $key => $value) {+ if (array_key_exists($key, $maintenance->getAttributes())+ && $maintenance->getRawOriginal()[$key] != $maintenance->getAttributes()[$key]+ ) {+ $changed[$key] = [+ 'old' => $maintenance->getRawOriginal()[$key],+ 'new' => $maintenance->getAttributes()[$key],+ ];+ }+ }++ if (empty($changed)) {+ return;+ }+$logAction = new Actionlog;$logAction->item_type = Maintenance::class;$logAction->item_id = $maintenance->id;@@ -23,6 +40,7 @@ class MaintenanceObserver$logAction->created_at = date('Y-m-d H:i:s');$logAction->action_date = date('Y-m-d H:i:s');$logAction->created_by = auth()->id();+ $logAction->log_meta = json_encode($changed);if ($maintenance->imported) {$logAction->setActionSource('importer');}diff --git a/app/Policies/MaintenancePolicy.php b/app/Policies/MaintenancePolicy.phpnew file mode 100644index 0000000000..0520e349d5--- /dev/null+++ b/app/Policies/MaintenancePolicy.php@@ -0,0 +1,98 @@+<?php++namespace App\Policies;++use App\Models\Asset;+use App\Models\Maintenance;+use App\Models\User;+use Illuminate\Auth\Access\HandlesAuthorization;+use Illuminate\Support\Facades\Gate;++/**+ * Policy for Asset Maintenances.+ *+ * A user may view or create maintenances on an asset if they have permission+ * to edit that asset. All other standard CRUD operations fall back to the+ * assets.edit permission, consistent with the rest of the application.+ */+final class MaintenancePolicy+{+ use HandlesAuthorization;++ /**+ * Superusers and admins are handled globally in AuthServiceProvider::boot().+ * Company-scoping is enforced at the model level via CompanyableChildTrait.+ */++ /**+ * Determine whether the user can list maintenances.+ * Requires asset edit permission (no specific asset to check against).+ */+ public function index(User $user): bool+ {+ return $user->hasAccess('assets.view');+ }++ /**+ * Determine whether the user can view a specific maintenance record.+ * Allowed if the user can edit the associated asset.+ */+ public function view(User $user, Maintenance $maintenance): bool+ {+ return Gate::allows('update', $maintenance->asset);+ }++ /**+ * Determine whether the user can create a maintenance record.+ * When checking against the class (no instance), fall back to assets.edit.+ * When an asset instance is provided via context, check update on that asset.+ */+ public function create(User $user, ?Asset $asset = null): bool+ {+ if ($asset instanceof Asset) {+ return Gate::allows('update', $asset);+ }++ return $user->hasAccess('assets.edit');+ }++ /**+ * Determine whether the user can update a maintenance record.+ * Allowed if the user can edit the associated asset.+ */+ public function update(User $user, Maintenance $maintenance): bool+ {+ return Gate::allows('update', $maintenance->asset);+ }++ /**+ * Determine whether the user can delete a maintenance record.+ * Allowed if the user can edit the associated asset and the record is not soft-deleted.+ */+ public function delete(User $user, Maintenance $maintenance): bool+ {+ return empty($maintenance->deleted_at)+ && Gate::allows('update', $maintenance->asset);+ }++ /**+ * Determine whether the user can upload or manage files attached to a maintenance record.+ * Allowed if the user can edit the associated asset.+ */+ public function files(User $user, Maintenance $maintenance): bool+ {+ return Gate::allows('update', $maintenance->asset);+ }++ /**+ * Determine whether the user can view history for a maintenance record.+ * Allowed when the user can view the maintenance itself, or has global activity view permission.+ */+ public function history(User $user, Maintenance $maintenance): bool+ {+ return Gate::allows('view', $maintenance->asset)+ || Gate::allows('view', $maintenance)+ || $user->hasAccess('activity.view');+ }+}+diff --git a/app/Providers/AuthServiceProvider.php b/app/Providers/AuthServiceProvider.phpindex 1ece49a070..498ac1f03b 100644--- a/app/Providers/AuthServiceProvider.php+++ b/app/Providers/AuthServiceProvider.php@@ -15,6 +15,7 @@ use App\Models\Department;use App\Models\Depreciation;use App\Models\License;use App\Models\Location;+use App\Models\Maintenance;use App\Models\Manufacturer;use App\Models\PredefinedKit;use App\Models\Statuslabel;@@ -33,6 +34,7 @@ use App\Policies\DepartmentPolicy;use App\Policies\DepreciationPolicy;use App\Policies\LicensePolicy;use App\Policies\LocationPolicy;+use App\Policies\MaintenancePolicy;use App\Policies\ManufacturerPolicy;use App\Policies\PredefinedKitPolicy;use App\Policies\StatuslabelPolicy;@@ -68,6 +70,7 @@ class AuthServiceProvider extends ServiceProviderDepreciation::class => DepreciationPolicy::class,License::class => LicensePolicy::class,Location::class => LocationPolicy::class,+ Maintenance::class => MaintenancePolicy::class,PredefinedKit::class => PredefinedKitPolicy::class,Statuslabel::class => StatuslabelPolicy::class,Supplier::class => SupplierPolicy::class,diff --git a/resources/views/maintenances/view.blade.php b/resources/views/maintenances/view.blade.phpindex f8bbfe0510..10f686d997 100644--- a/resources/views/maintenances/view.blade.php+++ b/resources/views/maintenances/view.blade.php@@ -22,6 +22,7 @@ use Carbon\Carbon;<x-slot:tabnav><x-tabs.details-tab/><x-tabs.files-tab :item="$maintenance" count="{{ $maintenance->uploads()->count() }}"/>+ <x-tabs.history-tab count="{{ $maintenance->history()->count() }}" :model="$maintenance"/><x-tabs.upload-tab :item="$maintenance"/></x-slot:tabnav>@@ -162,6 +163,10 @@ use Carbon\Carbon;<x-table.files object_type="maintenances" :object="$maintenance"/></x-tabs.pane>+ <x-tabs.pane name="history">+ <x-table.history :model="$maintenance" :route="route('api.maintenances.history', $maintenance)"/>+ </x-tabs.pane>+</x-slot:tabpanes></x-tabs>@@ -185,7 +190,7 @@ use Carbon\Carbon;@section('moar_scripts')- @can('files', $maintenance->asset)+ @can('files', $maintenance)@include ('modals.upload-file', ['item_type' => 'maintenances', 'item_id' => $maintenance->id])@endcandiff --git a/tests/Feature/Maintenances/Api/EditMaintenanceTest.php b/tests/Feature/Maintenances/Api/EditMaintenanceTest.phpindex 9c566f55af..864c6ee71c 100644--- a/tests/Feature/Maintenances/Api/EditMaintenanceTest.php+++ b/tests/Feature/Maintenances/Api/EditMaintenanceTest.php@@ -2,6 +2,8 @@namespace Tests\Feature\Maintenances\Api;+use App\Models\Actionlog;+use App\Models\Company;use App\Models\Maintenance;use App\Models\Supplier;use App\Models\User;@@ -60,5 +62,38 @@ class EditMaintenanceTest extends TestCase]);$this->assertHasTheseActionLogs($maintenance, ['create', 'update']);++ $updateLog = Actionlog::query()+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->where('action_type', 'update')+ ->latest('id')+ ->first();++ $this->assertNotNull($updateLog);+ $this->assertNotNull($updateLog->log_meta);+ $this->assertArrayHasKey('name', json_decode($updateLog->log_meta, true));+ }++ public function test_user_cannot_edit_maintenance_for_another_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $userInCompanyA = $companyA->users()->save(User::factory()->editAssets()->make());+ $maintenanceForCompanyB = Maintenance::factory()->create();+ $maintenanceForCompanyB->asset->update(['company_id' => $companyB->id]);++ $this->actingAsForApi($userInCompanyA)+ ->putJson(route('api.maintenances.update', $maintenanceForCompanyB), [+ 'name' => 'Should Not Update',+ ])+ ->assertStatusMessageIs('error');++ $this->assertDatabaseMissing('maintenances', [+ 'id' => $maintenanceForCompanyB->id,+ 'name' => 'Should Not Update',+ ]);}}diff --git a/tests/Feature/Maintenances/Api/MaintenanceFileTest.php b/tests/Feature/Maintenances/Api/MaintenanceFileTest.phpnew file mode 100644index 0000000000..d57db65618--- /dev/null+++ b/tests/Feature/Maintenances/Api/MaintenanceFileTest.php@@ -0,0 +1,80 @@+<?php++namespace Tests\Feature\Maintenances\Api;++use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\Company;+use App\Models\Maintenance;+use App\Models\User;+use Illuminate\Http\UploadedFile;+use Tests\TestCase;++class MaintenanceFileTest extends TestCase+{+ public function test_non_superuser_can_upload_and_list_maintenance_files_with_assets_edit_permission()+ {+ $company = Company::factory()->create();++ $user = User::factory()+ ->editAssets()+ ->create(['company_id' => $company->id]);++ $asset = Asset::factory()->create(['company_id' => $company->id]);++ $maintenance = Maintenance::factory()->create([+ 'asset_id' => $asset->id,+ 'created_by' => $user->id,+ ]);++ $this->actingAsForApi($user)+ ->post(route('api.files.store', ['object_type' => 'maintenances', 'id' => $maintenance->id]), [+ 'file' => [UploadedFile::fake()->create('maintenance-test.pdf', 64)],+ ])+ ->assertOk();++ $uploadedLog = Actionlog::query()+ ->where('action_type', 'uploaded')+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->latest('id')+ ->first();++ $this->assertNotNull($uploadedLog);+ $this->assertSame($company->id, $uploadedLog->company_id);++ $this->actingAsForApi($user)+ ->getJson(route('api.files.index', ['object_type' => 'maintenances', 'id' => $maintenance->id]))+ ->assertOk()+ ->assertJsonStructure(['rows', 'total'])+ ->assertJsonPath('total', 1);+ }++ public function test_user_cannot_list_or_upload_files_for_maintenance_in_another_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $userInCompanyA = $companyA->users()->save(User::factory()->editAssets()->make());+ $maintenanceForCompanyB = Maintenance::factory()->create();+ $maintenanceForCompanyB->asset->update(['company_id' => $companyB->id]);++ $this->actingAsForApi($userInCompanyA)+ ->getJson(route('api.files.index', ['object_type' => 'maintenances', 'id' => $maintenanceForCompanyB->id]))+ ->assertForbidden();++ $this->actingAsForApi($userInCompanyA)+ ->post(route('api.files.store', ['object_type' => 'maintenances', 'id' => $maintenanceForCompanyB->id]), [+ 'file' => [UploadedFile::fake()->create('cross-company.pdf', 64)],+ ])+ ->assertForbidden();++ $this->assertDatabaseMissing('action_logs', [+ 'action_type' => 'uploaded',+ 'item_type' => Maintenance::class,+ 'item_id' => $maintenanceForCompanyB->id,+ ]);+ }+}+diff --git a/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php b/tests/Feature/Maintenances/Ui/EditMaintenanceTest.phpindex 62397e73ed..33423b8d5e 100644--- a/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php+++ b/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php@@ -2,7 +2,9 @@namespace Tests\Feature\Maintenances\Ui;+use App\Models\Actionlog;use App\Models\Asset;+use App\Models\Company;use App\Models\Maintenance;use App\Models\Supplier;use App\Models\User;@@ -64,5 +66,45 @@ class EditMaintenanceTest extends TestCase]);$this->assertHasTheseActionLogs($maintenance, ['create', 'update']);++ $updateLog = Actionlog::query()+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->where('action_type', 'update')+ ->latest('id')+ ->first();++ $this->assertNotNull($updateLog);+ $this->assertNotNull($updateLog->log_meta);+ $this->assertArrayHasKey('name', json_decode($updateLog->log_meta, true));+ }++ public function test_user_cannot_edit_maintenance_for_another_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $userInCompanyA = $companyA->users()->save(User::factory()->editAssets()->make());+ $maintenanceForCompanyB = Maintenance::factory()->create();+ $maintenanceForCompanyB->asset->update(['company_id' => $companyB->id]);++ $this->actingAs($userInCompanyA)+ ->get(route('maintenances.edit', $maintenanceForCompanyB))+ ->assertRedirectToRoute('maintenances.index');++ $this->actingAs($userInCompanyA)+ ->put(route('maintenances.update', $maintenanceForCompanyB), [+ 'name' => 'Should Not Update',+ 'asset_id' => $maintenanceForCompanyB->asset_id,+ 'asset_maintenance_type' => $maintenanceForCompanyB->asset_maintenance_type,+ 'start_date' => $maintenanceForCompanyB->start_date,+ ])+ ->assertRedirectToRoute('maintenances.index');++ $this->assertDatabaseMissing('maintenances', [+ 'id' => $maintenanceForCompanyB->id,+ 'name' => 'Should Not Update',+ ]);}}diff --git a/tests/Feature/Maintenances/Ui/MaintenanceFileTest.php b/tests/Feature/Maintenances/Ui/MaintenanceFileTest.phpnew file mode 100644index 0000000000..e569bb8b62--- /dev/null+++ b/tests/Feature/Maintenances/Ui/MaintenanceFileTest.php@@ -0,0 +1,101 @@+<?php++namespace Tests\Feature\Maintenances\Ui;++use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\Company;+use App\Models\Maintenance;+use App\Models\User;+use Illuminate\Http\UploadedFile;+use Illuminate\Support\Facades\Storage;+use Tests\TestCase;++class MaintenanceFileTest extends TestCase+{+ public function test_non_superuser_can_upload_maintenance_file_via_ui_route()+ {+ Storage::fake('local');++ $company = Company::factory()->create();++ $user = User::factory()+ ->editAssets()+ ->create(['company_id' => $company->id]);++ $asset = Asset::factory()->create(['company_id' => $company->id]);++ $maintenance = Maintenance::factory()->create([+ 'asset_id' => $asset->id,+ 'created_by' => $user->id,+ ]);++ $this->actingAs($user)+ ->post(route('ui.files.store', ['object_type' => 'maintenances', 'id' => $maintenance->id]), [+ 'file' => [UploadedFile::fake()->create('maintenance-test.pdf', 64)],+ 'notes' => 'UI upload test',+ ])+ ->assertStatus(302)+ ->assertSessionHasNoErrors();++ $uploadedLog = Actionlog::query()+ ->where('action_type', 'uploaded')+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->latest('id')+ ->first();++ $this->assertNotNull($uploadedLog);+ $this->assertSame($company->id, $uploadedLog->company_id);+ }++ public function test_maintenance_show_page_includes_upload_modal_for_user_with_file_permission()+ {+ $company = Company::factory()->create();++ $user = User::factory()+ ->editAssets()+ ->create(['company_id' => $company->id]);++ $asset = Asset::factory()->create(['company_id' => $company->id]);++ $maintenance = Maintenance::factory()->create([+ 'asset_id' => $asset->id,+ 'created_by' => $user->id,+ ]);++ $this->actingAs($user)+ ->get(route('maintenances.show', $maintenance))+ ->assertOk()+ ->assertSee('id="uploadFileModal"', false)+ ->assertSee(route('ui.files.store', ['object_type' => 'maintenances', 'id' => $maintenance->id]), false);+ }++ public function test_user_cannot_view_or_upload_files_for_maintenance_in_another_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $userInCompanyA = $companyA->users()->save(User::factory()->editAssets()->make());+ $maintenanceForCompanyB = Maintenance::factory()->create();+ $maintenanceForCompanyB->asset->update(['company_id' => $companyB->id]);++ $this->actingAs($userInCompanyA)+ ->get(route('maintenances.show', $maintenanceForCompanyB))+ ->assertRedirectToRoute('maintenances.index');++ $this->actingAs($userInCompanyA)+ ->post(route('ui.files.store', ['object_type' => 'maintenances', 'id' => $maintenanceForCompanyB->id]), [+ 'file' => [UploadedFile::fake()->create('cross-company.pdf', 64)],+ ])+ ->assertForbidden();++ $this->assertDatabaseMissing('action_logs', [+ 'action_type' => 'uploaded',+ 'item_type' => Maintenance::class,+ 'item_id' => $maintenanceForCompanyB->id,+ ]);+ }+}+diff --git a/tests/Feature/Maintenances/Ui/ShowMaintenanceTest.php b/tests/Feature/Maintenances/Ui/ShowMaintenanceTest.phpindex 4495676f5c..2339bf9abc 100644--- a/tests/Feature/Maintenances/Ui/ShowMaintenanceTest.php+++ b/tests/Feature/Maintenances/Ui/ShowMaintenanceTest.php@@ -2,6 +2,7 @@namespace Tests\Feature\Maintenances\Ui;+use App\Models\Company;use App\Models\Maintenance;use App\Models\User;use Tests\TestCase;@@ -14,4 +15,30 @@ class ShowMaintenanceTest extends TestCase->get(route('maintenances.show', Maintenance::factory()->create()->id))->assertOk();}++ public function test_page_renders_history_tab_and_history_table()+ {+ $maintenance = Maintenance::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->get(route('maintenances.show', $maintenance))+ ->assertOk()+ ->assertSee(trans('general.history'))+ ->assertSee(route('api.maintenances.history', $maintenance), false);+ }++ public function test_user_cannot_view_maintenance_for_another_company_when_fmcs_enabled()+ {+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $userInCompanyA = $companyA->users()->save(User::factory()->editAssets()->make());+ $maintenanceForCompanyB = Maintenance::factory()->create();+ $maintenanceForCompanyB->asset->update(['company_id' => $companyB->id]);++ $this->actingAs($userInCompanyA)+ ->get(route('maintenances.show', $maintenanceForCompanyB))+ ->assertRedirectToRoute('maintenances.index');+ }}