A free open source IT asset/license management system
Fixed #19690 - Added model merge from asset model index
sniped2b9809d7ac0
diff --git a/app/Actions/AssetModels/MergeAssetModelsAction.php b/app/Actions/AssetModels/MergeAssetModelsAction.phpnew file mode 100644index 0000000000..f10f6a7c36--- /dev/null+++ b/app/Actions/AssetModels/MergeAssetModelsAction.php@@ -0,0 +1,82 @@+<?php++namespace App\Actions\AssetModels;++use App\Enums\ActionType;+use App\Models\Actionlog;+use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\User;+use Illuminate\Database\Eloquent\Collection;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;++class MergeAssetModelsAction+{+ /**+ * Reassign every asset attached to each of $sources onto $target,+ * then soft-delete the source models. Writes an action_log entry+ * on both the source and the surviving target for each pair, so+ * the merge history is visible from either side.+ *+ * Transactional: a partial failure rolls the whole operation+ * back, so admins never end up with half-moved assets and a+ * half-deleted source list.+ *+ * @param Collection<int, AssetModel> $sources+ * @return int Number of assets reassigned across all sources.+ */+ public static function run(AssetModel $target, Collection $sources, ?User $admin): int+ {+ return DB::transaction(function () use ($target, $sources, $admin) {+ $moved = 0;+ foreach ($sources as $source) {+ $moved += Asset::where('model_id', $source->id)+ ->update(['model_id' => $target->id]);+ $source->delete();+ self::logMerge($source, $target, $admin);+ }++ return $moved;+ });+ }++ private static function logMerge(AssetModel $source, AssetModel $target, ?User $admin): void+ {+ // One absolute note text, used on both logs. Avoids the+ // "this model" ambiguity that shows up when the polymorphic+ // history relation pulls both entries onto both models'+ // history tabs.+ $note = trans('general.merged_log_model', [+ 'from_id' => $source->id,+ 'from_name' => $source->name,+ 'to_id' => $target->id,+ 'to_name' => $target->name,+ ]);++ Log::debug('Asset models merged: '.$source->id.' ('.$source->name.') merged into '.$target->id.' ('.$target->name.')');++ // Record on the source model (the one being deleted).+ $sourceLog = new Actionlog;+ $sourceLog->item_id = $source->id;+ $sourceLog->item_type = AssetModel::class;+ $sourceLog->target_id = $target->id;+ $sourceLog->target_type = AssetModel::class;+ $sourceLog->action_type = ActionType::Merged->value;+ $sourceLog->note = $note;+ $sourceLog->created_by = $admin->id ?? null;+ $sourceLog->save();++ // Record on the surviving target so history is visible from+ // the model that stuck around.+ $targetLog = new Actionlog;+ $targetLog->item_id = $target->id;+ $targetLog->item_type = AssetModel::class;+ $targetLog->target_id = $source->id;+ $targetLog->target_type = AssetModel::class;+ $targetLog->action_type = ActionType::Merged->value;+ $targetLog->note = $note;+ $targetLog->created_by = $admin->id ?? null;+ $targetLog->save();+ }+}diff --git a/app/Helpers/IconHelper.php b/app/Helpers/IconHelper.phpindex 9f250189fe..79214cb409 100644--- a/app/Helpers/IconHelper.php+++ b/app/Helpers/IconHelper.php@@ -67,6 +67,8 @@ class IconHelperreturn 'fas fa-download';case 'checkmark':return 'fas fa-check';+ case 'merge':+ return 'fa-solid fa-code-merge';case 'x':return 'fas fa-times';case 'logout':diff --git a/app/Http/Controllers/BulkAssetModelsController.php b/app/Http/Controllers/BulkAssetModelsController.phpindex 9d69d38c78..06b7a37e46 100644--- a/app/Http/Controllers/BulkAssetModelsController.php+++ b/app/Http/Controllers/BulkAssetModelsController.php@@ -2,8 +2,10 @@namespace App\Http\Controllers;+use App\Actions\AssetModels\MergeAssetModelsAction;use App\Helpers\Helper;use App\Models\AssetModel;+use App\Models\User;use Illuminate\Contracts\View\View;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;@@ -24,6 +26,7 @@ class BulkAssetModelsController extends Controller// Make sure some IDs have been selectedif ((is_array($models_raw_array)) && (count($models_raw_array) > 0)) {$models = AssetModel::whereIn('id', $models_raw_array)+ ->with('manufacturer', 'category', 'fieldset')->withCount('assets as assets_count')->orderBy('assets_count', 'ASC')->get();@@ -45,6 +48,24 @@ class BulkAssetModelsController extends Controllerreturn view('models/bulk-delete', compact('models'))->with('valid_count', $valid_count);+ }++ // Merge: pick a surviving target, reassign every other selected+ // model's assets onto the target, then delete the sources.+ // Common driver: a sync adapter that auto-created an+ // AssetModel keyed on the vendor's part number sitting next+ // to the same-hardware model keyed on the marketing name.+ // The merge tool lets admins collapse them without hand-+ // walking every asset.+ if ($request->input('bulk_actions') == 'merge') {+ $this->authorize('delete', AssetModel::class);+ if ($models->count() < 2) {+ return redirect()->route('models.index')+ ->with('error', trans('admin/models/message.merge.min_two'));+ }++ return view('models/confirm-merge', compact('models'));+// Otherwise display the bulk edit screen}$this->authorize('update', AssetModel::class);@@ -153,4 +174,49 @@ class BulkAssetModelsController extends Controllerreturn redirect()->route('models.index')->with('error', trans('admin/models/message.bulkdelete.error'));}++ /**+ * Merge two or more AssetModels into one target. Every asset on+ * the sources gets its `model_id` pointed at the target, then the+ * source models are soft-deleted. Wrapped in a transaction so a+ * partial failure leaves the models table in its original state.+ *+ * Fixes the "phantom AssetModel" cleanup shape when a sync adapter+ * auto-created models keyed on hardwareModel next to the same-+ * hardware model keyed on the marketing name.+ */+ public function merge(Request $request): RedirectResponse+ {+ $this->authorize('delete', AssetModel::class);++ $target_id = (int) $request->input('merge_into_id');+ $source_ids = array_map('intval', (array) $request->input('ids_to_merge'));+ $source_ids = array_values(array_diff($source_ids, [$target_id]));++ if ($target_id === 0 || $source_ids === []) {+ return redirect()->route('models.index')+ ->with('error', trans('admin/models/message.merge.no_target'));+ }++ $target = AssetModel::find($target_id);+ $sources = AssetModel::whereIn('id', $source_ids)->get();++ if ($target === null || $sources->count() !== count($source_ids)) {+ return redirect()->route('models.index')+ ->with('error', trans('admin/models/message.merge.not_found'));+ }++ $moved_assets = MergeAssetModelsAction::run(+ target: $target,+ sources: $sources,+ admin: User::find(auth()->id()),+ );++ return redirect()->route('models.index')+ ->with('success', trans('admin/models/message.merge.success', [+ 'source_count' => $sources->count(),+ 'asset_count' => $moved_assets,+ 'target' => $target->name,+ ]));+ }}diff --git a/app/Http/Transformers/AssetModelsTransformer.php b/app/Http/Transformers/AssetModelsTransformer.phpindex 659eef4818..4928eb898d 100644--- a/app/Http/Transformers/AssetModelsTransformer.php+++ b/app/Http/Transformers/AssetModelsTransformer.php@@ -120,6 +120,7 @@ class AssetModelsTransformer'bulk_selectable' => ['edit' => (Gate::allows('update', $assetmodel) && ($assetmodel->deleted_at == '')),'delete' => (Gate::allows('delete', $assetmodel) && $assetmodel->isDeletable()),+ 'merge' => (Gate::allows('delete', AssetModel::class) && ($assetmodel->deleted_at == '')),],];diff --git a/app/Presenters/ActionlogPresenter.php b/app/Presenters/ActionlogPresenter.phpindex e77567a69c..618bc79ee5 100644--- a/app/Presenters/ActionlogPresenter.php+++ b/app/Presenters/ActionlogPresenter.php@@ -75,6 +75,10 @@ class ActionlogPresenter extends Presenterreturn 'fa-solid fa-plus';}+ if ($this->action_type == 'merged') {+ return 'fa-solid fa-code-merge';+ }+if (($this->action_type == 'delete') || ($this->action_type == 'upload deleted')) {return 'fa-solid fa-trash';}diff --git a/phpstan-baseline.neon b/phpstan-baseline.neonindex 9342e96b06..1437c4e458 100644--- a/phpstan-baseline.neon+++ b/phpstan-baseline.neon@@ -4647,7 +4647,7 @@ parameters:-message: '#^Access to an undefined property App\\Models\\Actionlog\:\:\$created_by\.$#'identifier: property.notFound- count: 4+ count: 6path: app/Listeners/LogListener.php-diff --git a/resources/lang/en-US/admin/models/message.php b/resources/lang/en-US/admin/models/message.phpindex a8196666a1..58128284a5 100644--- a/resources/lang/en-US/admin/models/message.php+++ b/resources/lang/en-US/admin/models/message.php@@ -51,6 +51,7 @@ return ['not_found' => 'One or more of the selected models could not be loaded. Refresh the models list and try again.','information' => 'You are about to merge :count models. Pick the model you want to keep. Every asset attached to the other models will be reassigned to the model you pick, then the source models will be deleted.','warning' => 'This cannot be undone. Reassigned assets will inherit the surviving model\'s category, fieldset, and depreciation settings.',+ 'pick_target' => 'Which model do you want to keep?','success' => 'Merged :source_count model(s) into ":target". :asset_count asset(s) were reassigned.',],diff --git a/resources/views/blade/table/bulk-models.blade.php b/resources/views/blade/table/bulk-models.blade.phpindex c937f6b22e..e6f5bec813 100644--- a/resources/views/blade/table/bulk-models.blade.php+++ b/resources/views/blade/table/bulk-models.blade.php@@ -9,6 +9,7 @@:actions="['edit' => ['label' => trans('general.bulk_edit')],'delete' => ['label' => trans('general.bulk_delete')],+ 'merge' => ['label' => trans('general.merge_models')],]"/>@endcananydiff --git a/resources/views/models/confirm-merge.blade.php b/resources/views/models/confirm-merge.blade.phpnew file mode 100644index 0000000000..700f5290f0--- /dev/null+++ b/resources/views/models/confirm-merge.blade.php@@ -0,0 +1,89 @@+@extends('layouts/default')++{{-- Page title --}}+@section('title')+ {{ trans('general.merge_models') }}+ @parent+@stop++@section('header_right')+ <a href="{{ URL::previous() }}" class="btn btn-primary pull-right">+ {{ trans('general.back') }}</a>+@stop++{{-- Page content --}}+@section('content')+ <x-container class="col-md-8 col-md-offset-2">+ <p>{{ trans('admin/models/message.merge.information', ['count' => count($models)]) }}</p>++ <x-callout type="danger" icon="warning" live="assertive">+ {{ trans('admin/models/message.merge.warning') }}+ </x-callout>++ <x-demo-callout />++ <x-form route="{{ route('models.merge.save') }}">+ <x-box>+ <x-slot:header>+ {{ trans('admin/models/message.merge.pick_target') }}+ </x-slot:header>++ <table class="table table-striped table-condensed">+ <thead>+ <tr>+ <th scope="col" class="col-md-3">{{ trans('general.name') }}</th>+ <th scope="col" class="col-md-2">{{ trans('general.manufacturer') }}</th>+ <th scope="col" class="col-md-2">{{ trans('general.category') }}</th>+ <th scope="col" class="col-md-3">{{ trans('admin/custom_fields/general.fieldset') }}</th>+ <th scope="col" class="col-md-2 text-right">+ <i class="fas fa-barcode fa-fw" aria-hidden="true" style="font-size: 17px;"></i>+ <span class="sr-only">{{ trans('general.assets') }}</span>+ </th>+ </tr>+ </thead>+ <tbody>+ @foreach ($models as $model)+ <tr>+ <td>+ <label class="form-control" for="model_{{ $model->id }}">+ <input type="radio" name="merge_into_id" id="model_{{ $model->id }}" value="{{ $model->id }}">+ {{ $model->name }}+ </label>+ </td>+ <td>{{ $model->manufacturer?->name }}</td>+ <td>{{ $model->category?->name }}</td>+ <td>+ @if ($model->fieldset)+ <a href="{{ route('fieldsets.show', $model->fieldset->id) }}">{{ $model->fieldset->name }}</a>+ @endif+ </td>+ <td class="text-right">{{ number_format($model->assets_count) }}</td>+ </tr>+ @endforeach+ </tbody>+ </table>++ @foreach ($models as $model)+ <input type="hidden" name="ids_to_merge[]" value="{{ $model->id }}">+ @endforeach++ <x-slot:customfooter>+ <div class="box-footer text-right">+ <a class="btn btn-link pull-left" href="{{ URL::previous() }}">{{ trans('button.cancel') }}</a>+ <button type="submit" class="btn btn-success" id="submit-button" disabled>+ <x-icon type="merge" /> {{ trans('general.merge_models') }}+ </button>+ </div>+ </x-slot:customfooter>+ </x-box>+ </x-form>+ </x-container>+@stop++@section('moar_scripts')+ <script>+ $("input[type='radio']").on('change', function () {+ $('#submit-button').prop('disabled', false).removeAttr('disabled');+ });+ </script>+@stopdiff --git a/tests/Feature/AssetModels/Ui/BulkMergeAssetModelsTest.php b/tests/Feature/AssetModels/Ui/BulkMergeAssetModelsTest.phpnew file mode 100644index 0000000000..6965047ec3--- /dev/null+++ b/tests/Feature/AssetModels/Ui/BulkMergeAssetModelsTest.php@@ -0,0 +1,176 @@+<?php++namespace Tests\Feature\AssetModels\Ui;++use App\Models\Asset;+use App\Models\AssetModel;+use App\Models\User;+use Tests\TestCase;++class BulkMergeAssetModelsTest extends TestCase+{+ public function test_shows_confirmation_when_at_least_two_models_are_selected()+ {+ $modelA = AssetModel::factory()->create();+ $modelB = AssetModel::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('models.bulkedit.index'), [+ 'ids' => [$modelA->id, $modelB->id],+ 'bulk_actions' => 'merge',+ ])+ ->assertStatus(200)+ ->assertSee($modelA->name)+ ->assertSee($modelB->name);+ }++ public function test_redirects_to_index_when_fewer_than_two_models_selected()+ {+ // Merge requires at least two models. Selecting one is not+ // enough. Redirect with a flash instead of rendering the+ // confirmation view.+ $modelA = AssetModel::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->from(route('models.index'))+ ->post(route('models.bulkedit.index'), [+ 'ids' => [$modelA->id],+ 'bulk_actions' => 'merge',+ ])+ ->assertRedirect(route('models.index'))+ ->assertSessionHas('error');+ }++ public function test_merges_assets_from_source_models_into_target()+ {+ $target = AssetModel::factory()->create();+ $sourceA = AssetModel::factory()->create();+ $sourceB = AssetModel::factory()->create();++ $assetOnA = Asset::factory()->for($sourceA, 'model')->create();+ $assetOnB1 = Asset::factory()->for($sourceB, 'model')->create();+ $assetOnB2 = Asset::factory()->for($sourceB, 'model')->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('models.merge.save'), [+ 'merge_into_id' => $target->id,+ 'ids_to_merge' => [$target->id, $sourceA->id, $sourceB->id],+ ])+ ->assertRedirect(route('models.index'))+ ->assertSessionHas('success');++ // Every source model's assets now point at the target.+ $this->assertSame($target->id, $assetOnA->refresh()->model_id);+ $this->assertSame($target->id, $assetOnB1->refresh()->model_id);+ $this->assertSame($target->id, $assetOnB2->refresh()->model_id);++ // Source models are soft-deleted, target survives.+ $this->assertNull(AssetModel::find($sourceA->id));+ $this->assertNull(AssetModel::find($sourceB->id));+ $this->assertNotNull(AssetModel::find($target->id));+ }++ public function test_merge_target_is_not_deleted_even_when_listed_in_ids_to_merge()+ {+ // ids_to_merge carries the full selection including the target+ // (that's how the confirmation form posts). The controller must+ // exclude the target from the sources list before deleting so+ // it doesn't wipe the model we're merging into.+ $target = AssetModel::factory()->create();+ $source = AssetModel::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('models.merge.save'), [+ 'merge_into_id' => $target->id,+ 'ids_to_merge' => [$target->id, $source->id],+ ])+ ->assertRedirect(route('models.index'));++ $this->assertNotNull(AssetModel::find($target->id));+ $this->assertNull(AssetModel::find($source->id));+ }++ public function test_redirects_with_error_when_target_not_picked()+ {+ $source = AssetModel::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->from(route('models.index'))+ ->post(route('models.merge.save'), [+ 'merge_into_id' => null,+ 'ids_to_merge' => [$source->id],+ ])+ ->assertRedirect(route('models.index'))+ ->assertSessionHas('error');++ // Source is untouched.+ $this->assertNotNull(AssetModel::find($source->id));+ }++ public function test_merge_logs_actionlog_entries_on_both_source_and_target()+ {+ // Same shape as the user-merge log: one action_log entry per+ // source pointing at target, plus one entry per pair pointing+ // at target->source. So merging N sources into one target+ // yields 2N action_log rows, all with action_type 'merged'.+ $target = AssetModel::factory()->create();+ $sourceA = AssetModel::factory()->create();+ $sourceB = AssetModel::factory()->create();++ $this->actingAs(User::factory()->superuser()->create())+ ->post(route('models.merge.save'), [+ 'merge_into_id' => $target->id,+ 'ids_to_merge' => [$target->id, $sourceA->id, $sourceB->id],+ ]);++ // Entry on each source model.+ $this->assertDatabaseHas('action_logs', [+ 'action_type' => 'merged',+ 'item_id' => $sourceA->id,+ 'item_type' => AssetModel::class,+ 'target_id' => $target->id,+ 'target_type' => AssetModel::class,+ ]);+ $this->assertDatabaseHas('action_logs', [+ 'action_type' => 'merged',+ 'item_id' => $sourceB->id,+ 'item_type' => AssetModel::class,+ 'target_id' => $target->id,+ 'target_type' => AssetModel::class,+ ]);++ // Entry on the target pointing at each source.+ $this->assertDatabaseHas('action_logs', [+ 'action_type' => 'merged',+ 'item_id' => $target->id,+ 'item_type' => AssetModel::class,+ 'target_id' => $sourceA->id,+ 'target_type' => AssetModel::class,+ ]);+ $this->assertDatabaseHas('action_logs', [+ 'action_type' => 'merged',+ 'item_id' => $target->id,+ 'item_type' => AssetModel::class,+ 'target_id' => $sourceB->id,+ 'target_type' => AssetModel::class,+ ]);+ }++ public function test_non_superusers_without_delete_permission_are_blocked()+ {+ $target = AssetModel::factory()->create();+ $source = AssetModel::factory()->create();++ // A user with no permissions at all shouldn't reach the merge+ // controller. The delete permission on AssetModel is what+ // gates it (matches the user-merge shape).+ $this->actingAs(User::factory()->create())+ ->post(route('models.merge.save'), [+ 'merge_into_id' => $target->id,+ 'ids_to_merge' => [$target->id, $source->id],+ ])+ ->assertForbidden();++ $this->assertNotNull(AssetModel::find($source->id));+ }+}