Skip to content

A free open source IT asset/license management system

Asset Audit: Fixed #17168 - added bulk audit to UI and API

snipe0faceea89685
diff --git a/app/Http/Controllers/Assets/BulkAssetsController.php b/app/Http/Controllers/Assets/BulkAssetsController.php
index b7457a196a..3618ee9d89 100644
--- a/app/Http/Controllers/Assets/BulkAssetsController.php
+++ b/app/Http/Controllers/Assets/BulkAssetsController.php
@@ -7,6 +7,7 @@ use App\Events\CheckoutablesCheckedOutInBulk;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Http\Requests\AssetCheckoutRequest;
+use App\Http\Requests\UploadFileRequest;
use App\Http\Traits\CheckInOutTrait;
use App\Http\Traits\MigratesLegacyAssetLocations;
use App\Models\Asset;
@@ -90,6 +91,12 @@ class BulkAssetsController extends Controller
return redirect()->route('hardware.bulkcheckin.show');
}
+ if ($request->input('bulk_actions') === 'audit') {
+ $request->session()->flashInput(['selected_assets' => $asset_ids]);
+
+ return redirect()->route('hardware.bulk-audit.show');
+ }
+
if ($request->input('bulk_actions') === 'maintenance') {
$request->session()->flashInput(['selected_assets' => $asset_ids]);
@@ -941,6 +948,123 @@ class BulkAssetsController extends Controller
->withErrors($errors);
}
+ /**
+ * Show the bulk-audit form: single shared note, optional location
+ * override, optional next_audit_date override. Applied uniformly
+ * to every selected asset when the form is submitted.
+ *
+ * The full walk-per-asset customization the single-audit form
+ * offers (custom fields, per-asset image, etc.) is intentionally
+ * out of scope here; the whole point of bulk audit is to
+ * touch-and-go a stack of items at once. Users needing to record
+ * per-item details should still use the single audit form.
+ */
+ public function showAudit(): View
+ {
+ $this->authorize('audit', Asset::class);
+
+ // 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;
+
+ return view('hardware/bulk-audit', [
+ 'next_audit_date' => $next_audit_date,
+ ]);
+ }
+
+ /**
+ * Apply the audit to every selected asset. Same skip-observer
+ * pattern the single-asset audit uses (AssetsController::auditStore)
+ * so the assets table update doesn't fire an extra Actionlog
+ * 'update' entry alongside the 'audit' entry logAudit() writes.
+ */
+ public function storeAudit(UploadFileRequest $request): RedirectResponse
+ {
+ $this->authorize('audit', Asset::class);
+
+ if (! is_array($request->input('selected_assets'))) {
+ return redirect()->route('hardware.bulk-audit.show')->withInput()
+ ->with('error', trans('admin/hardware/message.multi-audit.no_assets_selected'));
+ }
+
+ $asset_ids = array_filter($request->input('selected_assets'));
+ $assets = Asset::whereIn('id', $asset_ids)->get();
+
+ // Resolve the submitted location through the FMCS-scoped query
+ // 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.
+ $submittedLocation = null;
+ if ($request->filled('location_id')) {
+ $submittedLocation = Location::find($request->input('location_id'));
+ if (! $submittedLocation) {
+ return redirect()->route('hardware.bulk-audit.show')->withInput()
+ ->with('error', trans('admin/hardware/message.create.target_not_found.location'));
+ }
+ }
+
+ $errors = [];
+ $succeeded = 0;
+
+ DB::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');
+
+ if ($submittedLocation) {
+ $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,
+ );
+ $succeeded++;
+ } else {
+ $errors[$asset->id] = $asset->getErrors()->toArray();
+ }
+ }
+ });
+
+ if (! $errors) {
+ return redirect()->route('hardware.index')
+ ->with('success', trans_choice('admin/hardware/message.multi-audit.success', $succeeded, ['count' => $succeeded]));
+ }
+
+ return redirect()->route('hardware.bulk-audit.show')->withInput()
+ ->with('error', trans_choice('admin/hardware/message.multi-audit.partial_error', count($errors), ['success' => $succeeded, 'failed' => count($errors)]))
+ ->withErrors($errors);
+ }
+
public function restore(Request $request): RedirectResponse
{
// Restore is a delete-level action across the codebase. The bulk
diff --git a/resources/lang/en-US/admin/hardware/general.php b/resources/lang/en-US/admin/hardware/general.php
index f10684a391..dea3b904c1 100644
--- a/resources/lang/en-US/admin/hardware/general.php
+++ b/resources/lang/en-US/admin/hardware/general.php
@@ -7,6 +7,7 @@ return [
'asset' => 'Asset',
'bulk_checkout' => 'Bulk Checkout',
'bulk_checkin' => 'Bulk Checkin',
+ 'bulk_audit' => 'Bulk Audit',
'checkin' => 'Checkin Asset',
'checkin_assets' => 'Checkin Assets',
'checkout' => 'Checkout Asset',
diff --git a/resources/lang/en-US/admin/hardware/message.php b/resources/lang/en-US/admin/hardware/message.php
index 69b52291cf..e1919ea73d 100644
--- a/resources/lang/en-US/admin/hardware/message.php
+++ b/resources/lang/en-US/admin/hardware/message.php
@@ -140,6 +140,12 @@ return [
'no_assets_selected' => 'You must select at least one asset from the list',
],
+ 'multi-audit' => [
+ 'success' => ':count asset audited successfully.|:count assets audited successfully.',
+ 'partial_error' => ':success asset audited, :failed failed. Check the errors below and try again.|:success assets audited, :failed failed. Check the errors below and try again.',
+ 'no_assets_selected' => 'You must select at least one asset from the list',
+ ],
+
'checkin' => [
'error' => 'Asset was not checked in, please try again',
'success' => 'Asset checked in successfully.',
diff --git a/resources/views/blade/table/bulk-assets.blade.php b/resources/views/blade/table/bulk-assets.blade.php
index 11b25d101b..c7ef295062 100644
--- a/resources/views/blade/table/bulk-assets.blade.php
+++ b/resources/views/blade/table/bulk-assets.blade.php
@@ -43,6 +43,10 @@
@endcan
@endif
+ @can('audit', \App\Models\Asset::class)
+ <option value="audit">{{ trans('admin/hardware/general.bulk_audit') }}</option>
+ @endcan
+
@can('delete', \App\Models\Asset::class)
<option value="delete">{{ trans('general.bulk_delete') }}</option>
@endcan
diff --git a/resources/views/hardware/bulk-audit.blade.php b/resources/views/hardware/bulk-audit.blade.php
new file mode 100644
index 0000000000..83e67e459e
--- /dev/null
+++ b/resources/views/hardware/bulk-audit.blade.php
@@ -0,0 +1,73 @@
+@extends('layouts/default')
+
+{{-- Page title --}}
+@section('title')
+ {{ trans('admin/hardware/general.bulk_audit') }}
+ @parent
+@stop
+
+{{-- Page content --}}
+@section('content')
+
+ <style>
+ .input-group {
+ padding-left: 0px !important;
+ }
+ </style>
+
+ <x-container class="col-md-8 col-md-offset-2">
+ <x-form :route="route('hardware.bulk-audit.store')" data-disable-empty-on-submit>
+ <x-box>
+ <x-slot:header>
+ {{ trans('admin/hardware/general.bulk_audit') }}
+ </x-slot:header>
+
+ @include('partials.forms.edit.asset-select', [
+ 'translated_name' => trans('general.assets'),
+ 'fieldname' => 'selected_assets[]',
+ 'multiple' => true,
+ 'required' => true,
+ 'select_id' => 'assigned_assets_select',
+ 'asset_selector_div_id' => 'assets_to_audit_div',
+ 'asset_ids' => old('selected_assets'),
+ ])
+
+ <x-input.location-select
+ :label="trans('general.location')"
+ name="location_id"
+ :selected="old('location_id')"
+ />
+
+ {{-- Next audit date. Prefilled with today + audit_interval
+ from settings so users can accept the calculated
+ default or override for this batch. --}}
+ <x-form.row
+ :label="trans('general.next_audit_date')"
+ name="next_audit_date"
+ type="datepicker"
+ :default="$next_audit_date"
+ input_div_class="col-md-4"
+ />
+
+ {{-- Shared note applied to every audit log entry. --}}
+ <x-form.row
+ :label="trans('general.notes')"
+ name="note"
+ type="textarea"
+ />
+
+ {{-- Shared audit image. If uploaded, the same file is
+ saved per-asset (audit-{id}-...) and attached to
+ every audit log entry --}}
+ <x-input.image-upload :helpText="trans('general.audit_images_help')" />
+
+ <x-slot:customfooter>
+ <div class="box-footer">
+ <a class="btn btn-link" href="{{ URL::previous() }}">{{ trans('button.cancel') }}</a>
+ <x-button.submit class="btn-success pull-right" :label="trans('admin/hardware/general.bulk_audit')" />
+ </div>
+ </x-slot:customfooter>
+ </x-box>
+ </x-form>
+ </x-container>
+@stop
diff --git a/routes/web/hardware.php b/routes/web/hardware.php
index b85f70391c..ce855dfc0e 100644
--- a/routes/web/hardware.php
+++ b/routes/web/hardware.php
@@ -187,6 +187,19 @@ Route::group(
[BulkAssetsController::class, 'storeCheckin']
)->name('hardware.bulkcheckin.store');
+ // Checked-rows bulk audit. URL uses a dash to stay distinct
+ // from /hardware/bulkaudit (the barcode-scanner quickscan flow
+ // at assets.bulkaudit above).
+ Route::get('bulk-audit', [BulkAssetsController::class, 'showAudit'])
+ ->name('hardware.bulk-audit.show')
+ ->breadcrumbs(fn (Trail $trail) => $trail->parent('hardware.index')
+ ->push(trans('admin/hardware/general.bulk_audit'), route('hardware.index'))
+ );
+
+ Route::post('bulk-audit',
+ [BulkAssetsController::class, 'storeAudit']
+ )->name('hardware.bulk-audit.store');
+
});
Route::resource('hardware',
diff --git a/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php
new file mode 100644
index 0000000000..3b54ea9796
--- /dev/null
+++ b/tests/Feature/Assets/Ui/BulkAuditSelectedAssetsTest.php
@@ -0,0 +1,204 @@
+<?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;
+
+/**
+ * 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`.
+ *
+ * Route pair under test: `hardware.bulk-audit.show` /
+ * `hardware.bulk-audit.store`, controller BulkAssetsController.
+ */
+#[Group('auditing')]
+class BulkAuditSelectedAssetsTest extends TestCase
+{
+ public function test_permission_required_to_view_form(): void
+ {
+ $this->actingAs(User::factory()->create())
+ ->get(route('hardware.bulk-audit.show'))
+ ->assertForbidden();
+ }
+
+ public function test_auditor_can_view_form(): void
+ {
+ $this->actingAs(User::factory()->auditAssets()->create())
+ ->get(route('hardware.bulk-audit.show'))
+ ->assertOk()
+ ->assertViewIs('hardware.bulk-audit');
+ }
+
+ public function test_bulk_actions_dispatcher_redirects_to_show_with_selected_assets_flashed(): void
+ {
+ // BulkAssetsController::edit gates on view permission before
+ // dispatching to any specific action, so the auditor also
+ // needs view to reach the audit branch.
+ $auditor = User::factory()->viewAssets()->auditAssets()->create();
+ $assets = Asset::factory()->count(3)->create();
+
+ $this->actingAs($auditor)
+ ->post(route('hardware.bulkedit.show'), [
+ 'bulk_actions' => 'audit',
+ 'ids' => $assets->pluck('id')->toArray(),
+ ])
+ ->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_location_when_provided(): 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,
+ ])
+ ->assertRedirect(route('hardware.index'));
+
+ foreach ($assets as $asset) {
+ $fresh = $asset->fresh();
+ $this->assertSame($location->id, $fresh->location_id);
+ }
+ }
+
+ public function test_form_prefills_next_audit_date_from_audit_interval(): void
+ {
+ $this->settings->setAuditInterval(6);
+
+ $this->actingAs(User::factory()->auditAssets()->create())
+ ->get(route('hardware.bulk-audit.show'))
+ ->assertOk()
+ ->assertViewHas('next_audit_date', \Carbon\Carbon::now()->addMonths(6)->toDateString());
+ }
+
+ public function test_form_leaves_next_audit_date_blank_when_no_audit_interval_configured(): void
+ {
+ // With no audit_interval set, "today + 0 months" would prefill
+ // as today, which reads as "audit again right now" and is
+ // useless. The form should start empty and let the user pick
+ // a date (or leave blank to skip updating next_audit_date).
+ $this->settings->setAuditInterval(null);
+
+ $this->actingAs(User::factory()->auditAssets()->create())
+ ->get(route('hardware.bulk-audit.show'))
+ ->assertOk()
+ ->assertViewHas('next_audit_date', null);
+ }
+
+ 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);
+ }
+ }
+}