A free open source IT asset/license management system
Move some of the sample CSVs to the demo for processing
snipeeda206a16a97
diff --git a/app/Http/Controllers/Api/ImportController.php b/app/Http/Controllers/Api/ImportController.phpindex 8b5541d129..a283c1cbc2 100644--- a/app/Http/Controllers/Api/ImportController.php+++ b/app/Http/Controllers/Api/ImportController.php@@ -217,10 +217,10 @@ class ImportController extends Controller{$this->authorize('import');- // Demo mode: same "feature disabled" gate as store(). Uploading- // was blocked there but processing an existing (seeded or leftover)- // Import row would still mutate the demo DB - close the loophole.- if (config('app.lock_passwords')) {+ // Demo mode: uploads stay blocked at store(), but superadmins can+ // still process the seeded sample imports so the demo shows off+ // the flow end to end.+ if (config('app.lock_passwords') && ! auth()->user()->isSuperUser()) {return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.feature_disabled')), 422);}@@ -248,9 +248,6 @@ class ImportController extends Controller$redirectTo = 'hardware.index';switch ($request->input('import-type')) {case 'asset':- $model_perms = 'App\Models\Asset';- $redirectTo = 'hardware.index';- break;case 'assetHistory':$model_perms = 'App\Models\Asset';$redirectTo = 'hardware.index';diff --git a/app/Livewire/Importer.php b/app/Livewire/Importer.phpindex c2a910ab76..5c4532de3d 100644--- a/app/Livewire/Importer.php+++ b/app/Livewire/Importer.php@@ -853,10 +853,13 @@ class Importer extends Component*/public function startProcessing(bool $withBackup = false): void{- // Demo mode: the actual per-slice POSTs would 422 out of- // Api\ImportController::process() anyway, but bail here so we- // don't even flip the UI into processing mode.- if (config('app.lock_passwords')) {+ // Demo mode: uploads are blocked at Api\ImportController::store,+ // but a demo superadmin should still be able to run the seeded+ // sample imports so the end-to-end flow is exercisable in the+ // demo. Non-superadmins get the same "feature disabled" bail as+ // before. Api\ImportController::process() applies the matching+ // gate on the per-slice POSTs.+ if (config('app.lock_passwords') && ! auth()->user()->isSuperUser()) {$this->message = trans('general.feature_disabled');$this->message_type = 'danger';diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.phpindex 01d88a5648..2214937d02 100644--- a/database/seeders/DatabaseSeeder.php+++ b/database/seeders/DatabaseSeeder.php@@ -84,7 +84,8 @@ class DatabaseSeeder extends SeederModel::reguard();DB::statement('SET FOREIGN_KEY_CHECKS=1');- DB::table('imports')->truncate();+ $this->call(ImportSeeder::class);+ $this->reportMemory('after ImportSeeder');DB::table('requested_assets')->truncate();$this->reportMemory('DatabaseSeeder end');diff --git a/database/seeders/ImportSeeder.php b/database/seeders/ImportSeeder.phpnew file mode 100644index 0000000000..2b01972c74--- /dev/null+++ b/database/seeders/ImportSeeder.php@@ -0,0 +1,90 @@+<?php++namespace Database\Seeders;++use App\Models\Import;+use App\Models\User;+use Illuminate\Database\Seeder;+use League\Csv\Reader;++class ImportSeeder extends Seeder+{+ /**+ * Copy a handful of canonical sample CSVs from sample_csvs/ into the+ * importer's storage directory and register Import rows for them so+ * demo/dev users can exercise the import flow end to end without+ * uploading anything themselves. Runs on `db:seed` and is also safe+ * to invoke standalone via `db:seed --class=ImportSeeder`. On the+ * hosted demo, the reset pipeline calls `db:seed` after paving the+ * DB, so this re-seeds automatically without any extra wiring.+ */+ public function run(): void+ {+ Import::truncate();++ $samplesDir = base_path('sample_csvs');++ if (! is_dir($samplesDir)) {+ $this->command?->warn("Sample CSV directory not found at $samplesDir, skipping.");++ return;+ }++ $admin = User::where('permissions->superuser', '1')->first()+ ?? User::factory()->firstAdmin()->create();++ $importsDir = config('app.private_uploads').'/imports';++ if (! is_dir($importsDir)) {+ mkdir($importsDir, 0755, true);+ }++ // The subset a demo user is most likely to try. Keeping the list+ // short so the imports index doesn't become noisy after repeated+ // resets. Ordering is a suggestion, not a dependency chain.+ $samples = [+ 'users-sample.csv',+ 'assets-sample.csv',+ 'licenses-sample.csv',+ 'accessories-sample.csv',+ 'consumables-sample.csv',+ ];++ foreach ($samples as $sample) {+ $source = $samplesDir.'/'.$sample;++ if (! is_file($source)) {+ continue;+ }++ // Fixed filename so re-runs overwrite in place instead of+ // accumulating dated dupes on disk. The DB row is idempotent+ // via the truncate at the top.+ $storedName = 'demo-'.$sample;+ $destination = $importsDir.'/'.$storedName;++ copy($source, $destination);++ try {+ $reader = Reader::createFromPath($destination);+ $headerRow = $reader->nth(0);+ $firstRow = $reader->nth(1);+ } catch (\Throwable) {+ $this->command?->warn("Could not parse $sample, skipping.");++ continue;+ }++ // Explicit set-and-save because Import has no $fillable, so+ // mass-assignment helpers (updateOrCreate / firstOrNew) throw.+ $import = new Import;+ $import->file_path = $storedName;+ $import->name = $storedName;+ $import->filesize = filesize($destination);+ $import->header_row = $headerRow;+ $import->first_row = $firstRow;+ $import->created_by = $admin->id;+ $import->save();+ }+ }+}diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.phpindex 8e0ffd385a..f9e63d659e 100644--- a/resources/lang/en-US/general.php+++ b/resources/lang/en-US/general.php@@ -385,6 +385,7 @@ return ['open_new_window' => 'Open this file in a new window','file_upload_success' => 'File upload success!','no_files_uploaded' => 'No files were uploaded.',+ 'no_import_files_yet' => 'No import files yet. Upload a CSV using the panel on the right to get started.','token_expired' => 'Your form session has expired. Please try again.','login_enabled' => 'Login Enabled','login_disabled' => 'Login Disabled',diff --git a/resources/views/livewire/importer.blade.php b/resources/views/livewire/importer.blade.phpindex d8a5253bb7..6422ff935a 100644--- a/resources/views/livewire/importer.blade.php+++ b/resources/views/livewire/importer.blade.php@@ -73,6 +73,18 @@<div class="row"><div class="col-md-12 table-responsive">+ @if ($this->files->isEmpty())+ {{-- Nothing to list yet. Hide the whole+ table so an empty <thead> doesn't+ render as a stub, and point the user+ at the upload widget in the sidebar. --}}+ <div class="text-center text-muted" style="padding: 40px 20px;">+ <p style="font-size: 16px; margin-bottom: 0;">+ {{ trans('general.no_import_files_yet') }}+ </p>+ </div>+ @else+@if (count($selectedIds) > 0)<div class="row" style="padding-bottom: 10px;"><div class="col-md-12">@@ -199,6 +211,8 @@</div></div>@endif++ @endif {{-- $this->files->isEmpty() --}}</div></div></div>diff --git a/tests/Feature/Assets/Ui/ImportAssetHistoryTest.php b/tests/Feature/Assets/Ui/ImportAssetHistoryTest.phpindex fa5a0144b1..e59b114a3b 100644--- a/tests/Feature/Assets/Ui/ImportAssetHistoryTest.php+++ b/tests/Feature/Assets/Ui/ImportAssetHistoryTest.php@@ -28,15 +28,16 @@ class ImportAssetHistoryTest extends TestCase->assertStatus(405);}- public function test_process_endpoint_blocked_in_demo_mode(): void+ public function test_process_endpoint_blocked_in_demo_mode_for_non_superadmin(): void{- // Uploads were already blocked at Api\ImportController::store,- // but the process endpoint would still let a demo user mutate the- // DB via any seeded / leftover Import row. The lock_passwords- // gate here closes that loophole.+ // Uploads are blocked at Api\ImportController::store, and non-+ // superadmins are also blocked from processing so they can't+ // mutate the demo DB via any leftover Import row. Superadmins+ // are allowed through so they can exercise the seeded demo+ // samples end to end (see companion test below).config(['app.lock_passwords' => true]);- $actor = User::factory()->canImport()->superuser()->create();+ $actor = User::factory()->canImport()->create();$import = Import::factory()->assetHistory()->create(['created_by' => $actor->id]);$this->actingAsForApi($actor);@@ -46,6 +47,32 @@ class ImportAssetHistoryTest extends TestCase)->assertStatus(422);}+ public function test_process_endpoint_allowed_in_demo_mode_for_superadmin(): void+ {+ // Superadmins bypass the demo-mode gate on process() so the+ // seeded sample CSVs (populated by snipeit:demo-settings) can+ // actually be run against the demo DB. Without a real CSV on+ // disk the import will error out below the gate, so this test+ // just proves the gate itself lets the superadmin through+ // (any status other than 422 "feature disabled" is fine).+ config(['app.lock_passwords' => true]);++ $actor = User::factory()->canImport()->superuser()->create();+ $import = Import::factory()->assetHistory()->create(['created_by' => $actor->id]);++ $this->actingAsForApi($actor);+ $response = $this->postJson(+ route('api.imports.importFile', ['import' => $import->id]),+ ['import-type' => 'assetHistory', 'import' => $import->id],+ );++ $this->assertNotEquals(+ trans('general.feature_disabled'),+ $response->json('messages'),+ 'Superadmin should not hit the demo-mode gate on process().',+ );+ }+public function test_asset_history_import_requires_import_permission(): void{$actor = User::factory()->create();diff --git a/tests/Feature/Livewire/ImporterTest.php b/tests/Feature/Livewire/ImporterTest.phpindex 9aa6e94a72..e77b2889b2 100644--- a/tests/Feature/Livewire/ImporterTest.php+++ b/tests/Feature/Livewire/ImporterTest.php@@ -508,12 +508,13 @@ class ImporterTest extends TestCase});}- public function test_demo_mode_blocks_start_processing(): void+ public function test_demo_mode_blocks_start_processing_for_non_superadmin(): void{// With lock_passwords set the Process button on the wizard is// disabled in the blade, but a hand-crafted Livewire call would// still fire the action - guard it server-side so the modal can't- // flip into processing mode either.+ // flip into processing mode either. Superadmins bypass this gate+ // in demo mode so the seeded demo imports can actually be run.config(['app.lock_passwords' => true]);$user = User::factory()->canImport()->create();@@ -525,6 +526,18 @@ class ImporterTest extends TestCase->assertSet('message_type', 'danger');}+ public function test_demo_mode_allows_start_processing_for_superadmin(): void+ {+ config(['app.lock_passwords' => true]);++ $user = User::factory()->canImport()->superuser()->create();++ Livewire::actingAs($user)+ ->test(Importer::class)+ ->call('startProcessing')+ ->assertSet('processing', true);+ }+public function test_demo_mode_blocks_destroy(): void{config(['app.lock_passwords' => true]);diff --git a/tests/Feature/Seeders/ImportSeederTest.php b/tests/Feature/Seeders/ImportSeederTest.phpnew file mode 100644index 0000000000..16692a9048--- /dev/null+++ b/tests/Feature/Seeders/ImportSeederTest.php@@ -0,0 +1,72 @@+<?php++namespace Tests\Feature\Seeders;++use App\Models\Import;+use Database\Seeders\ImportSeeder;+use Tests\TestCase;++class ImportSeederTest extends TestCase+{+ private array $seededPaths = [];++ protected function setUp(): void+ {+ parent::setUp();++ if (! is_dir(base_path('sample_csvs'))) {+ $this->markTestSkipped('sample_csvs directory is not present on this checkout.');+ }+ }++ protected function tearDown(): void+ {+ // The seeder writes real files via copy(); clean up so nothing+ // leaks between tests. DB rows go with the transaction.+ foreach ($this->seededPaths as $path) {+ @unlink($path);+ }++ parent::tearDown();+ }++ private function trackSeededFiles(): void+ {+ $importsDir = config('app.private_uploads').'/imports';+ foreach (Import::where('file_path', 'like', 'demo-%.csv')->get() as $import) {+ $this->seededPaths[] = $importsDir.'/'.$import->file_path;+ }+ }++ public function test_seeds_a_handful_of_sample_imports(): void+ {+ $this->seed(ImportSeeder::class);+ $this->trackSeededFiles();++ $seeded = Import::where('file_path', 'like', 'demo-%.csv')->get();++ $this->assertGreaterThan(0, $seeded->count(), 'Expected at least one demo import to be seeded.');+ $this->assertContains('demo-users-sample.csv', $seeded->pluck('file_path')->all());++ $importsDir = config('app.private_uploads').'/imports';+ foreach ($seeded as $import) {+ $this->assertFileExists($importsDir.'/'.$import->file_path);+ $this->assertIsArray($import->header_row);+ $this->assertIsArray($import->first_row);+ $this->assertNotEmpty($import->header_row);+ }+ }++ public function test_seeding_is_idempotent(): void+ {+ $this->seed(ImportSeeder::class);+ $firstRunCount = Import::where('file_path', 'like', 'demo-%.csv')->count();++ $this->seed(ImportSeeder::class);+ $secondRunCount = Import::where('file_path', 'like', 'demo-%.csv')->count();++ $this->trackSeededFiles();++ $this->assertSame($firstRunCount, $secondRunCount, 'Repeated seeder runs must not accumulate duplicate imports.');+ }+}