Skip to content

A free open source IT asset/license management system

Wrap the checkout in a transaction and add tests

snipe2a56f6573d64
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.php
index 2dab3f876a..c8170aa551 100644
--- a/app/Http/Controllers/Api/AccessoriesController.php
+++ b/app/Http/Controllers/Api/AccessoriesController.php
@@ -15,11 +15,13 @@ use App\Http\Transformers\SelectlistTransformer;
use App\Models\Accessory;
use App\Models\AccessoryCheckout;
use App\Models\Company;
+use App\Models\Setting;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
+use Illuminate\Support\Facades\DB;
class AccessoriesController extends Controller
{
@@ -300,40 +302,49 @@ class AccessoriesController extends Controller
{
$this->authorize('checkout', $accessory);
$target = $this->determineCheckoutTarget();
- $accessory->checkout_qty = $request->input('checkout_qty', 1);
-
- for ($i = 0; $i < $accessory->checkout_qty; $i++) {
-
- $accessory_checkout = new AccessoryCheckout([
- 'accessory_id' => $accessory->id,
- 'created_at' => Carbon::now(),
- 'assigned_to' => $target->id,
- 'assigned_type' => $target::class,
- 'note' => $request->input('note'),
- ]);
-
- $accessory_checkout->created_by = auth()->id();
- $accessory_checkout->save();
- $payload = [
- 'accessory_id' => $accessory->id,
- 'assigned_to' => $target->id,
- 'assigned_type' => $target::class,
- 'note' => $request->input('note'),
- 'created_by' => auth()->id(),
- 'pivot' => $accessory_checkout->id,
- ];
+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($accessory->company_id !== $target->company_id)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
}
- // Set this value to be able to pass the qty through to the event
- event(new CheckoutableCheckedOut(
- $accessory,
- $target,
- auth()->user(),
- $request->input('note'),
- [],
- $accessory->checkout_qty,
- ));
+ $accessory->checkout_qty = $request->input('checkout_qty', 1);
+ $payload = null;
+
+ // Keep checkout rows and checkout log/event atomic to avoid ghost assignments.
+ DB::transaction(function () use ($accessory, $request, $target, &$payload): void {
+ for ($i = 0; $i < $accessory->checkout_qty; $i++) {
+
+ $accessory_checkout = new AccessoryCheckout([
+ 'accessory_id' => $accessory->id,
+ 'created_at' => Carbon::now(),
+ 'assigned_to' => $target->id,
+ 'assigned_type' => $target::class,
+ 'note' => $request->input('note'),
+ ]);
+
+ $accessory_checkout->created_by = auth()->id();
+ $accessory_checkout->save();
+
+ $payload = [
+ 'accessory_id' => $accessory->id,
+ 'assigned_to' => $target->id,
+ 'assigned_type' => $target::class,
+ 'note' => $request->input('note'),
+ 'created_by' => auth()->id(),
+ 'pivot' => $accessory_checkout->id,
+ ];
+ }
+
+ // Set this value to be able to pass the qty through to the event.
+ event(new CheckoutableCheckedOut(
+ $accessory,
+ $target,
+ auth()->user(),
+ $request->input('note'),
+ [],
+ $accessory->checkout_qty,
+ ));
+ });
return response()->json(Helper::formatStandardApiResponse('success', $payload, trans('admin/accessories/message.checkout.success')));
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.php
index b3566573bd..2f75ec9306 100644
--- a/app/Http/Controllers/Api/AssetsController.php
+++ b/app/Http/Controllers/Api/AssetsController.php
@@ -706,18 +706,35 @@ class AssetsController extends Controller
}
}
- if ($asset->save()) {
- if ($request->input('assigned_user')) {
- $target = User::find(request('assigned_user'));
- } elseif ($request->input('assigned_asset')) {
- $target = Asset::find(request('assigned_asset'));
- } elseif ($request->input('assigned_location')) {
- $target = Location::find(request('assigned_location'));
+ $target = $this->resolveCheckoutTargetForAssetMutation($request);
+ $requestedCheckout = $request->filled('assigned_user') || $request->filled('assigned_asset') || $request->filled('assigned_location');
+
+ if ($requestedCheckout && (! $target)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')));
+ }
+
+ if ($requestedCheckout) {
+ $companyMismatchResponse = $this->checkoutCompanyMismatchResponse($asset, $target);
+ if ($companyMismatchResponse) {
+ return $companyMismatchResponse;
+ }
+ }
+
+ $stored = DB::transaction(function () use ($asset, $request, $target, $requestedCheckout): bool {
+ if (! $asset->save()) {
+ return false;
}
- if (isset($target)) {
- $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), '', 'Checked out on asset creation', e($request->input('name')));
+
+ if ($requestedCheckout) {
+ // Keep create + optional checkout side effects atomic.
+ return $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), '', 'Checked out on asset creation', e($request->input('name')));
}
+ return true;
+ });
+
+ if ($stored) {
+
if ($asset->image) {
$asset->image = $asset->getImageUrl();
}
@@ -792,25 +809,54 @@ class AssetsController extends Controller
}
}
}
- if ($asset->save()) {
- if (($request->filled('assigned_user')) && ($target = User::find($request->input('assigned_user')))) {
- $location = $target->location_id;
- } elseif (($request->filled('assigned_asset')) && ($target = Asset::find($request->input('assigned_asset')))) {
- $location = $target->location_id;
-
- Asset::where('assigned_type', Asset::class)->where('assigned_to', $asset->id)
- ->update(['location_id' => $target->location_id]);
- } elseif (($request->filled('assigned_location')) && ($target = Location::find($request->input('assigned_location')))) {
- $location = $target->id;
+ $target = $this->resolveCheckoutTargetForAssetMutation($request, $asset->id);
+ $requestedCheckout = $request->filled('assigned_user') || $request->filled('assigned_asset') || $request->filled('assigned_location');
+
+ if ($requestedCheckout && (! $target)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.does_not_exist')));
+ }
+
+ if ($requestedCheckout) {
+ $companyMismatchResponse = $this->checkoutCompanyMismatchResponse($asset, $target);
+ if ($companyMismatchResponse) {
+ return $companyMismatchResponse;
+ }
+ }
+
+ $updated = DB::transaction(function () use ($asset, $request, $target, $requestedCheckout): bool {
+ if (! $asset->save()) {
+ return false;
}
- if (isset($target)) {
+ if ($requestedCheckout) {
// Using `->has` preserves the asset name if the name parameter was not included in request.
$asset_name = request()->has('name') ? request('name') : $asset->name;
- $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), '', 'Checked out on asset update', $asset_name, $location);
+ $location = null;
+ if ($request->filled('assigned_user')) {
+ $location = $target->location_id;
+ } elseif ($request->filled('assigned_asset')) {
+ $location = $target->location_id;
+ } elseif ($request->filled('assigned_location')) {
+ $location = $target->id;
+ }
+
+ // Keep update + optional checkout side effects atomic.
+ if (! $asset->checkOut($target, auth()->user(), date('Y-m-d H:i:s'), '', 'Checked out on asset update', $asset_name, $location)) {
+ return false;
+ }
+
+ if ($request->filled('assigned_asset')) {
+ Asset::where('assigned_type', Asset::class)->where('assigned_to', $asset->id)
+ ->update(['location_id' => $target->location_id]);
+ }
}
+ return true;
+ });
+
+ if ($updated) {
+
if ($asset->image) {
$asset->image = $asset->getImageUrl();
}
@@ -829,6 +875,36 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, $asset->getErrors()), 200);
}
+ private function resolveCheckoutTargetForAssetMutation(Request $request, ?int $assetId = null): User|Asset|Location|null
+ {
+ if ($request->filled('assigned_user')) {
+ return User::withoutGlobalScopes()->find($request->input('assigned_user'));
+ }
+
+ if ($request->filled('assigned_asset')) {
+ return Asset::withoutGlobalScopes()->where('id', '!=', $assetId)->find($request->input('assigned_asset'));
+ }
+
+ if ($request->filled('assigned_location')) {
+ return Location::withoutGlobalScopes()->find($request->input('assigned_location'));
+ }
+
+ return null;
+ }
+
+ private function checkoutCompanyMismatchResponse(Asset $asset, User|Asset|Location $target): ?JsonResponse
+ {
+ if ((Setting::getSettings()->full_multiple_companies_support == '1')
+ && (! is_null($asset->company_id))
+ && (! is_null($target->company_id))
+ && ((int) $asset->company_id !== (int) $target->company_id)
+ ) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
+ }
+
+ return null;
+ }
+
/**
* Delete a given asset (mark as deleted).
*
@@ -905,6 +981,7 @@ class AssetsController extends Controller
*/
public function checkoutByTag(AssetCheckoutRequest $request, $tag): JsonResponse
{
+ // Use the same hardened checkout path as ID-based checkout.
if ($asset = Asset::where('asset_tag', $tag)->first()) {
return $this->checkout($request, $asset->id);
}
@@ -940,19 +1017,22 @@ class AssetsController extends Controller
// This item is checked out to a location
if (request('checkout_to_type') == 'location') {
- $target = Location::find(request('assigned_location'));
+ // Resolve unscoped target first so FMCS mismatch can be handled explicitly.
+ $target = Location::withoutGlobalScopes()->find(request('assigned_location'));
$asset->location_id = ($target) ? $target->id : '';
$error_payload['target_id'] = $request->input('assigned_location');
$error_payload['target_type'] = 'location';
} elseif (request('checkout_to_type') == 'asset') {
- $target = Asset::where('id', '!=', $asset_id)->find(request('assigned_asset'));
+ // Resolve unscoped target first so FMCS mismatch can be handled explicitly.
+ $target = Asset::withoutGlobalScopes()->where('id', '!=', $asset_id)->find(request('assigned_asset'));
// Override with the asset's location_id if it has one
$asset->location_id = (($target) && (isset($target->location_id))) ? $target->location_id : '';
$error_payload['target_id'] = $request->input('assigned_asset');
$error_payload['target_type'] = 'asset';
} elseif (request('checkout_to_type') == 'user') {
// Fetch the target and set the asset's new location_id
- $target = User::find(request('assigned_user'));
+ // Resolve unscoped target first so FMCS mismatch can be handled explicitly.
+ $target = User::withoutGlobalScopes()->find(request('assigned_user'));
$asset->location_id = (($target) && (isset($target->location_id))) ? $target->location_id : '';
$error_payload['target_id'] = $request->input('assigned_user');
$error_payload['target_type'] = 'user';
@@ -971,6 +1051,16 @@ class AssetsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', $error_payload, 'Checkout target for asset '.e($asset->asset_tag).' is invalid - '.$error_payload['target_type'].' does not exist.'));
}
+ // In FMCS mode, enforce explicit same-company target checks before mutating checkout state.
+ $targetCompanyId = data_get($target, 'company_id');
+ if ((Setting::getSettings()->full_multiple_companies_support == '1')
+ && (! is_null($asset->company_id))
+ && (! is_null($targetCompanyId))
+ && ((int) $asset->company_id !== (int) $targetCompanyId)
+ ) {
+ return response()->json(Helper::formatStandardApiResponse('error', $error_payload, trans('general.error_user_company')));
+ }
+
$checkout_at = request('checkout_at', date('Y-m-d H:i:s'));
$expected_checkin = request('expected_checkin', null);
$note = request('note', null);
@@ -985,7 +1075,12 @@ class AssetsController extends Controller
// $asset->location_id = $target->rtd_location_id;
// }
- if ($asset->checkOut($target, auth()->user(), $checkout_at, $expected_checkin, $note, $asset_name, $asset->location_id)) {
+ // Keep checkout mutation + checkout logging/event side effects atomic.
+ $wasCheckedOut = DB::transaction(function () use ($asset, $target, $checkout_at, $expected_checkin, $note, $asset_name): bool {
+ return $asset->checkOut($target, auth()->user(), $checkout_at, $expected_checkin, $note, $asset_name, $asset->location_id);
+ });
+
+ if ($wasCheckedOut) {
return response()->json(Helper::formatStandardApiResponse('success', ['asset' => e($asset->asset_tag)], trans('admin/hardware/message.checkout.success')));
}
diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.php
index 10a8a90471..bf754ba1a5 100644
--- a/app/Http/Controllers/Api/ComponentsController.php
+++ b/app/Http/Controllers/Api/ComponentsController.php
@@ -315,6 +315,8 @@ class ComponentsController extends Controller
}
if ($component->numRemaining() >= $request->input('assigned_qty')) {
+ // Resolve the raw target first, then enforce FMCS explicitly.
+ // Scoped lookup can hide cross-company records and lead to partial writes.
$asset = Asset::withoutGlobalScopes()->find($request->input('assigned_to'));
if (! $asset) {
@@ -325,6 +327,7 @@ class ComponentsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
}
+ // 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');
diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.php
index 58f15f5140..1ef3bff1e3 100644
--- a/app/Http/Controllers/Api/ConsumablesController.php
+++ b/app/Http/Controllers/Api/ConsumablesController.php
@@ -13,9 +13,11 @@ use App\Http\Transformers\ConsumablesTransformer;
use App\Http\Transformers\SelectlistTransformer;
use App\Models\Company;
use App\Models\Consumable;
+use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
class ConsumablesController extends Controller
{
@@ -306,34 +308,42 @@ class ConsumablesController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, trans('admin/consumables/message.checkout.unavailable', ['requested' => $consumable->checkout_qty, 'remaining' => $consumable->numRemaining()])));
}
- // Check if the user exists - @TODO: this should probably be handled via validation, not here??
- if (! $user = User::find($request->input('assigned_to'))) {
+ // Resolve the raw target first, then enforce FMCS explicitly.
+ // Scoped lookup can hide cross-company users and make failures ambiguous.
+ if (! $user = User::withoutGlobalScopes()->find($request->input('assigned_to'))) {
// Return error message
return response()->json(Helper::formatStandardApiResponse('error', null, 'No user found'));
}
+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($consumable->company_id !== $user->company_id)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
+ }
+
// Update the consumable data
$consumable->assigned_to = $request->input('assigned_to');
- for ($i = 0; $i < $consumable->checkout_qty; $i++) {
- $consumable->users()->attach($consumable->id,
- [
- 'consumable_id' => $consumable->id,
- 'created_by' => $user->id,
- 'assigned_to' => $request->input('assigned_to'),
- 'note' => $request->input('note'),
- ]
- );
- }
-
- event(new CheckoutableCheckedOut(
- $consumable,
- $user,
- auth()->user(),
- $request->input('note'),
- [],
- $consumable->checkout_qty,
- ));
+ // Keep pivot writes and checkout log/event atomic to avoid partial checkout state.
+ DB::transaction(function () use ($consumable, $request, $user): void {
+ for ($i = 0; $i < $consumable->checkout_qty; $i++) {
+ $consumable->users()->attach($consumable->id,
+ [
+ 'consumable_id' => $consumable->id,
+ 'created_by' => $user->id,
+ 'assigned_to' => $request->input('assigned_to'),
+ 'note' => $request->input('note'),
+ ]
+ );
+ }
+
+ event(new CheckoutableCheckedOut(
+ $consumable,
+ $user,
+ auth()->user(),
+ $request->input('note'),
+ [],
+ $consumable->checkout_qty,
+ ));
+ });
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/consumables/message.checkout.success')));
diff --git a/app/Http/Controllers/Api/LicenseSeatsController.php b/app/Http/Controllers/Api/LicenseSeatsController.php
index fdee549d67..ba93e52ff1 100644
--- a/app/Http/Controllers/Api/LicenseSeatsController.php
+++ b/app/Http/Controllers/Api/LicenseSeatsController.php
@@ -8,9 +8,11 @@ use App\Http\Transformers\LicenseSeatsTransformer;
use App\Models\Asset;
use App\Models\License;
use App\Models\LicenseSeat;
+use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\DB;
class LicenseSeatsController extends Controller
{
@@ -106,7 +108,8 @@ class LicenseSeatsController extends Controller
'prohibits:asset_id',
// must be a valid user or null to unassign
function ($attribute, $value, $fail) {
- if (! is_null($value) && ! User::where('id', $value)->whereNull('deleted_at')->exists()) {
+ // Validate existence without company scopes; FMCS checks happen explicitly below.
+ if (! is_null($value) && ! User::withoutGlobalScopes()->where('id', $value)->whereNull('deleted_at')->exists()) {
$fail('The selected assigned_to is invalid.');
}
},
@@ -118,7 +121,8 @@ class LicenseSeatsController extends Controller
'prohibits:assigned_to',
// must be a valid asset or null to unassign
function ($attribute, $value, $fail) {
- if (! is_null($value) && ! Asset::where('id', $value)->whereNull('deleted_at')->exists()) {
+ // Validate existence without company scopes; FMCS checks happen explicitly below.
+ if (! is_null($value) && ! Asset::withoutGlobalScopes()->where('id', $value)->whereNull('deleted_at')->exists()) {
$fail('The selected asset_id is invalid.');
}
},
@@ -139,6 +143,34 @@ class LicenseSeatsController extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, 'Seat does not belong to the specified license'));
}
+ $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) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));
+ }
+
+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($license->company_id !== $targetUser->company_id)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
+ }
+ }
+
+ $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) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, 'Target not found'));
+ }
+
+ if ((Setting::getSettings()->full_multiple_companies_support == '1') && ($license->company_id !== $targetAsset->company_id)) {
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.error_user_company')));
+ }
+ }
+
$oldUser = $licenseSeat->user;
$oldAsset = $licenseSeat->asset;
@@ -166,11 +198,11 @@ class LicenseSeatsController extends Controller
// the logging functions expect only one "target". if both asset and user are present in the request,
// we simply let assets take precedence over users...
if ($licenseSeat->isDirty('assigned_to')) {
- $target = $is_checkin ? $oldUser : User::find($licenseSeat->assigned_to);
+ $target = $is_checkin ? $oldUser : $targetUser;
}
if ($licenseSeat->isDirty('asset_id')) {
- $target = $is_checkin ? $oldAsset : Asset::find($licenseSeat->asset_id);
+ $target = $is_checkin ? $oldAsset : $targetAsset;
}
if ($assignmentTouched && is_null($target)) {
@@ -181,13 +213,22 @@ class LicenseSeatsController extends Controller
}
}
- if ($licenseSeat->save()) {
+ // Keep seat updates and checkout/checkin logging atomic to prevent partial state changes.
+ $updated = DB::transaction(function () use ($licenseSeat, $assignmentTouched, $is_checkin, $target, $request): bool {
+ if (! $licenseSeat->save()) {
+ return false;
+ }
+
if ($assignmentTouched) {
if ($is_checkin) {
if (! $licenseSeat->license->reassignable) {
$licenseSeat->unreassignable_seat = true;
- $licenseSeat->save();
+
+ if (! $licenseSeat->save()) {
+ return false;
+ }
}
+
// todo: skip if target is null?
$licenseSeat->logCheckin($target, $licenseSeat->notes);
} else {
@@ -196,6 +237,10 @@ class LicenseSeatsController extends Controller
}
}
+ return true;
+ });
+
+ if ($updated) {
return response()->json(Helper::formatStandardApiResponse('success', $licenseSeat, trans('admin/licenses/message.update.success')));
}
diff --git a/tests/Feature/Assets/Api/StoreAssetTest.php b/tests/Feature/Assets/Api/StoreAssetTest.php
index 402dbc8016..83245750d7 100644
--- a/tests/Feature/Assets/Api/StoreAssetTest.php
+++ b/tests/Feature/Assets/Api/StoreAssetTest.php
@@ -577,6 +577,43 @@ class StoreAssetTest extends TestCase
$this->assertHasTheseActionLogs($asset, ['create', 'checkout']);
}
+ public function test_store_rejects_cross_company_checkout_target_with_full_company_support_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $actorInCompanyA = User::factory()->createAssets()->for($companyA)->create();
+ $targetUserInCompanyB = User::factory()->for($companyB)->create();
+
+ $model = AssetModel::factory()->create();
+ $status = Statuslabel::factory()->readyToDeploy()->create();
+ $assetTag = 'fmcs-store-rollback-asset';
+
+ $this->actingAsForApi($actorInCompanyA)
+ ->postJson(route('api.assets.store'), [
+ 'asset_tag' => $assetTag,
+ 'model_id' => $model->id,
+ 'status_id' => $status->id,
+ 'company_id' => $companyA->id,
+ 'assigned_user' => $targetUserInCompanyB->id,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $this->assertDatabaseMissing('assets', [
+ 'asset_tag' => $assetTag,
+ ]);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $targetUserInCompanyB->id,
+ 'item_type' => Asset::class,
+ ]);
+ }
+
public static function checkoutTargets()
{
yield 'Users' => [
diff --git a/tests/Feature/Assets/Api/UpdateAssetTest.php b/tests/Feature/Assets/Api/UpdateAssetTest.php
index 3489a9c089..daab37514e 100644
--- a/tests/Feature/Assets/Api/UpdateAssetTest.php
+++ b/tests/Feature/Assets/Api/UpdateAssetTest.php
@@ -422,6 +422,40 @@ class UpdateAssetTest extends TestCase
$this->assertEquals($asset->assigned_type, 'App\Models\User');
}
+ public function test_update_rejects_cross_company_checkout_target_with_full_company_support_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $asset = Asset::factory()->for($companyA)->create(['name' => 'Original Name']);
+ $actorInCompanyA = User::factory()->editAssets()->for($companyA)->create();
+ $targetUserInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($actorInCompanyA)
+ ->patchJson(route('api.assets.update', $asset->id), [
+ 'name' => 'Name That Should Roll Back',
+ 'assigned_user' => $targetUserInCompanyB->id,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $asset->refresh();
+
+ $this->assertEquals('Original Name', $asset->name);
+ $this->assertNull($asset->assigned_to);
+ $this->assertNull($asset->assigned_type);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $targetUserInCompanyB->id,
+ 'item_type' => Asset::class,
+ 'item_id' => $asset->id,
+ ]);
+ }
+
public function test_checkout_to_user_with_assigned_to_and_assigned_type()
{
$asset = Asset::factory()->create();
diff --git a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php
index 7156021a2c..1e3f5c74eb 100644
--- a/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php
+++ b/tests/Feature/Checkouts/Api/AccessoryCheckoutTest.php
@@ -5,6 +5,7 @@ namespace Tests\Feature\Checkouts\Api;
use App\Mail\CheckoutAccessoryMail;
use App\Models\Accessory;
use App\Models\Actionlog;
+use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
use Tests\Concerns\TestsPermissionsRequirement;
@@ -189,4 +190,42 @@ class AccessoryCheckoutTest extends TestCase implements TestsPermissionsRequirem
$this->assertHasTheseActionLogs($accessory, ['create', 'checkout']);
}
+
+ public function test_superuser_cannot_checkout_accessory_to_a_target_in_another_company_when_full_company_support_is_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $superuser = User::factory()->superuser()->create(['company_id' => null]);
+ $accessoryInCompanyA = Accessory::factory()->for($companyA)->create(['qty' => 1]);
+ $userInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($superuser)
+ ->postJson(route('api.accessories.checkout', $accessoryInCompanyA), [
+ 'assigned_user' => $userInCompanyB->id,
+ 'checkout_to_type' => 'user',
+ 'checkout_qty' => 1,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $this->assertDatabaseMissing('accessories_checkout', [
+ 'accessory_id' => $accessoryInCompanyA->id,
+ 'assigned_to' => $userInCompanyB->id,
+ 'assigned_type' => User::class,
+ ]);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $superuser->id,
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $userInCompanyB->id,
+ 'item_type' => Accessory::class,
+ 'item_id' => $accessoryInCompanyA->id,
+ ]);
+
+ $this->assertEquals(1, $accessoryInCompanyA->fresh()->numRemaining());
+ }
}
diff --git a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php b/tests/Feature/Checkouts/Api/AssetCheckoutTest.php
index d83d8307b3..8774092a36 100644
--- a/tests/Feature/Checkouts/Api/AssetCheckoutTest.php
+++ b/tests/Feature/Checkouts/Api/AssetCheckoutTest.php
@@ -4,6 +4,7 @@ namespace Tests\Feature\Checkouts\Api;
use App\Events\CheckoutableCheckedOut;
use App\Models\Asset;
+use App\Models\Company;
use App\Models\Location;
use App\Models\Statuslabel;
use App\Models\User;
@@ -95,7 +96,72 @@ class AssetCheckoutTest extends TestCase
public function test_cannot_checkout_across_companies_when_full_company_support_enabled()
{
- $this->markTestIncomplete('This is not implemented');
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $actorInCompanyA = User::factory()->checkoutAssets()->for($companyA)->create();
+ $assetInCompanyA = Asset::factory()->for($companyA)->create();
+ $userInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($actorInCompanyA)
+ ->postJson(route('api.asset.checkout', $assetInCompanyA), [
+ 'checkout_to_type' => 'user',
+ 'assigned_user' => $userInCompanyB->id,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $assetInCompanyA->refresh();
+
+ $this->assertNull($assetInCompanyA->assigned_to);
+ $this->assertNull($assetInCompanyA->assigned_type);
+ $this->assertEquals(0, $assetInCompanyA->checkout_counter);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $actorInCompanyA->id,
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $userInCompanyB->id,
+ 'item_type' => Asset::class,
+ 'item_id' => $assetInCompanyA->id,
+ ]);
+ }
+
+ public function test_checkout_by_tag_cannot_checkout_across_companies_when_full_company_support_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $actorInCompanyA = User::factory()->checkoutAssets()->for($companyA)->create();
+ $assetInCompanyA = Asset::factory()->for($companyA)->create();
+ $userInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($actorInCompanyA)
+ ->postJson(route('api.assets.checkout.bytag', $assetInCompanyA->asset_tag), [
+ 'checkout_to_type' => 'user',
+ 'assigned_user' => $userInCompanyB->id,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $assetInCompanyA->refresh();
+
+ $this->assertNull($assetInCompanyA->assigned_to);
+ $this->assertNull($assetInCompanyA->assigned_type);
+ $this->assertEquals(0, $assetInCompanyA->checkout_counter);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $actorInCompanyA->id,
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $userInCompanyB->id,
+ 'item_type' => Asset::class,
+ 'item_id' => $assetInCompanyA->id,
+ ]);
}
/**
diff --git a/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php b/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php
index 8893e17875..22814a70b8 100644
--- a/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php
+++ b/tests/Feature/Checkouts/Api/ComponentCheckoutTest.php
@@ -126,6 +126,7 @@ class ComponentCheckoutTest extends TestCase implements TestsFullMultipleCompani
public function test_adheres_to_full_multiple_companies_support_scoping()
{
+
[$companyA, $companyB] = Company::factory()->count(2)->create();
$userForCompanyA = User::factory()->for($companyA)->create();
@@ -139,4 +140,76 @@ class ComponentCheckoutTest extends TestCase implements TestsFullMultipleCompani
])
->assertForbidden();
}
+
+ public function test_cannot_checkout_component_to_an_asset_in_another_company_when_full_company_support_is_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $userInCompanyA = User::factory()->checkoutComponents()->for($companyA)->create();
+ $componentInCompanyA = Component::factory()->for($companyA)->create(['qty' => 1]);
+ $assetInCompanyB = Asset::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($userInCompanyA)
+ ->postJson(route('api.components.checkout', $componentInCompanyA->id), [
+ 'assigned_to' => $assetInCompanyB->id,
+ 'assigned_qty' => 1,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $this->assertDatabaseMissing('components_assets', [
+ 'component_id' => $componentInCompanyA->id,
+ 'asset_id' => $assetInCompanyB->id,
+ ]);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $userInCompanyA->id,
+ 'action_type' => 'checkout',
+ 'target_type' => Asset::class,
+ 'target_id' => $assetInCompanyB->id,
+ 'item_type' => Component::class,
+ 'item_id' => $componentInCompanyA->id,
+ ]);
+
+ $this->assertEquals(1, $componentInCompanyA->fresh()->numRemaining());
+ }
+
+ public function test_superuser_cannot_checkout_component_to_an_asset_in_another_company_when_full_company_support_is_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $superuser = User::factory()->superuser()->create(['company_id' => null]);
+ $componentInCompanyA = Component::factory()->for($companyA)->create(['qty' => 1]);
+ $assetInCompanyB = Asset::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($superuser)
+ ->postJson(route('api.components.checkout', $componentInCompanyA->id), [
+ 'assigned_to' => $assetInCompanyB->id,
+ 'assigned_qty' => 1,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $this->assertDatabaseMissing('components_assets', [
+ 'component_id' => $componentInCompanyA->id,
+ 'asset_id' => $assetInCompanyB->id,
+ ]);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $superuser->id,
+ 'action_type' => 'checkout',
+ 'target_type' => Asset::class,
+ 'target_id' => $assetInCompanyB->id,
+ 'item_type' => Component::class,
+ 'item_id' => $componentInCompanyA->id,
+ ]);
+
+ $this->assertEquals(1, $componentInCompanyA->fresh()->numRemaining());
+ }
}
diff --git a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php
index 97e431857c..1a74a68d77 100644
--- a/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php
+++ b/tests/Feature/Checkouts/Api/ConsumableCheckoutTest.php
@@ -4,6 +4,7 @@ namespace Tests\Feature\Checkouts\Api;
use App\Mail\CheckoutConsumableMail;
use App\Models\Actionlog;
+use App\Models\Company;
use App\Models\Consumable;
use App\Models\User;
use Illuminate\Support\Facades\Mail;
@@ -115,4 +116,40 @@ class ConsumableCheckoutTest extends TestCase
'Log entry either does not exist or there are more than expected'
);
}
+
+ public function test_superuser_cannot_checkout_consumable_to_a_user_in_another_company_when_full_company_support_is_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $superuser = User::factory()->superuser()->create(['company_id' => null]);
+ $consumableInCompanyA = Consumable::factory()->for($companyA)->create(['qty' => 1]);
+ $userInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($superuser)
+ ->postJson(route('api.consumables.checkout', $consumableInCompanyA), [
+ 'assigned_to' => $userInCompanyB->id,
+ 'checkout_qty' => 1,
+ ])
+ ->assertOk()
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $this->assertDatabaseMissing('consumables_users', [
+ 'consumable_id' => $consumableInCompanyA->id,
+ 'assigned_to' => $userInCompanyB->id,
+ ]);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $superuser->id,
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $userInCompanyB->id,
+ 'item_type' => Consumable::class,
+ 'item_id' => $consumableInCompanyA->id,
+ ]);
+
+ $this->assertEquals(1, $consumableInCompanyA->fresh()->numRemaining());
+ }
}
diff --git a/tests/Feature/LicenseSeats/Api/LicenseSeatUpdateTest.php b/tests/Feature/LicenseSeats/Api/LicenseSeatUpdateTest.php
index 8cac165cc1..58652df295 100644
--- a/tests/Feature/LicenseSeats/Api/LicenseSeatUpdateTest.php
+++ b/tests/Feature/LicenseSeats/Api/LicenseSeatUpdateTest.php
@@ -3,6 +3,7 @@
namespace Tests\Feature\LicenseSeats\Api;
use App\Models\Asset;
+use App\Models\Company;
use App\Models\License;
use App\Models\LicenseSeat;
use App\Models\User;
@@ -444,6 +445,46 @@ class LicenseSeatUpdateTest extends TestCase
]);
}
+ public function test_superuser_cannot_assign_a_license_seat_to_a_target_in_another_company_when_full_company_support_is_enabled()
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ [$companyA, $companyB] = Company::factory()->count(2)->create();
+
+ $superuser = User::factory()->superuser()->create(['company_id' => null]);
+ $licenseInCompanyA = License::factory()->for($companyA)->create();
+ $seatForCompanyA = LicenseSeat::factory()->create([
+ 'license_id' => $licenseInCompanyA->id,
+ 'assigned_to' => null,
+ 'asset_id' => null,
+ 'notes' => null,
+ ]);
+ $userInCompanyB = User::factory()->for($companyB)->create();
+
+ $this->actingAsForApi($superuser)
+ ->patchJson($this->route($seatForCompanyA), [
+ 'assigned_to' => $userInCompanyB->id,
+ 'notes' => 'cross-company assignment attempt',
+ ])
+ ->assertStatus(200)
+ ->assertStatusMessageIs('error')
+ ->assertMessagesAre(trans('general.error_user_company'));
+
+ $seatForCompanyA->refresh();
+ $this->assertNull($seatForCompanyA->assigned_to);
+ $this->assertNull($seatForCompanyA->asset_id);
+
+ $this->assertDatabaseMissing('action_logs', [
+ 'created_by' => $superuser->id,
+ 'action_type' => 'checkout',
+ 'target_type' => User::class,
+ 'target_id' => $userInCompanyB->id,
+ 'item_type' => License::class,
+ 'item_id' => $licenseInCompanyA->id,
+ 'note' => 'cross-company assignment attempt',
+ ]);
+ }
+
private function route(LicenseSeat $licenseSeat)
{
return route('api.licenses.seats.update', [$licenseSeat->license->id, $licenseSeat->id]);