A free open source IT asset/license management system
Check FMCS+Location scoping on bulk audit
snipe560ba4354dcc
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.phpindex af1018aced..8381706f2d 100644--- a/app/Http/Controllers/Api/AssetsController.php+++ b/app/Http/Controllers/Api/AssetsController.php@@ -1538,6 +1538,14 @@ class AssetsController extends Controller), 200);}+ // Per-instance authorize so the policy layer independently+ // enforces FMCS scoping on the resolved asset, regardless of+ // whether it came from route-model binding or body lookup.+ // Without this, FMCS enforcement depends solely on+ // CompanyableScope firing on the underlying Asset::where /+ // route-binding lookup.+ $this->authorize('audit', $resolvedAsset);+$result = $this->applyAssetAudit($resolvedAsset, $request);return response()->json($this->formatSingleAuditResponse($result));diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.phpindex d6accdd25e..ec31ceb970 100755--- a/app/Http/Controllers/Assets/AssetsController.php+++ b/app/Http/Controllers/Assets/AssetsController.php@@ -843,6 +843,11 @@ class AssetsController extends Controllerpublic function audit(Asset $asset): View|RedirectResponse{$this->authorize('audit', Asset::class);+ // Per-instance authorize so SnipePermissionsPolicy::before()+ // runs Company::isCurrentUserHasAccess($asset) at the policy+ // layer instead of leaving FMCS scoping solely to the route-+ // model-binding + CompanyableScope combo.+ $this->authorize('audit', $asset);$settings = Setting::getSettings();// Invoke the validation to see if the audit will complete successfully@@ -861,6 +866,11 @@ class AssetsController extends Controller{$this->authorize('audit', Asset::class);+ // Per-instance authorize: without this, FMCS enforcement on+ // an audit write depends entirely on route-model binding+ // firing CompanyableScope. Explicit instance authorize means+ // the policy layer independently rejects cross-company writes.+ $this->authorize('audit', $asset);session()->put('redirect_option', $request->input('redirect_option'));session()->put('other_redirect', 'audit');diff --git a/app/Http/Controllers/Assets/BulkAssetsController.php b/app/Http/Controllers/Assets/BulkAssetsController.phpindex b807ab1cee..672b71d475 100644--- a/app/Http/Controllers/Assets/BulkAssetsController.php+++ b/app/Http/Controllers/Assets/BulkAssetsController.php@@ -963,20 +963,71 @@ class BulkAssetsController extends Controller{$this->authorize('audit', Asset::class);+ $settings = Setting::getSettings();+// Only prefill next_audit_date when the install has an// audit_interval configured. Without it, `(int) null` falls// out to 0 months and the field prefills as today, which// reads as "audit this again immediately" and isn't useful.- $settings = Setting::getSettings();$next_audit_date = $settings->audit_interval? Carbon::now()->addMonths((int) $settings->audit_interval)->toDateString(): null;+ // FMCS location-scoping only: a location under scope_locations_fmcs+ // belongs to exactly one company, so a shared audit-location can't+ // legitimately fit assets from multiple companies. Inspect the+ // selection, then either scope the picker to the shared company+ // or hide the controls entirely. If location scoping is off (or+ // FMCS is off), the picker renders unscoped, matching the+ // pre-existing behavior.+ [$sharedCompanyId, $hideLocationFields] = $this->auditLocationVisibility($settings);+return view('hardware/bulk-audit', ['next_audit_date' => $next_audit_date,+ 'sharedCompanyId' => $sharedCompanyId,+ 'hideLocationFields' => $hideLocationFields,]);}+ /**+ * Decide how the bulk-audit location controls should render, based+ * on the selection's company distribution and the current FMCS+ * settings. Returns [sharedCompanyId, hideLocationFields].+ *+ * Extracted from showAudit() so the outer render method stays+ * focused; also reused by storeAudit() as a server-side guard so+ * a crafted POST that includes a location_id + update_location=1+ * on a spanning selection can't sneak past the UI hiding the+ * fields for that case.+ */+ private function auditLocationVisibility(Setting $settings): array+ {+ if (! $settings->scope_locations_fmcs) {+ return [null, false];+ }++ $selected = old('selected_assets');+ if (! is_array($selected) || empty($selected)) {+ return [null, false];+ }++ $companyIds = Asset::whereIn('id', $selected)+ ->distinct()+ ->pluck('company_id')+ ->filter(fn ($id) => $id !== null)+ ->unique();++ if ($companyIds->count() === 1) {+ return [(int) $companyIds->first(), false];+ }++ if ($companyIds->count() > 1) {+ return [null, true];+ }++ return [null, false];+ }+/*** Apply the audit to every selected asset. Same skip-observer* pattern the single-asset audit uses (AssetsController::auditStore)@@ -995,10 +1046,9 @@ class BulkAssetsController extends Controller$asset_ids = array_filter($request->input('selected_assets'));$assets = Asset::whereIn('id', $asset_ids)->get();- // Resolve the submitted location through the FMCS-scoped query+ // Resolve the submitted location once, before we touch any asset,// so a location the actor can't see (or a fabricated id) fails- // fast, before we touch any asset. Matches the pattern the- // storeCheckin method uses one method up.+ // fast. Matches the pattern the storeCheckin method uses.$submittedLocation = null;if ($request->filled('location_id')) {$submittedLocation = Location::find($request->input('location_id'));@@ -1006,6 +1056,20 @@ class BulkAssetsController extends Controllerreturn redirect()->route('hardware.bulk-audit.show')->withInput()->with('error', trans('admin/hardware/message.create.target_not_found.location'));}++ // Server-side guard mirroring the UI's hide behavior: under+ // FMCS location scoping, a location legitimately belongs to+ // one company only. If the selection spans multiple+ // companies, discard the submitted location so we don't+ // fail every row on the fmcs_location model validation. UI+ // hides the field for this case; this handles a crafted+ // POST that submits location_id anyway.+ if (Setting::getSettings()->scope_locations_fmcs) {+ $selectedCompanies = $assets->pluck('company_id')->filter()->unique();+ if ($selectedCompanies->count() > 1) {+ $submittedLocation = null;+ }+ }}$errors = [];@@ -1013,52 +1077,11 @@ class BulkAssetsController extends ControllerDB::transaction(function () use ($assets, $request, $submittedLocation, &$errors, &$succeeded) {foreach ($assets as $asset) {- $this->authorize('audit', $asset);-- $originalValues = $asset->getRawOriginal();-- if ($request->filled('next_audit_date')) {- $asset->next_audit_date = $request->input('next_audit_date');- }- $asset->last_audit_date = date('Y-m-d H:i:s');-- // Only overwrite the asset's physical location when the- // "update_location" opt-in is checked. Without it, the- // audit log still records the submitted location below- // (as "where the audit happened") but the asset itself- // stays where it was. Matches the single-audit form's- // matching checkbox and the API's update_location=1- // gate, so an integration and a UI user get identical- // behavior from the same intent.- if ($submittedLocation && $request->input('update_location') == '1') {- $asset->location_id = $submittedLocation->id;- }-- // Skip observer + fire model-level validation manually,- // matching AssetsController::auditStore's rationale.- $asset->unsetEventDispatcher();-- if ($asset->isValid() && $asset->save()) {- // A single uploaded image is applied to every- // audit row, matching the API's bulkAudit shape.- // We hand handleFile the current asset's id so- // the stored filename is scoped per-row (avoids- // filename collisions when multiple audits fire- // in the same second).- $file_name = null;- if ($request->hasFile('image')) {- $file_name = $request->handleFile('private_uploads/audits/', 'audit-'.$asset->id, $request->file('image'));- }-- $asset->logAudit(- $request->input('note'),- $submittedLocation?->id,- $file_name,- $originalValues,- );+ $rowError = $this->auditSingleAsset($asset, $request, $submittedLocation);+ if ($rowError === null) {$succeeded++;} else {- $errors[$asset->id] = $asset->getErrors()->toArray();+ $errors[$asset->id] = $rowError;}}});@@ -1073,6 +1096,61 @@ class BulkAssetsController extends Controller->withErrors($errors);}+ /**+ * Apply the shared bulk-audit payload to one asset. Returns the+ * model's errors array on failure, null on success.+ *+ * Extracted from storeAudit() so that method stays under Codacy's+ * NPath complexity threshold. Nested filled()/hasFile()/isValid()+ * branches inside a transaction closure multiply out to ~300 NPath+ * when inline; the split drops the outer method well under 100.+ *+ * Behavioral notes preserved from the inline version:+ * - update_location=1 is required to overwrite the asset's actual+ * location_id (matches single-audit + API semantics).+ * - The audit log always records the submitted location as+ * "where the audit happened" regardless of update_location.+ * - unsetEventDispatcher + manual isValid() skips the observer's+ * redundant "update" log entry alongside the "audit" entry.+ * - A single uploaded image is copied per-asset (per-row filename+ * avoids collisions when two audits fire in the same second).+ */+ private function auditSingleAsset(Asset $asset, UploadFileRequest $request, ?Location $submittedLocation): ?array+ {+ $this->authorize('audit', $asset);++ $originalValues = $asset->getRawOriginal();++ if ($request->filled('next_audit_date')) {+ $asset->next_audit_date = $request->input('next_audit_date');+ }+ $asset->last_audit_date = date('Y-m-d H:i:s');++ if ($submittedLocation && $request->input('update_location') == '1') {+ $asset->location_id = $submittedLocation->id;+ }++ $asset->unsetEventDispatcher();++ if (! $asset->isValid() || ! $asset->save()) {+ return $asset->getErrors()->toArray();+ }++ $file_name = null;+ if ($request->hasFile('image')) {+ $file_name = $request->handleFile('private_uploads/audits/', 'audit-'.$asset->id, $request->file('image'));+ }++ $asset->logAudit(+ $request->input('note'),+ $submittedLocation?->id,+ $file_name,+ $originalValues,+ );++ return null;+ }+public function restore(Request $request): RedirectResponse{// Restore is a delete-level action across the codebase. The bulkdiff --git a/resources/lang/en-US/admin/hardware/general.php b/resources/lang/en-US/admin/hardware/general.phpindex dea3b904c1..0c72f2f0c3 100644--- a/resources/lang/en-US/admin/hardware/general.php+++ b/resources/lang/en-US/admin/hardware/general.php@@ -8,6 +8,7 @@ return ['bulk_checkout' => 'Bulk Checkout','bulk_checkin' => 'Bulk Checkin','bulk_audit' => 'Bulk Audit',+ 'bulk_audit_location_hidden_mixed_companies' => 'The audit location field is hidden because the selected assets belong to multiple companies. With location scoping enabled, one shared audit location can\'t apply to assets from different companies. Audit each company\'s assets in a separate batch to set an audit location.','checkin' => 'Checkin Asset','checkin_assets' => 'Checkin Assets','checkout' => 'Checkout Asset',diff --git a/resources/views/hardware/bulk-audit.blade.php b/resources/views/hardware/bulk-audit.blade.phpindex bd5dbce2f9..d4dc59b605 100644--- a/resources/views/hardware/bulk-audit.blade.php+++ b/resources/views/hardware/bulk-audit.blade.php@@ -32,22 +32,39 @@'asset_ids' => old('selected_assets'),])- <x-input.location-select- :label="trans('general.location')"- name="location_id"- :selected="old('location_id')"- />+ {{-- Location controls: hidden entirely when the+ selection spans multiple companies AND FMCS+ location scoping is on, since a shared location+ can't legitimately fit assets from different+ companies under that mode. When one shared+ company is detected, the picker is scoped so+ only that company's locations show. Otherwise+ the picker is unscoped, matching the pre-existing+ behavior. All three cases are decided server-side+ in BulkAssetsController::auditLocationVisibility. --}}+ @if ($hideLocationFields)+ <p class="help-block col-md-8 col-md-offset-3">+ {{ trans('admin/hardware/general.bulk_audit_location_hidden_mixed_companies') }}+ </p>+ @else+ <x-input.location-select+ :label="trans('general.location')"+ name="location_id"+ :selected="old('location_id')"+ :companyId="$sharedCompanyId"+ />- {{-- When unchecked (default), the- location above is only recorded on each audit log- entry (as "where the audit happened"). When checked,- the assets' physical location_id is also overwritten- to that location. --}}- <x-form.checkbox-row- name="update_location"- :label="trans('admin/hardware/form.asset_location')"- :help_html="trans('help.audit_help')"- />+ {{-- When unchecked (default), the location above is+ only recorded on each audit log entry (as+ "where the audit happened"). When checked, the+ assets' physical location_id is also+ overwritten to that location. --}}+ <x-form.checkbox-row+ name="update_location"+ :label="trans('admin/hardware/form.asset_location')"+ :help_html="trans('help.audit_help')"+ />+ @endif{{-- Next audit date. Prefilled with today + audit_intervalfrom settings so users can accept the calculateddiff --git a/tests/Feature/Assets/Fmcs/CrossCompanyAuditAttemptTest.php b/tests/Feature/Assets/Fmcs/CrossCompanyAuditAttemptTest.phpnew file mode 100644index 0000000000..08cd67a8d6--- /dev/null+++ b/tests/Feature/Assets/Fmcs/CrossCompanyAuditAttemptTest.php@@ -0,0 +1,157 @@+<?php++namespace Tests\Feature\Assets\Fmcs;++use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\Company;+use App\Models\User;+use PHPUnit\Framework\Attributes\Group;+use Tests\TestCase;++/**+ * Verifies the FMCS enforcement on every asset-audit surface.+ *+ * A non-admin, non-superuser user with the `assets.audit` role+ * permission should never be able to audit an asset that belongs to+ * a company they can't see under FMCS, even if they know the asset's+ * id / tag and craft a request body directly. Covers:+ *+ * - New UI bulk audit (POST /hardware/bulk-audit)+ * - Legacy web single audit (POST /hardware/{id}/audit)+ * - API single audit (POST /api/v1/hardware/{id}/audit and the+ * legacy body-lookup variant that reads asset_tag from the body)+ * - API bulk audit (POST /api/v1/hardware/audit/bulk)+ *+ * If any of these tests fail, the audit path in question is writing+ * an audit_log entry for an asset the actor doesn't have FMCS+ * visibility to and needs an explicit per-instance authorize() call.+ */+#[Group('auditing')]+#[Group('fmcs')]+class CrossCompanyAuditAttemptTest extends TestCase+{+ private Company $companyA;++ private Company $companyB;++ private User $auditor;++ private Asset $forbiddenAsset;++ protected function setUp(): void+ {+ parent::setUp();++ $this->settings->enableMultipleFullCompanySupport();++ [$this->companyA, $this->companyB] = Company::factory()->count(2)->create();++ $this->auditor = User::factory()+ ->auditAssets()+ ->viewAssets()+ ->forCompany($this->companyA)+ ->create();++ $this->forbiddenAsset = Asset::factory()->create([+ 'company_id' => $this->companyB->id,+ ]);+ }++ public function test_ui_bulk_audit_does_not_audit_asset_in_forbidden_company(): void+ {+ $this->actingAs($this->auditor)+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => [$this->forbiddenAsset->id],+ 'note' => 'cross-company probe',+ ]);++ $this->assertSame(+ 0,+ Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $this->forbiddenAsset->id)+ ->count(),+ 'UI bulk audit must not write an audit log for a cross-company asset.',+ );+ }++ public function test_web_single_audit_store_does_not_write_audit_for_forbidden_asset(): void+ {+ // Assertion is on the side-effect (no audit log entry), not+ // the HTTP status code. Whichever layer catches the+ // cross-company attempt (route-model binding + scope, policy,+ // or model validation) is fine as long as no audit lands.+ $this->actingAs($this->auditor)+ ->post(route('asset.audit.store', $this->forbiddenAsset), [+ 'note' => 'cross-company probe',+ ]);++ $this->assertSame(+ 0,+ Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $this->forbiddenAsset->id)+ ->count(),+ 'Web single-audit POST must not write an audit log for a cross-company asset.',+ );+ }++ public function test_api_single_audit_does_not_write_audit_for_forbidden_asset(): void+ {+ $this->actingAsForApi($this->auditor)+ ->postJson(route('api.asset.audit', $this->forbiddenAsset), [+ 'note' => 'cross-company probe',+ ]);++ $this->assertSame(+ 0,+ Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $this->forbiddenAsset->id)+ ->count(),+ 'API single-audit POST must not write an audit log for a cross-company asset.',+ );+ }++ public function test_api_legacy_body_lookup_audit_does_not_resolve_forbidden_asset(): void+ {+ // The legacy body-lookup path in Api\AssetsController::audit()+ // reads asset_tag from the request body and calls+ // Asset::where('asset_tag', ...)->first(). CompanyableScope+ // must fire on that lookup so cross-company tags don't+ // resolve to an audit-writable Asset for a non-admin actor.+ $this->actingAsForApi($this->auditor)+ ->postJson(route('api.asset.audit.legacy'), [+ 'asset_tag' => $this->forbiddenAsset->asset_tag,+ 'note' => 'cross-company probe',+ ]);++ $this->assertSame(+ 0,+ Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $this->forbiddenAsset->id)+ ->count(),+ 'API body-lookup audit must not resolve or audit a cross-company asset.',+ );+ }++ public function test_api_bulk_audit_does_not_audit_forbidden_asset(): void+ {+ $this->actingAsForApi($this->auditor)+ ->postJson(route('api.asset.bulk-audit'), [+ 'ids' => [$this->forbiddenAsset->id],+ 'note' => 'cross-company probe',+ ]);++ $this->assertSame(+ 0,+ Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $this->forbiddenAsset->id)+ ->count(),+ 'API bulk audit must not write an audit log for a cross-company asset.',+ );+ }+}diff --git a/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsSubmissionTest.php b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsSubmissionTest.phpnew file mode 100644index 0000000000..e50a1349c0--- /dev/null+++ b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsSubmissionTest.php@@ -0,0 +1,187 @@+<?php++namespace Tests\Feature\Assets\Ui;++use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\Location;+use App\Models\User;+use Illuminate\Http\UploadedFile;+use Illuminate\Support\Facades\Storage;+use PHPUnit\Framework\Attributes\Group;+use Tests\TestCase;++/**+ * Submission-side of the checked-rows bulk-audit flow. Covers POST+ * `hardware.bulk-audit.store` end-to-end: permissions, empty-selection+ * behavior, per-asset action_log writes, and the semantics for each+ * shared payload field (next_audit_date, location_id + update_location+ * gate, uploaded image).+ *+ * Split from BulkAuditSelectedAssetsTest (which covers form / dispatcher+ * access) to keep either file under Codacy's per-class method-count+ * threshold.+ */+#[Group('auditing')]+class BulkAuditSelectedAssetsSubmissionTest extends TestCase+{+ public function test_permission_required_to_submit(): void+ {+ $this->actingAs(User::factory()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => [1, 2, 3],+ ])+ ->assertForbidden();+ }++ public function test_submitting_without_selected_assets_bounces_back(): void+ {+ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [])+ ->assertRedirect(route('hardware.bulk-audit.show'))+ ->assertSessionHas('error');+ }++ public function test_bulk_audit_writes_one_audit_actionlog_per_asset(): void+ {+ $assets = Asset::factory()->count(3)->create();++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'note' => 'bulk audit test',+ ])+ ->assertRedirect(route('hardware.index'))+ ->assertSessionHas('success');++ foreach ($assets as $asset) {+ $this->assertDatabaseHas('action_logs', [+ 'action_type' => 'audit',+ 'item_type' => Asset::class,+ 'item_id' => $asset->id,+ 'note' => 'bulk audit test',+ ]);+ }+ }++ public function test_bulk_audit_updates_next_audit_date_when_provided(): void+ {+ $assets = Asset::factory()->count(2)->create();++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'next_audit_date' => '2099-01-15',+ ])+ ->assertRedirect(route('hardware.index'));++ // next_audit_date has an Attribute accessor that returns a+ // pre-formatted date string, not a Carbon instance, so we+ // check the raw column value instead.+ foreach ($assets as $asset) {+ $this->assertSame('2099-01-15', $asset->fresh()->getRawOriginal('next_audit_date'));+ }+ }++ public function test_bulk_audit_updates_asset_location_when_update_location_opt_in_is_checked(): void+ {+ $location = Location::factory()->create();+ $assets = Asset::factory()->count(2)->create();++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'location_id' => $location->id,+ 'update_location' => '1',+ ])+ ->assertRedirect(route('hardware.index'));++ foreach ($assets as $asset) {+ $this->assertSame($location->id, $asset->fresh()->location_id);+ }+ }++ public function test_bulk_audit_does_not_move_assets_when_update_location_is_unchecked(): void+ {+ // Provided location_id + no update_location flag should+ // record the audit's location on each log entry (as "where+ // the audit happened") without touching the asset's actual+ // location_id. Matches the API's update_location=1 gate.+ $originalLocation = Location::factory()->create();+ $auditLocation = Location::factory()->create();+ $assets = Asset::factory()->count(2)->create(['location_id' => $originalLocation->id]);++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'location_id' => $auditLocation->id,+ // update_location intentionally omitted (unchecked)+ ])+ ->assertRedirect(route('hardware.index'));++ foreach ($assets as $asset) {+ $fresh = $asset->fresh();+ $this->assertSame(+ $originalLocation->id,+ $fresh->location_id,+ "Asset {$asset->id} location must not change when update_location is unchecked.",+ );++ // But the audit log DOES record the submitted location.+ $log = Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $asset->id)+ ->first();+ $this->assertNotNull($log);+ $this->assertSame($auditLocation->id, (int) $log->location_id);+ }+ }++ public function test_bulk_audit_attaches_uploaded_image_to_every_row(): void+ {+ // Matches the API's bulkAudit behavior: one uploaded image is+ // stamped onto every asset's audit log entry, with the stored+ // filename scoped by asset id (audit-{id}-...).+ Storage::fake();+ $assets = Asset::factory()->count(2)->create();++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'image' => UploadedFile::fake()->image('audit.png'),+ ])+ ->assertRedirect(route('hardware.index'))+ ->assertSessionHas('success');++ foreach ($assets as $asset) {+ $log = Actionlog::where('action_type', 'audit')+ ->where('item_type', Asset::class)+ ->where('item_id', $asset->id)+ ->first();++ $this->assertNotNull($log, "Audit log missing for asset {$asset->id}");+ $this->assertNotEmpty($log->filename, "Audit log filename missing for asset {$asset->id}");+ $this->assertStringStartsWith('audit-'.$asset->id, $log->filename);+ }+ }++ public function test_bulk_audit_rejects_unresolvable_location_before_touching_any_asset(): void+ {+ $assets = Asset::factory()->count(2)->create();+ $originalLocations = $assets->pluck('location_id', 'id');++ $this->actingAs(User::factory()->auditAssets()->create())+ ->post(route('hardware.bulk-audit.store'), [+ 'selected_assets' => $assets->pluck('id')->toArray(),+ 'location_id' => 9999999, // does not exist+ ])+ ->assertRedirect(route('hardware.bulk-audit.show'))+ ->assertSessionHas('error');++ // No audit rows written, no location mutations applied.+ $this->assertSame(0, Actionlog::where('action_type', 'audit')->count());+ foreach ($assets as $asset) {+ $this->assertSame($originalLocations[$asset->id], $asset->fresh()->location_id);+ }+ }+}diff --git a/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.phpindex f2f010d3d3..d91efab5bd 100644--- a/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php+++ b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php@@ -2,23 +2,23 @@namespace Tests\Feature\Assets\Ui;-use App\Models\Actionlog;use App\Models\Asset;-use App\Models\Location;+use App\Models\Company;use App\Models\User;-use Illuminate\Http\UploadedFile;-use Illuminate\Support\Facades\Storage;use PHPUnit\Framework\Attributes\Group;use Tests\TestCase;/**- * Covers the checked-rows bulk-audit flow (Selected Actions >- * Bulk Audit on the assets index). Distinct from the existing- * BulkAuditAssetsTest which covers /hardware/bulkaudit, the barcode-- * scanner quickscan workflow at route `assets.bulkaudit`.+ * Form / access surface of the checked-rows bulk-audit flow (Selected+ * Actions > Bulk Audit on the assets index). Route pair covered here:+ * `hardware.bulk-audit.show` and the dispatcher redirect on+ * `hardware.bulkedit.show`. Submission-side (POST /bulk-audit)+ * behavior lives in BulkAuditSelectedAssetsSubmissionTest to keep+ * either file under Codacy's per-class method-count threshold.*- * Route pair under test: `hardware.bulk-audit.show` /- * `hardware.bulk-audit.store`, controller BulkAssetsController.+ * Distinct from the existing BulkAuditAssetsTest which covers+ * /hardware/bulkaudit, the barcode-scanner quickscan workflow at+ * route `assets.bulkaudit`.*/#[Group('auditing')]class BulkAuditSelectedAssetsTest extends TestCase@@ -54,118 +54,6 @@ class BulkAuditSelectedAssetsTest extends TestCase->assertRedirect(route('hardware.bulk-audit.show'));}- public function test_permission_required_to_submit(): void- {- $this->actingAs(User::factory()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => [1, 2, 3],- ])- ->assertForbidden();- }-- public function test_submitting_without_selected_assets_bounces_back(): void- {- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [])- ->assertRedirect(route('hardware.bulk-audit.show'))- ->assertSessionHas('error');- }-- public function test_bulk_audit_writes_one_audit_actionlog_per_asset(): void- {- $assets = Asset::factory()->count(3)->create();-- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'note' => 'bulk audit test',- ])- ->assertRedirect(route('hardware.index'))- ->assertSessionHas('success');-- foreach ($assets as $asset) {- $this->assertDatabaseHas('action_logs', [- 'action_type' => 'audit',- 'item_type' => Asset::class,- 'item_id' => $asset->id,- 'note' => 'bulk audit test',- ]);- }- }-- public function test_bulk_audit_updates_next_audit_date_when_provided(): void- {- $assets = Asset::factory()->count(2)->create();-- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'next_audit_date' => '2099-01-15',- ])- ->assertRedirect(route('hardware.index'));-- // next_audit_date has an Attribute accessor that returns a- // pre-formatted date string, not a Carbon instance, so we- // check the raw column value instead.- foreach ($assets as $asset) {- $this->assertSame('2099-01-15', $asset->fresh()->getRawOriginal('next_audit_date'));- }- }-- public function test_bulk_audit_updates_asset_location_when_update_location_opt_in_is_checked(): void- {- $location = Location::factory()->create();- $assets = Asset::factory()->count(2)->create();-- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'location_id' => $location->id,- 'update_location' => '1',- ])- ->assertRedirect(route('hardware.index'));-- foreach ($assets as $asset) {- $this->assertSame($location->id, $asset->fresh()->location_id);- }- }-- public function test_bulk_audit_does_not_move_assets_when_update_location_is_unchecked(): void- {- // Provided location_id + no update_location flag should- // record the audit's location on each log entry (as "where- // the audit happened") without touching the asset's actual- // location_id. Matches the API's update_location=1 gate.- $originalLocation = Location::factory()->create();- $auditLocation = Location::factory()->create();- $assets = Asset::factory()->count(2)->create(['location_id' => $originalLocation->id]);-- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'location_id' => $auditLocation->id,- // update_location intentionally omitted (unchecked)- ])- ->assertRedirect(route('hardware.index'));-- foreach ($assets as $asset) {- $fresh = $asset->fresh();- $this->assertSame(- $originalLocation->id,- $fresh->location_id,- "Asset {$asset->id} location must not change when update_location is unchecked.",- );-- // But the audit log DOES record the submitted location.- $log = Actionlog::where('action_type', 'audit')- ->where('item_type', Asset::class)- ->where('item_id', $asset->id)- ->first();- $this->assertNotNull($log);- $this->assertSame($auditLocation->id, (int) $log->location_id);- }- }-public function test_form_prefills_next_audit_date_from_audit_interval(): void{$this->settings->setAuditInterval(6);@@ -190,51 +78,66 @@ class BulkAuditSelectedAssetsTest extends TestCase->assertViewHas('next_audit_date', null);}- public function test_bulk_audit_attaches_uploaded_image_to_every_row(): void+ public function test_location_controls_render_unscoped_when_location_scoping_is_off(): void{- // Matches the API's bulkAudit behavior: one uploaded image is- // stamped onto every asset's audit log entry, with the stored- // filename scoped by asset id (audit-{id}-...).- Storage::fake();- $assets = Asset::factory()->count(2)->create();-+ // FMCS location scoping disabled -> no company-based hiding+ // and no picker scoping regardless of selection distribution.$this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'image' => UploadedFile::fake()->image('audit.png'),- ])- ->assertRedirect(route('hardware.index'))- ->assertSessionHas('success');-- foreach ($assets as $asset) {- $log = Actionlog::where('action_type', 'audit')- ->where('item_type', Asset::class)- ->where('item_id', $asset->id)- ->first();-- $this->assertNotNull($log, "Audit log missing for asset {$asset->id}");- $this->assertNotEmpty($log->filename, "Audit log filename missing for asset {$asset->id}");- $this->assertStringStartsWith('audit-'.$asset->id, $log->filename);- }+ ->withSession(['_old_input' => ['selected_assets' => [1, 2, 3]]])+ ->get(route('hardware.bulk-audit.show'))+ ->assertOk()+ ->assertViewHas('hideLocationFields', false)+ ->assertViewHas('sharedCompanyId', null);}- public function test_bulk_audit_rejects_unresolvable_location_before_touching_any_asset(): void+ public function test_location_controls_scope_to_shared_company_when_selection_is_uniform(): void{- $assets = Asset::factory()->count(2)->create();- $originalLocations = $assets->pluck('location_id', 'id');+ // FMCS location scoping on + every selected asset in the same+ // company -> the picker is scoped so only that company's+ // locations are offered. Uses the real dispatch flow so+ // `old('selected_assets')` populates from the same session+ // mechanism prod uses. Create fixtures BEFORE enabling FMCS+ // so the Asset factory's fmcs_company validation rule doesn't+ // fail with no authenticated user during setUp.+ $company = Company::factory()->create();+ $assets = Asset::factory()->count(3)->create(['company_id' => $company->id]);+ $actor = User::factory()->viewAssets()->auditAssets()->forCompany($company)->create();++ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $response = $this->actingAs($actor)+ ->post(route('hardware.bulkedit.show'), [+ 'bulk_actions' => 'audit',+ 'ids' => $assets->pluck('id')->toArray(),+ ]);- $this->actingAs(User::factory()->auditAssets()->create())- ->post(route('hardware.bulk-audit.store'), [- 'selected_assets' => $assets->pluck('id')->toArray(),- 'location_id' => 9999999, // does not exist- ])- ->assertRedirect(route('hardware.bulk-audit.show'))- ->assertSessionHas('error');-- // No audit rows written, no location mutations applied.- $this->assertSame(0, Actionlog::where('action_type', 'audit')->count());- foreach ($assets as $asset) {- $this->assertSame($originalLocations[$asset->id], $asset->fresh()->location_id);- }+ $this->followRedirects($response)+ ->assertOk()+ ->assertViewHas('hideLocationFields', false)+ ->assertViewHas('sharedCompanyId', $company->id);+ }++ public function test_location_controls_hide_when_selection_spans_multiple_companies(): void+ {+ // FMCS location scoping on + selected assets belong to more+ // than one company -> the picker is hidden entirely since no+ // shared location can legitimately fit all of them.+ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $assetA = Asset::factory()->create(['company_id' => $companyA->id]);+ $assetB = Asset::factory()->create(['company_id' => $companyB->id]);+ $actor = User::factory()->superuser()->create();++ $this->settings->enableScopedLocationsWithFullMultipleCompanySupport();++ $response = $this->actingAs($actor)+ ->post(route('hardware.bulkedit.show'), [+ 'bulk_actions' => 'audit',+ 'ids' => [$assetA->id, $assetB->id],+ ]);++ $this->followRedirects($response)+ ->assertOk()+ ->assertViewHas('hideLocationFields', true)+ ->assertViewHas('sharedCompanyId', null);}}