Skip to content

A free open source IT asset/license management system

Fixed #19681 - stop parent companies from being blocked from deletion if children are soft-deleted

snipe0c4ec9ab09ae
diff --git a/app/Models/Company.php b/app/Models/Company.php
index d88ec01d38..92412f2cb9 100644
--- a/app/Models/Company.php
+++ b/app/Models/Company.php
@@ -506,17 +506,16 @@ final class Company extends SnipeModel
*/
public function parent(): BelongsTo
{
- return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScopes();
+ return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScopes([CompanyableScope::class]);
}
/**
* Child companies. The one-level-deep validator on parent_id guarantees
* children of a child cannot be created, so this is the full descendant set.
- * See parent() above for why the global scope is dropped.
*/
public function children()
{
- return $this->hasMany(self::class, 'parent_id')->withoutGlobalScopes();
+ return $this->hasMany(self::class, 'parent_id')->withoutGlobalScopes([CompanyableScope::class]);
}
/**
diff --git a/tests/Feature/Companies/Api/CompanyHierarchyTest.php b/tests/Feature/Companies/Api/CompanyHierarchyTest.php
index 6615aac16d..f158a9ba1c 100644
--- a/tests/Feature/Companies/Api/CompanyHierarchyTest.php
+++ b/tests/Feature/Companies/Api/CompanyHierarchyTest.php
@@ -740,4 +740,34 @@ class CompanyHierarchyTest extends TestCase
$this->assertNull($child->fresh()->parent_id);
}
+
+ // Soft-deleted children still counted against
+ // isDeletable(), blocking parent deletion after a child was removed.
+ public function test_soft_deleted_child_does_not_block_parent_deletion()
+ {
+ // isDeletable() calls Gate::allows('delete', ...) so we need an
+ // authenticated superuser for the gate to pass through to the
+ // children-count check the regression pins.
+ $this->actingAs(User::factory()->superuser()->create());
+
+ $parent = Company::factory()->create();
+ $child = Company::factory()->create(['parent_id' => $parent->id]);
+
+ $this->assertFalse($parent->fresh()->isDeletable(), 'Parent with an active child should not be deletable.');
+
+ $child->delete();
+
+ $this->assertSame(0, $parent->fresh()->children()->count(), 'Soft-deleted children must not show up in ->children().');
+ $this->assertTrue($parent->fresh()->isDeletable(), 'Parent should be deletable once its only child is soft-deleted.');
+ }
+
+ public function test_soft_deleted_parent_is_not_returned_on_children_parent_relation()
+ {
+ $parent = Company::factory()->create();
+ $child = Company::factory()->create(['parent_id' => $parent->id]);
+
+ $parent->delete();
+
+ $this->assertNull($child->fresh()->parent, 'A soft-deleted parent should not surface via ->parent on its child.');
+ }
}