Skip to content

A free open source IT asset/license management system

Importer: Fixed 18338 - Added pagination and bulk delete

snipec28f06dbec98
diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.php
index 7eefdc87e4..e5b7af6883 100644
--- a/app/Livewire/Importer.php
+++ b/app/Livewire/Importer.php
@@ -7,9 +7,26 @@ use App\Models\Import;
use Illuminate\Support\Facades\Storage;
use Livewire\Attributes\Computed;
use Livewire\Component;
+use Livewire\WithPagination;
class Importer extends Component
{
+ use WithPagination;
+
+ // How many import files to show per page. Not currently user-configurable;
+ // twenty-five is enough to avoid pagination for most installs but small
+ // enough to keep the page manageable when someone's uploaded hundreds.
+ public $perPage = 25;
+
+ // IDs the caller has checkbox-ticked on the current page. Cleared on page
+ // change (see updatedPage) so "Select All" is naturally per-page.
+ public $selectedIds = [];
+
+ // Header select-all checkbox state. Purely visual — the source of truth
+ // for which files get bulk-deleted is $selectedIds. Kept in sync via the
+ // updatedSelectAll hook.
+ public $selectAll = false;
+
public $progress = -1; // upload progress - '-1' means don't show
public $progress_message;
@@ -735,7 +752,7 @@ class Importer extends Component
#[Computed]
public function files()
{
- return Import::orderBy('id', 'desc')->get();
+ return Import::orderBy('id', 'desc')->paginate($this->perPage);
}
#[Computed]
@@ -744,6 +761,99 @@ class Importer extends Component
return Import::find($this->activeFileId);
}
+ /**
+ * True when the current caller may delete the given Import (owner or
+ * superuser). Kept as a method so the view can guard both the row
+ * checkbox and the singular delete button consistently.
+ */
+ public function canDeleteFile(Import $import): bool
+ {
+ return auth()->user()->id === $import->created_by || auth()->user()->isSuperUser();
+ }
+
+ /**
+ * Livewire lifecycle hook: fires when Livewire's built-in $page property
+ * changes (any paginator link click). Selection is a per-page affordance,
+ * so drop it whenever the page changes.
+ */
+ public function updatedPage()
+ {
+ $this->selectedIds = [];
+ $this->selectAll = false;
+ }
+
+ /**
+ * Livewire lifecycle hook for the header "select all" checkbox. When
+ * toggled on, pick every current-page id the caller is allowed to delete;
+ * when toggled off, clear the selection. Rows the caller cannot delete
+ * (not owner, not superuser) are never selectable, so leaving them out
+ * of $selectedIds matches what the disabled row checkboxes convey.
+ */
+ public function updatedSelectAll($value)
+ {
+ if (! $value) {
+ $this->selectedIds = [];
+
+ return;
+ }
+
+ $this->selectedIds = collect($this->files->items())
+ ->filter(fn (Import $import) => $this->canDeleteFile($import))
+ ->pluck('id')
+ ->map(fn ($id) => (string) $id)
+ ->all();
+ }
+
+ /**
+ * Delete every Import in $selectedIds the caller may delete. Rows they
+ * cannot delete are counted separately and reported so the caller knows
+ * why the total may not match what they ticked. File-system delete
+ * failures are swallowed intentionally: the record delete still runs so
+ * a missing/orphaned physical file doesn't lock the import list forever.
+ */
+ public function bulkDestroy()
+ {
+ $this->authorize('import');
+
+ if (empty($this->selectedIds)) {
+ return;
+ }
+
+ $imports = Import::whereIn('id', $this->selectedIds)->get();
+
+ $deleted = 0;
+ $skipped = 0;
+
+ foreach ($imports as $import) {
+ if (! $this->canDeleteFile($import)) {
+ $skipped++;
+
+ continue;
+ }
+
+ Storage::delete('private_uploads/imports/'.$import->file_path);
+ $import->delete();
+ $deleted++;
+ }
+
+ $this->selectedIds = [];
+ $this->selectAll = false;
+ unset($this->files);
+
+ if ($deleted === 0 && $skipped > 0) {
+ $this->message = trans('admin/hardware/message.import.bulk_delete.skipped', ['count' => $skipped]);
+ $this->message_type = 'danger';
+
+ return;
+ }
+
+ $this->message = trans_choice('admin/hardware/message.import.bulk_delete.success', $deleted, ['count' => $deleted]);
+ if ($skipped > 0) {
+ $this->message .= ' '.trans('admin/hardware/message.import.bulk_delete.skipped', ['count' => $skipped]);
+ }
+ $this->message_type = 'success';
+ }
+
public function render()
{
return view('livewire.importer')
diff --git a/resources/lang/en-US/admin/hardware/message.php b/resources/lang/en-US/admin/hardware/message.php
index f33e37be08..a75c07267e 100644
--- a/resources/lang/en-US/admin/hardware/message.php
+++ b/resources/lang/en-US/admin/hardware/message.php
@@ -77,6 +77,16 @@ return [
'header_row_has_malformed_characters' => 'One or more attributes in the header row contain malformed UTF-8 characters',
'content_row_has_malformed_characters' => 'One or more attributes in the first row of content contain malformed UTF-8 characters',
'transliterate_failure' => 'Transliteration from :encoding to UTF-8 failed due to invalid characters in input',
+ 'bulk_delete' => [
+ 'button' => 'Delete Selected (:count)',
+ 'confirm_title' => 'Delete selected import files?',
+ 'confirm_body' => 'You are about to permanently delete :count import file(s). This cannot be undone.',
+ 'confirm_button' => 'Delete',
+ 'success' => 'Import file deleted successfully.|:count import files were deleted successfully.',
+ 'skipped' => ':count file(s) were skipped because you do not have permission to delete them.',
+ 'select_all' => 'Select all files on this page',
+ 'select_row' => 'Select :file for bulk delete',
+ ],
],
'delete' => [
diff --git a/resources/views/livewire/importer.blade.php b/resources/views/livewire/importer.blade.php
index b7a43b1545..7a77eed71a 100644
--- a/resources/views/livewire/importer.blade.php
+++ b/resources/views/livewire/importer.blade.php
@@ -106,12 +106,36 @@
</div>
<div class="row">
<div class="col-md-12 table-responsive" style="padding-top: 30px;">
+
+ @if (count($selectedIds) > 0)
+ <div class="row" style="padding-bottom: 10px;">
+ <div class="col-md-12">
+ <button type="button"
+ class="btn btn-danger"
+ data-toggle="modal"
+ data-target="#bulkDeleteImportsModal">
+ <i class="fas fa-trash" aria-hidden="true"></i>
+ {{ trans('admin/hardware/message.import.bulk_delete.button', ['count' => count($selectedIds)]) }}
+ </button>
+ </div>
+ </div>
+ @endif
+
<table data-id-table="upload-table"
data-side-pagination="client"
id="upload-table"
class="col-md-12 table table-striped snipe-table">
<tr>
+ <th class="col-md-1">
+ <label class="sr-only" for="importsSelectAll">
+ {{ trans('admin/hardware/message.import.bulk_delete.select_all') }}
+ </label>
+ <input type="checkbox"
+ id="importsSelectAll"
+ wire:model.live="selectAll"
+ aria-label="{{ trans('admin/hardware/message.import.bulk_delete.select_all') }}">
+ </th>
<th>
{{ trans('general.file_name') }}
</th>
@@ -133,6 +157,17 @@
@foreach($this->files as $currentFile)
<tr style="{{ ($this->activeFile && ($currentFile->id == $this->activeFile->id)) ? 'font-weight: bold' : '' }}" class="{{ ($this->activeFile && ($currentFile->id == $this->activeFile->id)) ? '' : '' }}">
+ <td>
+ <label class="sr-only" for="import-row-{{ $currentFile->id }}">
+ {{ trans('admin/hardware/message.import.bulk_delete.select_row', ['file' => $currentFile->file_path]) }}
+ </label>
+ <input type="checkbox"
+ id="import-row-{{ $currentFile->id }}"
+ wire:model.live="selectedIds"
+ value="{{ $currentFile->id }}"
+ @disabled(! $this->canDeleteFile($currentFile))
+ aria-label="{{ trans('admin/hardware/message.import.bulk_delete.select_row', ['file' => $currentFile->file_path]) }}">
+ </td>
<td>
@if ((auth()->user()->id == $currentFile->adminuser?->id) || (auth()->user()->isSuperUser()))
@@ -180,7 +215,7 @@
@if( $currentFile && $this->activeFile && ($currentFile->id == $this->activeFile->id))
<tr>
- <td colspan="5">
+ <td colspan="6">
<div class="form-group">
@@ -338,6 +373,14 @@
@endif
@endforeach
</table>
+
+ @if ($this->files->hasPages())
+ <div class="row">
+ <div class="col-md-12">
+ {{ $this->files->links() }}
+ </div>
+ </div>
+ @endif
</div>
</div>
</div>
@@ -349,6 +392,45 @@
</div>
</div>
+
+ {{-- Bulk delete confirmation modal. Kept as a Livewire-driven Bootstrap
+ modal (not the shared confirm-action partial, which POSTs a form)
+ so the confirm button can fire wire:click and let Livewire handle
+ the delete without a page reload. --}}
+ <div wire:ignore.self class="modal fade" id="bulkDeleteImportsModal" tabindex="-1" role="dialog" aria-labelledby="bulkDeleteImportsModalLabel" aria-hidden="true">
+ <div class="modal-dialog" role="document">
+ <div class="modal-content">
+ <div class="modal-header">
+ <button type="button" class="close" data-dismiss="modal" aria-label="{{ trans('button.cancel') }}">
+ <span aria-hidden="true">&times;</span>
+ </button>
+ <h4 class="modal-title" id="bulkDeleteImportsModalLabel">
+ {{ trans('admin/hardware/message.import.bulk_delete.confirm_title') }}
+ </h4>
+ </div>
+ <div class="modal-body">
+ <p>
+ {{ trans('admin/hardware/message.import.bulk_delete.confirm_body', ['count' => count($selectedIds)]) }}
+ </p>
+ @if (count($selectedIds) > 0)
+ <ul>
+ @foreach ($this->files as $currentFile)
+ @if (in_array((string) $currentFile->id, $selectedIds, true) || in_array($currentFile->id, $selectedIds, true))
+ <li>{{ $currentFile->file_path }}</li>
+ @endif
+ @endforeach
+ </ul>
+ @endif
+ </div>
+ <div class="modal-footer">
+ <a href="#" class="pull-left" data-dismiss="modal">{{ trans('button.cancel') }}</a>
+ <button type="button" class="btn btn-danger" wire:click="bulkDestroy" data-dismiss="modal">
+ {{ trans('admin/hardware/message.import.bulk_delete.confirm_button') }}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
</div>
@script
<script>
diff --git a/tests/Feature/Livewire/ImporterTest.php b/tests/Feature/Livewire/ImporterTest.php
index d7dd82c0c2..1b84058451 100644
--- a/tests/Feature/Livewire/ImporterTest.php
+++ b/tests/Feature/Livewire/ImporterTest.php
@@ -3,7 +3,9 @@
namespace Tests\Feature\Livewire;
use App\Livewire\Importer;
+use App\Models\Import;
use App\Models\User;
+use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;
@@ -22,4 +24,146 @@ class ImporterTest extends TestCase
->test(Importer::class)
->assertStatus(403);
}
+
+ public function test_bulk_deletes_owned_imports()
+ {
+ Storage::fake();
+ $user = User::factory()->canImport()->create();
+ $imports = Import::factory()->count(3)->create(['created_by' => $user->id]);
+
+ Livewire::actingAs($user)
+ ->test(Importer::class)
+ ->set('selectedIds', $imports->pluck('id')->map(fn ($id) => (string) $id)->all())
+ ->call('bulkDestroy')
+ ->assertSet('message_type', 'success');
+
+ foreach ($imports as $import) {
+ $this->assertDatabaseMissing('imports', ['id' => $import->id]);
+ }
+ }
+
+ public function test_bulk_destroy_skips_imports_the_caller_does_not_own()
+ {
+ Storage::fake();
+ $me = User::factory()->canImport()->create();
+ $someoneElse = User::factory()->canImport()->create();
+
+ $mine = Import::factory()->create(['created_by' => $me->id]);
+ $theirs = Import::factory()->create(['created_by' => $someoneElse->id]);
+
+ Livewire::actingAs($me)
+ ->test(Importer::class)
+ ->set('selectedIds', [(string) $mine->id, (string) $theirs->id])
+ ->call('bulkDestroy')
+ ->assertSet('message_type', 'success');
+
+ $this->assertDatabaseMissing('imports', ['id' => $mine->id]);
+ $this->assertDatabaseHas('imports', ['id' => $theirs->id]);
+ }
+
+ public function test_bulk_destroy_all_denied_produces_error_message()
+ {
+ Storage::fake();
+ $me = User::factory()->canImport()->create();
+ $someoneElse = User::factory()->canImport()->create();
+
+ $theirs = Import::factory()->count(2)->create(['created_by' => $someoneElse->id]);
+
+ Livewire::actingAs($me)
+ ->test(Importer::class)
+ ->set('selectedIds', $theirs->pluck('id')->map(fn ($id) => (string) $id)->all())
+ ->call('bulkDestroy')
+ ->assertSet('message_type', 'danger');
+
+ // Neither import was deleted.
+ foreach ($theirs as $import) {
+ $this->assertDatabaseHas('imports', ['id' => $import->id]);
+ }
+ }
+
+ public function test_superuser_can_bulk_delete_anyone_elses_imports()
+ {
+ Storage::fake();
+ $superuser = User::factory()->superuser()->create();
+ $owner = User::factory()->canImport()->create();
+ $imports = Import::factory()->count(2)->create(['created_by' => $owner->id]);
+
+ Livewire::actingAs($superuser)
+ ->test(Importer::class)
+ ->set('selectedIds', $imports->pluck('id')->map(fn ($id) => (string) $id)->all())
+ ->call('bulkDestroy')
+ ->assertSet('message_type', 'success');
+
+ foreach ($imports as $import) {
+ $this->assertDatabaseMissing('imports', ['id' => $import->id]);
+ }
+ }
+
+ public function test_bulk_destroy_with_no_selection_does_nothing()
+ {
+ Storage::fake();
+ $user = User::factory()->canImport()->create();
+ Import::factory()->create(['created_by' => $user->id]);
+
+ Livewire::actingAs($user)
+ ->test(Importer::class)
+ ->call('bulkDestroy')
+ ->assertSet('message', null);
+
+ $this->assertDatabaseCount('imports', 1);
+ }
+
+ public function test_files_paginate_by_per_page()
+ {
+ $user = User::factory()->canImport()->create();
+ Import::factory()->count(30)->create(['created_by' => $user->id]);
+
+ $component = Livewire::actingAs($user)->test(Importer::class);
+
+ // Default $perPage = 25; 30 imports means 25 on page 1, 5 on page 2.
+ $this->assertCount(25, $component->instance()->files->items());
+ $this->assertSame(30, $component->instance()->files->total());
+ $this->assertTrue($component->instance()->files->hasPages());
+ }
+
+ public function test_select_all_selects_only_current_page_deletable_rows()
+ {
+ $me = User::factory()->canImport()->create();
+ $someoneElse = User::factory()->canImport()->create();
+
+ // 5 mine + 3 theirs = 8 imports on page 1 (fits under the 25 default).
+ $mine = Import::factory()->count(5)->create(['created_by' => $me->id]);
+ Import::factory()->count(3)->create(['created_by' => $someoneElse->id]);
+
+ $component = Livewire::actingAs($me)
+ ->test(Importer::class)
+ ->set('selectAll', true);
+
+ // Only the 5 the caller can delete are picked up.
+ $selected = $component->get('selectedIds');
+ $this->assertCount(5, $selected);
+ $this->assertEquals(
+ $mine->pluck('id')->sort()->values()->all(),
+ collect($selected)->map(fn ($id) => (int) $id)->sort()->values()->all()
+ );
+ }
+
+ public function test_changing_page_clears_selection()
+ {
+ $user = User::factory()->canImport()->create();
+ Import::factory()->count(30)->create(['created_by' => $user->id]);
+
+ $component = Livewire::actingAs($user)
+ ->test(Importer::class)
+ ->set('selectAll', true);
+
+ $this->assertNotEmpty($component->get('selectedIds'));
+
+ // Livewire's WithPagination exposes a setPage() method; calling it
+ // triggers the updatedPage hook where we clear selection.
+ $component->call('setPage', 2);
+
+ $this->assertSame([], $component->get('selectedIds'));
+ $this->assertFalse($component->get('selectAll'));
+ }
}