A free open source IT asset/license management system
Guardrails for #19303 - added safer state when edge cases happen
snipe81520804e06a
diff --git a/app/Models/AssetModel.php b/app/Models/AssetModel.phpindex 21e5ac3ea0..c31451b1d3 100755--- a/app/Models/AssetModel.php+++ b/app/Models/AssetModel.php@@ -173,7 +173,15 @@ class AssetModel extends SnipeModelreturn 0;}+ // Guard the divisor: in principle available > 0 implies total > 0+ // (available is a subset of total via the RTD scope), but a data+ // anomaly — an asset counted by availableAssets but not by assets,+ // or a race between the two correlated subqueries — has surfaced as+ // DivisionByZeroError in production. Return 0 rather than throw.$total = $raw['assets_count'] ?? $this->assets()->count();+ if ($total === 0) {+ return 0;+ }return $available / $total * 100;}diff --git a/tests/Unit/AssetModelTest.php b/tests/Unit/AssetModelTest.phpindex 49f816e5d7..23a8a77077 100644--- a/tests/Unit/AssetModelTest.php+++ b/tests/Unit/AssetModelTest.php@@ -175,4 +175,54 @@ class AssetModelTest extends TestCase$this->assertEquals(100.0, $model->percentRemaining());}++ public function test_percent_remaining_returns_zero_when_eager_loaded_total_is_zero_but_available_is_not(): void+ {+ // Regression for a production DivisionByZeroError at+ // AssetModel::percentRemaining. In principle+ // availableAssets ⊆ assets+ // so `remaining > 0 && assets_count === 0` shouldn't happen, but a race+ // between the two correlated withCount subqueries — or a data anomaly+ // where an asset row is visible to one count but not the other — has+ // produced exactly that shape in the wild. percentRemaining must+ // absorb it, not throw.+ $category = Category::factory()->create(['category_type' => 'asset']);+ $model = AssetModel::factory()->create(['category_id' => $category->id]);+ $model->forceFill(['remaining' => 3, 'assets_count' => 0]);++ $this->assertSame(0, $model->percentRemaining());+ }++ public function test_percent_remaining_returns_zero_when_runtime_total_is_zero_but_available_is_not(): void+ {+ // Same guard, exercised through the non-eager-loaded fallback path+ // (Api\AssetModelsController::show and any callers that render a+ // single model without the index endpoint's withCount).+ $model = new class extends AssetModel+ {+ public function availableAssets()+ {+ return new class+ {+ public function count()+ {+ return 3;+ }+ };+ }++ public function assets()+ {+ return new class+ {+ public function count()+ {+ return 0;+ }+ };+ }+ };++ $this->assertSame(0, $model->percentRemaining());+ }}