A free open source IT asset/license management system
Fix for custom fields being populated even though they're no longer associated with the asset's model any more.
Brady Wetheringtondb61be327245
diff --git a/app/Console/Commands/CleanUnreferencedCustomFields.php b/app/Console/Commands/CleanUnreferencedCustomFields.phpnew file mode 100644index 0000000000..5040262876--- /dev/null+++ b/app/Console/Commands/CleanUnreferencedCustomFields.php@@ -0,0 +1,69 @@+<?php++namespace App\Console\Commands;++use App\Models\Asset;+use App\Models\CustomField;+use App\Models\CustomFieldset;+use App\Models\AssetModel;+use Illuminate\Console\Command;+use Illuminate\Support\Facades\DB;++class CleanUnreferencedCustomFields extends Command+{+ /**+ * The name and signature of the console command.+ *+ * @var string+ */+ protected $signature = 'snipeit:clean-custom-fields+ {--force : Run immediately without requiring confirmation}';++ /**+ * The console command description.+ *+ * @var string+ */+ protected $description = 'This command will iterate through all of your custom fields and fieldsets to determine which ones *should* be blank but aren\'t actually blank - and will blank those out, as well';++ /**+ * Execute the console command.+ */+ public function handle()+ {+ if (!$this->option('force') && !$this->confirm('This will blank out *ALL* custom fields in your assets that are not referenced by their model\'s fieldset. Are you sure you want to continue?')) {+ $this->fail('Command was canceled');+ }+ // first, we get a 'master fieldmap' of db fieldnames => null+ // (the 'null' part will be important later)+ $master_fieldmap = [];+ foreach (CustomField::all() as $field) {+ $master_fieldmap[$field->db_column] = null;+ }++ $update_count = 0;+ // then, we iterate through *each* customfieldset to figure out models which use that fieldset, and the fields in the fieldset+ foreach (CustomFieldset::all() as $fieldset) {+ // similar to the $master_fieldmap above, we assemble now an associative array of db_column -> null entries...+ $fieldset_fields = [];+ foreach ($fieldset->fields as $field) {+ $fieldset_fields[$field->db_column] = null;+ }+ /** @phpstan-ignore method.notFound */+ $model_ids = $fieldset->models()->withTrashed()->select('id'); // should generate a subquery++ // and boom! the 'null' payoff - we get a pre-formatted list of unused keys => null+ $fields_to_blank = array_diff_assoc($master_fieldmap, $fieldset_fields);+ $assets_updated_count = Asset::whereIn('model_id', $model_ids)->withTrashed()->update($fields_to_blank);+ $this->info('Fieldset "' . $fieldset->name . '" (' . $fieldset->id . ') - updated ' . $assets_updated_count);+ $update_count += $assets_updated_count;+ }++ //finally, we need to handle the 'empty fieldset' models+ $model_ids = AssetModel::select('id')->whereNull('fieldset_id')->withTrashed(); //note: no ->get() because this should end up being a subquery (we hope!)+ $assets_updated_count = Asset::whereIn('model_id', $model_ids)->withTrashed()->update($master_fieldmap);+ $this->info('No Fieldset - updated ' . $assets_updated_count);+ $update_count += $assets_updated_count;+ $this->info("Finished cleaning unreferenced custom fields, total updated assets are: $update_count");+ }+}diff --git a/tests/Feature/Console/CleanUnreferencedCustomFieldsTest.php b/tests/Feature/Console/CleanUnreferencedCustomFieldsTest.phpnew file mode 100644index 0000000000..b79dda0f1c--- /dev/null+++ b/tests/Feature/Console/CleanUnreferencedCustomFieldsTest.php@@ -0,0 +1,62 @@+<?php++namespace Tests\Feature\Console;++use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\CustomField;+use App\Models\CustomFieldset;+use Tests\TestCase;++class CleanUnreferencedCustomFieldsTest extends TestCase+{+ public function test_blanks_orphaned_field_but_preserves_field_in_fieldset(): void+ {+ // One asset carries values for two custom fields: one is in its+ // model's fieldset, the other is not (e.g. removed from the+ // fieldset after the value was written). A single asset is used+ // for both fields so the test can't pass by the command doing+ // nothing at all.+ $inFieldset = CustomField::factory()->create();+ $orphaned = CustomField::factory()->create();++ $fieldset = CustomFieldset::factory()->create();+ $fieldset->fields()->attach($inFieldset, ['order' => 1, 'required' => false]);++ $model = AssetModel::factory()->create(['fieldset_id' => $fieldset->id]);++ $inFieldsetColumn = $inFieldset->db_column_name();+ $orphanedColumn = $orphaned->db_column_name();++ $asset = Asset::factory()->for($model, 'model')->create();+ $asset->{$inFieldsetColumn} = 'KEEP-ME';+ $asset->{$orphanedColumn} = 'ORPHANED-VALUE';+ $asset->save();++ $this->artisan('snipeit:clean-custom-fields', ['--force' => true])->assertExitCode(0);++ $asset->refresh();+ $this->assertSame('KEEP-ME', $asset->{$inFieldsetColumn},+ 'Value for a field that is in the model\'s fieldset should be preserved');+ $this->assertNull($asset->{$orphanedColumn},+ 'Value for a field that is not in the model\'s fieldset should be blanked');+ }++ public function test_blanks_all_custom_field_values_for_model_with_no_fieldset(): void+ {+ $field = CustomField::factory()->create();+ $column = $field->db_column_name();++ $modelWithoutFieldset = AssetModel::factory()->create(['fieldset_id' => null]);++ $asset = Asset::factory()->for($modelWithoutFieldset, 'model')->create();+ $asset->{$column} = 'SHOULD-BE-BLANKED';+ $asset->save();++ $this->artisan('snipeit:clean-custom-fields', ['--force' => true])->assertExitCode(0);++ $asset->refresh();+ $this->assertNull($asset->{$column},+ 'A field value on an asset whose model has no fieldset at all should be blanked');+ }+}