A free open source IT asset/license management system
Better handle target cannot be blank erroring
snipee5b097cfbd71
diff --git a/app/Exceptions/MissingLogTarget.php b/app/Exceptions/MissingLogTarget.phpnew file mode 100644index 0000000000..11e338b778--- /dev/null+++ b/app/Exceptions/MissingLogTarget.php@@ -0,0 +1,17 @@+<?php++namespace App\Exceptions;++use Exception;++/**+ * Thrown by Loggable::logCheckout when the caller couldn't hand it a valid+ * target (missing entirely, or a hollow object with no id). Kept as a typed+ * exception so callers wrapping their work in a DB::transaction can catch+ * this specifically to roll back the transaction and return a real 4xx+ * response body, instead of letting it bubble up as an unhandled 500.+ */+class MissingLogTarget extends Exception+{+ //+}diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.phpindex b10ab8872c..ef20531119 100644--- a/app/Http/Controllers/Api/ComponentsController.php+++ b/app/Http/Controllers/Api/ComponentsController.php@@ -3,6 +3,7 @@namespace App\Http\Controllers\Api;use App\Events\CheckoutableCheckedIn;+use App\Exceptions\MissingLogTarget;use App\Helpers\Helper;use App\Http\Controllers\Controller;use App\Http\Requests\ImageUploadRequest;@@ -334,20 +335,36 @@ class ComponentsController extends Controller}// Keep pivot + action log in one transaction so checkout is all-or-nothing.- DB::transaction(function () use ($component, $request, $asset): void {- $component->assigned_to = $request->input('assigned_to');-- $component->assets()->attach($component->id, [+ try {+ DB::transaction(function () use ($component, $request, $asset): void {+ $component->assigned_to = $request->input('assigned_to');++ $component->assets()->attach($component->id, [+ 'component_id' => $component->id,+ 'created_at' => Carbon::now(),+ 'assigned_qty' => $request->input('assigned_qty', 1),+ 'created_by' => auth()->id(),+ 'asset_id' => $request->input('assigned_to'),+ 'note' => $request->input('note'),+ ]);++ $component->logCheckout($request->input('note'), $asset, null, [], $request->get('assigned_qty', 1));+ });+ } catch (MissingLogTarget $e) {+ // Loggable trait fell through its target check inside the+ // transaction. DB::transaction rethrew on exception, so the+ // pivot attach was rolled back and no checkout persisted.+ // Downgrade what would otherwise surface as an unhandled 500+ // to a 4xx the client can act on, and warning-log for+ // triage (see the same pattern in LicenseSeatsController).+ Log::warning('logCheckout target validation failed during component checkout.', ['component_id' => $component->id,- 'created_at' => Carbon::now(),- 'assigned_qty' => $request->input('assigned_qty', 1),- 'created_by' => auth()->id(),'asset_id' => $request->input('assigned_to'),- 'note' => $request->input('note'),+ 'error' => $e->getMessage(),]);- $component->logCheckout($request->input('note'), $asset, null, [], $request->get('assigned_qty', 1));- });+ return response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'), 422);+ }return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/components/message.checkout.success')));}diff --git a/app/Http/Controllers/Api/LicenseSeatsController.php b/app/Http/Controllers/Api/LicenseSeatsController.phpindex dbe1565f10..4455b8391b 100644--- a/app/Http/Controllers/Api/LicenseSeatsController.php+++ b/app/Http/Controllers/Api/LicenseSeatsController.php@@ -2,6 +2,7 @@namespace App\Http\Controllers\Api;+use App\Exceptions\MissingLogTarget;use App\Helpers\Helper;use App\Http\Controllers\Controller;use App\Http\Transformers\LicenseSeatsTransformer;@@ -13,6 +14,7 @@ use App\Models\User;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Log;class LicenseSeatsController extends Controller{@@ -137,127 +139,143 @@ class LicenseSeatsController extends Controller// Fetch the seat with a pessimistic lock inside a transaction so concurrent requests// on the same seat serialise rather than racing to overwrite each other's assignment.- DB::transaction(function () use ($request, $licenseId, $seatId, $validated, &$errorResponse, &$updatedSeat): void {- $licenseSeat = LicenseSeat::with(['license', 'asset', 'user'])- ->lockForUpdate()- ->find($seatId);+ try {+ DB::transaction(function () use ($request, $licenseId, $seatId, $validated, &$errorResponse, &$updatedSeat): void {+ $licenseSeat = LicenseSeat::with(['license', 'asset', 'user'])+ ->lockForUpdate()+ ->find($seatId);- if (! $licenseSeat) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Seat not found'));+ if (! $licenseSeat) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Seat not found'));- return;- }+ return;+ }- $license = $licenseSeat->license;- if (! $license || $license->id != intval($licenseId)) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license'));+ $license = $licenseSeat->license;+ if (! $license || $license->id != intval($licenseId)) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license'));- return;- }+ return;+ }- $targetUser = null;- if (! is_null($request->input('assigned_to'))) {- // Resolve unscoped target so we can return a clean cross-company error instead of a hidden-not-found.- $targetUser = User::withoutGlobalScopes()->find($request->input('assigned_to'));+ $targetUser = null;+ if (! is_null($request->input('assigned_to'))) {+ // Resolve unscoped target so we can return a clean cross-company error instead of a hidden-not-found.+ $targetUser = User::withoutGlobalScopes()->find($request->input('assigned_to'));- if (! $targetUser) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));+ if (! $targetUser) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));- return;- }+ return;+ }- if ((Setting::getSettings()->full_multiple_companies_support == '1') && (! $targetUser->companies()->where('companies.id', $license->company_id)->exists())) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && (! $targetUser->companies()->where('companies.id', $license->company_id)->exists())) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));- return;+ return;+ }}- }- $targetAsset = null;- if (! is_null($request->input('asset_id'))) {- // Resolve unscoped target so FMCS company mismatch can be enforced explicitly.- $targetAsset = Asset::withoutGlobalScopes()->find($request->input('asset_id'));+ $targetAsset = null;+ if (! is_null($request->input('asset_id'))) {+ // Resolve unscoped target so FMCS company mismatch can be enforced explicitly.+ $targetAsset = Asset::withoutGlobalScopes()->find($request->input('asset_id'));- if (! $targetAsset) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));+ if (! $targetAsset) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));- return;- }+ return;+ }- if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($license->company_id !== $targetAsset->company_id)) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($license->company_id !== $targetAsset->company_id)) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));- return;+ return;+ }}- }- $oldUser = $licenseSeat->user;- $oldAsset = $licenseSeat->asset;+ $oldUser = $licenseSeat->user;+ $oldAsset = $licenseSeat->asset;- $licenseSeat->fill($validated);+ $licenseSeat->fill($validated);- $assignmentTouched = $licenseSeat->isDirty('assigned_to') || $licenseSeat->isDirty('asset_id');- $anythingTouched = $licenseSeat->isDirty();+ $assignmentTouched = $licenseSeat->isDirty('assigned_to') || $licenseSeat->isDirty('asset_id');+ $anythingTouched = $licenseSeat->isDirty();- if (! $anythingTouched) {- $updatedSeat = $licenseSeat;+ if (! $anythingTouched) {+ $updatedSeat = $licenseSeat;- return;- }+ return;+ }- if ($assignmentTouched && $licenseSeat->unreassignable_seat) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/licenses/message.checkout.unavailable')));+ if ($assignmentTouched && $licenseSeat->unreassignable_seat) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/licenses/message.checkout.unavailable')));- return;- }+ return;+ }- // Are the assignment fields cleared? If yes, this is a checkin operation.- $is_checkin = ($assignmentTouched && $licenseSeat->assigned_to === null && $licenseSeat->asset_id === null);+ // Are the assignment fields cleared? If yes, this is a checkin operation.+ $is_checkin = ($assignmentTouched && $licenseSeat->assigned_to === null && $licenseSeat->asset_id === null);- // The logging functions expect only one "target"; assets take precedence over users.- $target = null;- if ($licenseSeat->isDirty('assigned_to')) {- $target = $is_checkin ? $oldUser : $targetUser;- }- if ($licenseSeat->isDirty('asset_id')) {- $target = $is_checkin ? $oldAsset : $targetAsset;- }+ // The logging functions expect only one "target"; assets take precedence over users.+ $target = null;+ if ($licenseSeat->isDirty('assigned_to')) {+ $target = $is_checkin ? $oldUser : $targetUser;+ }+ if ($licenseSeat->isDirty('asset_id')) {+ $target = $is_checkin ? $oldAsset : $targetAsset;+ }- if ($assignmentTouched && is_null($target)) {- // Both fields are null but one was provided — the related model is purged or bad data.- if (! is_null($request->input('asset_id')) || ! is_null($request->input('assigned_to'))) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));+ if ($assignmentTouched && is_null($target)) {+ // Both fields are null but one was provided — the related model is purged or bad data.+ if (! is_null($request->input('asset_id')) || ! is_null($request->input('assigned_to'))) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));- return;+ return;+ }}- }- if (! $licenseSeat->save()) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, $licenseSeat->getErrors()));+ if (! $licenseSeat->save()) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, $licenseSeat->getErrors()));- return;- }+ return;+ }- if ($assignmentTouched) {- if ($is_checkin) {- if (! $licenseSeat->license->reassignable) {- $licenseSeat->unreassignable_seat = true;+ if ($assignmentTouched) {+ if ($is_checkin) {+ if (! $licenseSeat->license->reassignable) {+ $licenseSeat->unreassignable_seat = true;- if (! $licenseSeat->save()) {- $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, $licenseSeat->getErrors()));+ if (! $licenseSeat->save()) {+ $errorResponse = response()->json(Helper::formatStandardApiResponse('error', null, $licenseSeat->getErrors()));- return;+ return;+ }}- }- $licenseSeat->logCheckin($target, $licenseSeat->notes);- } else {- $licenseSeat->logCheckout($request->input('notes'), $target);+ $licenseSeat->logCheckin($target, $licenseSeat->notes);+ } else {+ $licenseSeat->logCheckout($request->input('notes'), $target);+ }}- }- $updatedSeat = $licenseSeat;- });+ $updatedSeat = $licenseSeat;+ });+ } catch (MissingLogTarget $e) {+ // Loggable trait fell through its target check inside the transaction.+ // The transaction has already rolled back (DB::transaction rethrows on+ // exception) so no seat assignment persisted. Downgrade the surfaced+ // 500 to a 4xx response body the client can act on, and warning-log+ // so we still see systemic regressions in Rollbar without alerting as+ // an unhandled exception.+ Log::warning('logCheckout target validation failed during license seat update.', [+ 'license_id' => $licenseId,+ 'seat_id' => $seatId,+ 'error' => $e->getMessage(),+ ]);++ return response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'), 422);+ }if ($errorResponse) {return $errorResponse;diff --git a/app/Models/Traits/Loggable.php b/app/Models/Traits/Loggable.phpindex 894c0b7e85..02c008644a 100644--- a/app/Models/Traits/Loggable.php+++ b/app/Models/Traits/Loggable.php@@ -2,6 +2,7 @@namespace App\Models\Traits;+use App\Exceptions\MissingLogTarget;use App\Models\Actionlog;use App\Models\Asset;use App\Models\CompanyableScope;@@ -126,6 +127,13 @@ trait Loggable* @since [v3.4]** @return Actionlog+ *+ * @throws MissingLogTarget When the caller couldn't hand us a valid+ * target. Deliberately typed so callers wrapping+ * their work in a DB::transaction can catch it+ * specifically, roll the transaction back, and+ * return a proper 4xx response body instead of+ * letting an unhandled 500 leak into the caller.*/public function logCheckout($note, $target, $action_date = null, $originalValues = [], $quantity = 1){@@ -140,15 +148,11 @@ trait Loggable}if (! isset($target)) {- throw new \Exception('All checkout logs require a target.');-- return;+ throw new MissingLogTarget('All checkout logs require a target.');}if (! isset($target->id)) {- throw new \Exception('That target seems invalid (no target ID available).');-- return;+ throw new MissingLogTarget('That target seems invalid (no target ID available).');}$log->target_type = get_class($target);diff --git a/tests/Unit/Models/LoggableTest.php b/tests/Unit/Models/LoggableTest.phpnew file mode 100644index 0000000000..a0fde5f40c--- /dev/null+++ b/tests/Unit/Models/LoggableTest.php@@ -0,0 +1,42 @@+<?php++namespace Tests\Unit\Models;++use App\Exceptions\MissingLogTarget;+use App\Models\Asset;+use App\Models\User;+use Tests\TestCase;++/**+ * The Loggable trait provides the logCheckout() / logCheckin() helpers used by+ * every checkout-capable model. logCheckout() throws MissingLogTarget when the+ * caller can't hand it a valid target so callers wrapping their work in a+ * DB::transaction can catch it specifically, roll back cleanly, and return a+ * proper 4xx response body instead of leaking an unhandled 500.+ */+class LoggableTest extends TestCase+{+ public function test_log_checkout_throws_missing_log_target_when_target_is_missing()+ {+ $this->actingAs(User::factory()->create());+ $asset = Asset::factory()->create();++ $this->expectException(MissingLogTarget::class);++ $asset->logCheckout('some note', null);+ }++ public function test_log_checkout_throws_missing_log_target_when_target_has_no_id()+ {+ $this->actingAs(User::factory()->create());+ $asset = Asset::factory()->create();++ // Fresh, unsaved model: a real object but its id is null, so the+ // shape check should refuse to log against it.+ $badTarget = new User;++ $this->expectException(MissingLogTarget::class);++ $asset->logCheckout('some note', $badTarget);+ }+}