A free open source IT asset/license management system
Companies: Added bulk edit, fixed #19261
snipea7e8546cf18a
diff --git a/app/Actions/Companies/DestroyCompanyAction.php b/app/Actions/Companies/DestroyCompanyAction.phpnew file mode 100644index 0000000000..2a236886fd--- /dev/null+++ b/app/Actions/Companies/DestroyCompanyAction.php@@ -0,0 +1,72 @@+<?php++namespace App\Actions\Companies;++use App\Exceptions\ItemStillHasAccessories;+use App\Exceptions\ItemStillHasAssets;+use App\Exceptions\ItemStillHasComponents;+use App\Exceptions\ItemStillHasConsumables;+use App\Exceptions\ItemStillHasLicenses;+use App\Exceptions\ItemStillHasUsers;+use App\Models\Company;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Storage;++class DestroyCompanyAction+{+ /**+ * @throws ItemStillHasAssets+ * @throws ItemStillHasAccessories+ * @throws ItemStillHasLicenses+ * @throws ItemStillHasComponents+ * @throws ItemStillHasConsumables+ * @throws ItemStillHasUsers+ */+ public static function run(Company $company): bool+ {+ $company->loadCount([+ 'assets as assets_count',+ 'accessories as accessories_count',+ 'licenses as licenses_count',+ 'components as components_count',+ 'consumables as consumables_count',+ 'users as users_count',+ ]);++ if ($company->assets_count > 0) {+ throw new ItemStillHasAssets($company);+ }++ if ($company->accessories_count > 0) {+ throw new ItemStillHasAccessories($company);+ }++ if ($company->licenses_count > 0) {+ throw new ItemStillHasLicenses($company);+ }++ if ($company->components_count > 0) {+ throw new ItemStillHasComponents($company);+ }++ if ($company->consumables_count > 0) {+ throw new ItemStillHasConsumables($company);+ }++ if ($company->users_count > 0) {+ throw new ItemStillHasUsers($company);+ }++ if ($company->image) {+ try {+ Storage::disk('public')->delete('companies/'.$company->image);+ } catch (\Exception $e) {+ Log::info($e->getMessage());+ }+ }++ $company->delete();++ return true;+ }+}diff --git a/app/Actions/Manufacturers/DeleteManufacturerAction.php b/app/Actions/Manufacturers/DestroyManufacturerAction.phpsimilarity index 98%rename from app/Actions/Manufacturers/DeleteManufacturerAction.phprename to app/Actions/Manufacturers/DestroyManufacturerAction.phpindex fd918fe1dd..e71def96b7 100644--- a/app/Actions/Manufacturers/DeleteManufacturerAction.php+++ b/app/Actions/Manufacturers/DestroyManufacturerAction.php@@ -11,7 +11,7 @@ use App\Models\Manufacturer;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;-class DeleteManufacturerAction+class DestroyManufacturerAction{/*** @throws ItemStillHasAssetsdiff --git a/app/Console/Commands/Purge.php b/app/Console/Commands/Purge.phpindex 9fe9f39228..0567829d76 100644--- a/app/Console/Commands/Purge.php+++ b/app/Console/Commands/Purge.php@@ -7,6 +7,7 @@ use App\Models\Actionlog;use App\Models\Asset;use App\Models\AssetModel;use App\Models\Category;+use App\Models\Company;use App\Models\Component;use App\Models\Consumable;use App\Models\License;@@ -53,7 +54,10 @@ class Purge extends Commandpublic function handle(){$force = $this->option('force');- if (($this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) || $force == 'true') {+ // Short-circuit on --force so the confirm() prompt isn't rendered+ // (and isn't required by the test harness) when the operator has+ // already opted in from the command line.+ if ($force == 'true' || $this->confirm("\n****************************************************\nTHIS WILL PURGE ALL SOFT-DELETED ITEMS IN YOUR SYSTEM. \nThere is NO undo. This WILL permanently destroy \nALL of your deleted data. \n****************************************************\n\nDo you wish to continue? No backsies! [y|N]")) {/*** Delete assets@@ -140,6 +144,13 @@ class Purge extends Command$supplier->forceDelete();}+ $companies = Company::whereNotNull('deleted_at')->withTrashed()->get();+ $this->info($companies->count().' companies purged.');+ foreach ($companies as $company) {+ $this->info('- Company "'.$company->name.'" deleted.');+ $company->forceDelete();+ }+$users = User::whereNotNull('deleted_at')->where('show_in_list', '!=', '0')->withTrashed()->get();$this->info($users->count().' users purged.');$user_assoc = 0;diff --git a/app/Exceptions/ItemStillHasUsers.php b/app/Exceptions/ItemStillHasUsers.phpnew file mode 100644index 0000000000..798ab92d75--- /dev/null+++ b/app/Exceptions/ItemStillHasUsers.php@@ -0,0 +1,5 @@+<?php++namespace App\Exceptions;++class ItemStillHasUsers extends ItemStillHasChildren {}diff --git a/app/Http/Controllers/Api/ManufacturersController.php b/app/Http/Controllers/Api/ManufacturersController.phpindex 33e56d42ab..d4a7807a1c 100644--- a/app/Http/Controllers/Api/ManufacturersController.php+++ b/app/Http/Controllers/Api/ManufacturersController.php@@ -2,7 +2,7 @@namespace App\Http\Controllers\Api;-use App\Actions\Manufacturers\DeleteManufacturerAction;+use App\Actions\Manufacturers\DestroyManufacturerAction;use App\Exceptions\ItemStillHasChildren;use App\Helpers\Helper;use App\Http\Controllers\Controller;@@ -213,7 +213,7 @@ class ManufacturersController extends Controller{$this->authorize('delete', $manufacturer);try {- DeleteManufacturerAction::run($manufacturer);+ DestroyManufacturerAction::run($manufacturer);} catch (ItemStillHasChildren $e) {return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.bulk_delete_associations.general_assoc_warning', ['item' => trans('general.manufacturer')])));} catch (\Exception $e) {diff --git a/app/Http/Controllers/BulkCompaniesController.php b/app/Http/Controllers/BulkCompaniesController.phpnew file mode 100644index 0000000000..9fdd3542a1--- /dev/null+++ b/app/Http/Controllers/BulkCompaniesController.php@@ -0,0 +1,65 @@+<?php++namespace App\Http\Controllers;++use App\Actions\Companies\DestroyCompanyAction;+use App\Exceptions\ItemStillHasAccessories;+use App\Exceptions\ItemStillHasAssets;+use App\Exceptions\ItemStillHasComponents;+use App\Exceptions\ItemStillHasConsumables;+use App\Exceptions\ItemStillHasLicenses;+use App\Exceptions\ItemStillHasUsers;+use App\Models\Company;+use Illuminate\Http\Request;++class BulkCompaniesController extends Controller+{+ public function destroy(Request $request)+ {+ $this->authorize('delete', Company::class);++ $errors = [];+ $success_count = 0;++ foreach ($request->ids as $id) {+ $company = Company::find($id);+ if (is_null($company)) {+ $errors[] = trans('admin/companies/message.does_not_exist');++ continue;+ }+ try {+ DestroyCompanyAction::run(company: $company);+ $success_count++;+ } catch (ItemStillHasAssets $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_assets_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (ItemStillHasAccessories $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_accessories_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (ItemStillHasLicenses $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_licenses_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (ItemStillHasComponents $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_components_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (ItemStillHasConsumables $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_consumables_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (ItemStillHasUsers $e) {+ $errors[] = trans('general.bulk_delete_associations.assoc_users_no_count', ['item_name' => $company->name, 'item' => trans('general.company')]);+ } catch (\Exception $e) {+ report($e);+ $errors[] = trans('general.something_went_wrong');+ }+ }++ if (count($errors) > 0) {+ if ($success_count > 0) {+ return redirect()->route('companies.index')+ ->with('success', trans_choice('admin/companies/message.delete.partial_success', $success_count, ['count' => $success_count]))+ ->with('multi_error_messages', $errors);+ }++ return redirect()->route('companies.index')->with('multi_error_messages', $errors);+ }++ return redirect()->route('companies.index')+ ->with('success', trans('admin/companies/message.delete.bulk_success'));+ }+}diff --git a/app/Http/Controllers/BulkManufacturersController.php b/app/Http/Controllers/BulkManufacturersController.phpindex d2e0b8e616..6d13c6999d 100644--- a/app/Http/Controllers/BulkManufacturersController.php+++ b/app/Http/Controllers/BulkManufacturersController.php@@ -2,7 +2,7 @@namespace App\Http\Controllers;-use App\Actions\Manufacturers\DeleteManufacturerAction;+use App\Actions\Manufacturers\DestroyManufacturerAction;use App\Exceptions\ItemStillHasAccessories;use App\Exceptions\ItemStillHasAssets;use App\Exceptions\ItemStillHasComponents;@@ -27,7 +27,7 @@ class BulkManufacturersController extends Controllercontinue;}try {- DeleteManufacturerAction::run(manufacturer: $manufacturer);+ DestroyManufacturerAction::run(manufacturer: $manufacturer);$success_count++;} catch (ItemStillHasAssets $e) {$errors[] = trans('general.bulk_delete_associations.assoc_assets_no_count', ['item_name' => $manufacturer->name, 'item' => trans('general.manufacturer')]);diff --git a/app/Http/Controllers/ManufacturersController.php b/app/Http/Controllers/ManufacturersController.phpindex e5f18fdf78..f87af87c37 100755--- a/app/Http/Controllers/ManufacturersController.php+++ b/app/Http/Controllers/ManufacturersController.php@@ -2,7 +2,7 @@namespace App\Http\Controllers;-use App\Actions\Manufacturers\DeleteManufacturerAction;+use App\Actions\Manufacturers\DestroyManufacturerAction;use App\Exceptions\ItemStillHasChildren;use App\Http\Requests\ImageUploadRequest;use App\Models\Actionlog;@@ -176,7 +176,7 @@ class ManufacturersController extends Controller{$this->authorize('delete', $manufacturer);try {- DeleteManufacturerAction::run($manufacturer);+ DestroyManufacturerAction::run($manufacturer);} catch (ItemStillHasChildren $e) {return redirect()->route('manufacturers.index')->with('error', trans('general.bulk_delete_associations.general_assoc_warning', ['item' => trans('general.manufacturer')]));} catch (\Exception $e) {diff --git a/app/Http/Transformers/CompaniesTransformer.php b/app/Http/Transformers/CompaniesTransformer.phpindex af60ceab49..7d7e748ebb 100644--- a/app/Http/Transformers/CompaniesTransformer.php+++ b/app/Http/Transformers/CompaniesTransformer.php@@ -50,6 +50,9 @@ class CompaniesTransformer$permissions_array['available_actions'] = ['update' => Gate::allows('update', Company::class),'delete' => $company->isDeletable(),+ 'bulk_selectable' => [+ 'delete' => $company->isDeletable(),+ ],];$array += $permissions_array;diff --git a/app/Presenters/CompanyPresenter.php b/app/Presenters/CompanyPresenter.phpindex 6d2af89291..5ea1a0f1c1 100644--- a/app/Presenters/CompanyPresenter.php+++ b/app/Presenters/CompanyPresenter.php@@ -16,6 +16,13 @@ class CompanyPresenter extends Presenter{$layout = [[+ 'field' => 'checkbox',+ 'checkbox' => true,+ 'formatter' => 'checkboxEnabledFormatter',+ 'titleTooltip' => trans('general.select_all_none'),+ 'printIgnore' => true,+ 'class' => 'hidden-print',+ ], ['field' => 'id','searchable' => false,'sortable' => true,diff --git a/resources/lang/en-US/admin/companies/message.php b/resources/lang/en-US/admin/companies/message.phpindex f8a34ec15a..0daf841063 100644--- a/resources/lang/en-US/admin/companies/message.php+++ b/resources/lang/en-US/admin/companies/message.php@@ -16,5 +16,7 @@ return ['confirm' => 'Are you sure you wish to delete this company?','error' => 'There was an issue deleting the company. Please try again.','success' => 'The Company was deleted successfully.',+ 'bulk_success' => 'Companies were deleted successfully.',+ 'partial_success' => 'Company deleted successfully. See additional information below. | :count companies were deleted successfully. See additional information below.',],];diff --git a/resources/lang/en-US/general.php b/resources/lang/en-US/general.phpindex defa695a25..8a263c975d 100644--- a/resources/lang/en-US/general.php+++ b/resources/lang/en-US/general.php@@ -739,6 +739,7 @@ return ['assoc_consumables_no_count' => ':item_name is currently associated with other consumables and cannot be deleted. Please update your consumables to no longer reference this :item and try again.','assoc_components_no_count' => ':item_name is currently associated with other components and cannot be deleted. Please update your components to no longer reference this :item and try again.','assoc_licenses_no_count' => ':item_name is currently associated with other licenses and cannot be deleted. Please update your licenses to no longer reference this :item and try again.',+ 'assoc_users_no_count' => ':item_name is currently associated with other users and cannot be deleted. Please update your users to no longer reference this :item and try again.',],'breadcrumb_button_actions' => [diff --git a/resources/views/companies/index.blade.php b/resources/views/companies/index.blade.phpindex 4bd579ed37..ef692b2e80 100644--- a/resources/views/companies/index.blade.php+++ b/resources/views/companies/index.blade.php@@ -12,22 +12,29 @@<x-page-column class="col-md-9"><x-box>- <table- data-columns="{{ \App\Presenters\CompanyPresenter::dataTableLayout() }}"- data-cookie-id-table="companiesTable"- data-id-table="companiesTable"- data-side-pagination="server"- data-sort-order="asc"- data-advanced-search="false"- id="companiesTable"- data-buttons="companyButtons"- class="table table-striped snipe-table"- data-url="{{ route('api.companies.index') }}"- data-export-options='{- "fileName": "export-companies-{{ date('Y-m-d') }}",- "ignoreColumn": ["actions","image","change","checkbox","checkincheckout","icon"]- }'>- </table>++ <x-slot:bulkactions>+ <x-table.bulk-actions+ name='company'+ action_route="{{ route('companies.bulk.delete') }}"+ model_name="company"+ >+ @can('delete', App\Models\Company::class)+ <option>{{ trans('general.delete') }}</option>+ @endcan+ </x-table.bulk-actions>+ </x-slot:bulkactions>++ <x-table+ name="company"+ buttons="companyButtons"+ fixed_right_number="1"+ fixed_number="1"+ api_url="{{ route('api.companies.index') }}"+ :presenter="\App\Presenters\CompanyPresenter::dataTableLayout()"+ export_filename="export-companies-{{ date('Y-m-d') }}"+ />+</x-box></x-page-column>diff --git a/routes/web.php b/routes/web.phpindex 04777c8e25..9484ef1c67 100644--- a/routes/web.php+++ b/routes/web.php@@ -7,6 +7,7 @@ use App\Http\Controllers\Auth\ForgotPasswordController;use App\Http\Controllers\Auth\LoginController;use App\Http\Controllers\Auth\ResetPasswordController;use App\Http\Controllers\BulkCategoriesController;+use App\Http\Controllers\BulkCompaniesController;use App\Http\Controllers\BulkManufacturersController;use App\Http\Controllers\BulkSuppliersController;use App\Http\Controllers\CategoriesController;@@ -22,8 +23,8 @@ use App\Http\Controllers\ManufacturersController;use App\Http\Controllers\ModalController;use App\Http\Controllers\NotesController;use App\Http\Controllers\ProfileController;-use App\Http\Controllers\Reports\CustomComponentReportController;use App\Http\Controllers\QrCodeController;+use App\Http\Controllers\Reports\CustomComponentReportController;use App\Http\Controllers\ReportsController;use App\Http\Controllers\ReportTemplatesController;use App\Http\Controllers\SettingsController;@@ -47,6 +48,8 @@ Route::group(['middleware' => 'auth'], function () {'parameters' => ['company' => 'company_id'],]);+ Route::post('companies/bulk/delete', [BulkCompaniesController::class, 'destroy'])->name('companies.bulk.delete');+/** Categories*/diff --git a/tests/Feature/Companies/Api/BulkSelectableTest.php b/tests/Feature/Companies/Api/BulkSelectableTest.phpnew file mode 100644index 0000000000..7f456c5ab2--- /dev/null+++ b/tests/Feature/Companies/Api/BulkSelectableTest.php@@ -0,0 +1,51 @@+<?php++namespace Tests\Feature\Companies\Api;++use App\Models\Asset;+use App\Models\Company;+use App\Models\User;+use Tests\TestCase;++/**+ * Verifies the JS-visible flag that drives the bulk-delete checkbox on the+ * companies index. The bootstrap-table `checkboxEnabledFormatter` reads+ * `available_actions.bulk_selectable.delete` and disables the row's checkbox+ * when every entry there is false. A company with any associated record must+ * therefore report `bulk_selectable.delete === false`; a clean company must+ * report `true`.+ */+class BulkSelectableTest extends TestCase+{+ public function test_clean_company_is_bulk_selectable()+ {+ $company = Company::factory()->create();++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.companies.show', $company))+ ->assertOk()+ ->assertJsonPath('available_actions.bulk_selectable.delete', true);+ }++ public function test_company_with_assets_is_not_bulk_selectable()+ {+ $company = Company::factory()->create();+ Asset::factory()->create(['company_id' => $company->id]);++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.companies.show', $company))+ ->assertOk()+ ->assertJsonPath('available_actions.bulk_selectable.delete', false);+ }++ public function test_company_with_users_is_not_bulk_selectable()+ {+ $company = Company::factory()->create();+ $company->users()->syncWithoutDetaching([User::factory()->create()->id]);++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->getJson(route('api.companies.show', $company))+ ->assertOk()+ ->assertJsonPath('available_actions.bulk_selectable.delete', false);+ }+}diff --git a/tests/Feature/Companies/Ui/BulkDeleteCompaniesTest.php b/tests/Feature/Companies/Ui/BulkDeleteCompaniesTest.phpnew file mode 100644index 0000000000..60b62bc3bd--- /dev/null+++ b/tests/Feature/Companies/Ui/BulkDeleteCompaniesTest.php@@ -0,0 +1,99 @@+<?php++namespace Tests\Feature\Companies\Ui;++use App\Models\Asset;+use App\Models\Company;+use App\Models\User;+use Tests\TestCase;++class BulkDeleteCompaniesTest extends TestCase+{+ public function test_requires_permission()+ {+ $this->actingAs(User::factory()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [1, 2, 3],+ ])+ ->assertForbidden();+ }++ public function test_company_with_assets_is_not_bulk_deleted()+ {+ $company = Company::factory()->create();+ Asset::factory()->create(['company_id' => $company->id]);++ $this->actingAs(User::factory()->deleteCompanies()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [$company->id],+ ]);++ $this->assertModelExists($company);+ $this->assertNotSoftDeleted($company);+ }++ public function test_company_with_users_is_not_bulk_deleted()+ {+ $company = Company::factory()->create();+ $company->users()->syncWithoutDetaching([User::factory()->create()->id]);++ $this->actingAs(User::factory()->deleteCompanies()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [$company->id],+ ]);++ $this->assertModelExists($company);+ $this->assertNotSoftDeleted($company);+ }++ public function test_deletable_companies_are_bulk_deleted()+ {+ $company1 = Company::factory()->create();+ $company2 = Company::factory()->create();+ $company3 = Company::factory()->create();++ $this->actingAs(User::factory()->deleteCompanies()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [$company1->id, $company2->id, $company3->id],+ ])+ ->assertRedirect(route('companies.index'));++ $this->assertSoftDeleted($company1);+ $this->assertSoftDeleted($company2);+ $this->assertSoftDeleted($company3);+ }++ public function test_partial_success_deletes_the_clean_ones_and_reports_the_rest()+ {+ // One clean company, one with an asset — the clean one should be+ // deleted, the other should be skipped and reported to the flash bag.+ $deletable = Company::factory()->create();+ $blocked = Company::factory()->create();+ Asset::factory()->create(['company_id' => $blocked->id]);++ $this->actingAs(User::factory()->deleteCompanies()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [$deletable->id, $blocked->id],+ ])+ ->assertRedirect(route('companies.index'))+ ->assertSessionHas('success')+ ->assertSessionHas('multi_error_messages');++ $this->assertSoftDeleted($deletable);+ $this->assertNotSoftDeleted($blocked);+ }++ public function test_nonexistent_ids_are_reported_and_do_not_break_the_batch()+ {+ $deletable = Company::factory()->create();++ $this->actingAs(User::factory()->deleteCompanies()->create())+ ->post(route('companies.bulk.delete'), [+ 'ids' => [$deletable->id, 999999],+ ])+ ->assertRedirect(route('companies.index'))+ ->assertSessionHas('multi_error_messages');++ $this->assertSoftDeleted($deletable);+ }+}diff --git a/tests/Feature/Console/Commands/PurgeCompaniesTest.php b/tests/Feature/Console/Commands/PurgeCompaniesTest.phpnew file mode 100644index 0000000000..5461c092b1--- /dev/null+++ b/tests/Feature/Console/Commands/PurgeCompaniesTest.php@@ -0,0 +1,32 @@+<?php++namespace Tests\Feature\Console\Commands;++use App\Models\Company;+use Tests\TestCase;++class PurgeCompaniesTest extends TestCase+{+ public function test_soft_deleted_company_is_force_deleted_by_purge()+ {+ $company = Company::factory()->create();+ $company->delete();++ $this->assertSoftDeleted($company);++ $this->artisan('snipeit:purge', ['--force' => 'true'])+ ->assertExitCode(0);++ $this->assertDatabaseMissing('companies', ['id' => $company->id]);+ }++ public function test_live_company_is_untouched_by_purge()+ {+ $company = Company::factory()->create();++ $this->artisan('snipeit:purge', ['--force' => 'true'])+ ->assertExitCode(0);++ $this->assertDatabaseHas('companies', ['id' => $company->id, 'deleted_at' => null]);+ }+}