Skip to content

A free open source IT asset/license management system

Refactored trait/scopes to simplify complexity

snipe369853333ee7
diff --git a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
index c66bdaf33e..eaa7190339 100644
--- a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
+++ b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
@@ -23,7 +23,7 @@ class CreateCheckoutRequestAction
*/
public static function run(Asset $asset, User $user): string
{
- if (is_null(Asset::RequestableAssets()->find($asset->id))) {
+ if (! $asset->isFlaggedRequestable()) {
throw new AssetNotRequestable($asset);
}
if (! Company::isCurrentUserHasAccess($asset)) {
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.php
index 2c11182d81..7f8aa23e59 100644
--- a/app/Http/Controllers/Api/AccessoriesController.php
+++ b/app/Http/Controllers/Api/AccessoriesController.php
@@ -565,7 +565,7 @@ class AccessoriesController extends Controller
* current caller (per FMCS + location scoping). Hydrates the
* accessories tab on /account/requestable. Deliberately
* open to any authenticated user - the web page it feeds is open
- * too, and the RequestableAccessories() scope layered on top of
+ * too, and the Requestable() scope layered on top of
* the CompanyableTrait global scope ensures the caller only sees
* rows they can act on.
*/
@@ -573,7 +573,7 @@ class AccessoriesController extends Controller
{
$query = Accessory::with('category', 'location', 'company', 'manufacturer', 'requests')
->withCount('checkouts as checkouts_count')
- ->RequestableAccessories();
+ ->Requestable();
if ($request->filled('search')) {
$query->TextSearch($request->input('search'));
diff --git a/app/Http/Controllers/Api/AssetModelsController.php b/app/Http/Controllers/Api/AssetModelsController.php
index e31f1d40be..d4a326146c 100644
--- a/app/Http/Controllers/Api/AssetModelsController.php
+++ b/app/Http/Controllers/Api/AssetModelsController.php
@@ -394,7 +394,7 @@ class AssetModelsController extends Controller
{
$query = AssetModel::with('category', 'manufacturer', 'requests')
->withCount('availableAssets as remaining')
- ->RequestableModels();
+ ->Requestable();
if ($request->filled('search')) {
$query->TextSearch($request->input('search'));
diff --git a/app/Http/Controllers/Api/CheckoutRequest.php b/app/Http/Controllers/Api/CheckoutRequest.php
index 82d3667b4e..08fdd2e427 100644
--- a/app/Http/Controllers/Api/CheckoutRequest.php
+++ b/app/Http/Controllers/Api/CheckoutRequest.php
@@ -191,7 +191,7 @@ class CheckoutRequest extends Controller
public function storeConsumable(Consumable $consumable): JsonResponse
{
- return $this->createRequestFor($consumable, Consumable::RequestableConsumables()->find($consumable->id));
+ return $this->createRequestFor($consumable);
}
public function destroyConsumable(Consumable $consumable): JsonResponse
@@ -201,7 +201,7 @@ class CheckoutRequest extends Controller
public function storeComponent(Component $component): JsonResponse
{
- return $this->createRequestFor($component, Component::RequestableComponents()->find($component->id));
+ return $this->createRequestFor($component);
}
public function destroyComponent(Component $component): JsonResponse
@@ -211,7 +211,7 @@ class CheckoutRequest extends Controller
public function storeLicense(License $license): JsonResponse
{
- return $this->createRequestFor($license, License::RequestableLicenses()->find($license->id));
+ return $this->createRequestFor($license);
}
public function destroyLicense(License $license): JsonResponse
@@ -220,24 +220,18 @@ class CheckoutRequest extends Controller
}
/**
- * Shared create-request flow for Consumable + Component. Kept
- * separate from the Asset store() path so the Asset flow can
+ * Shared create-request flow for Consumable + Component + License.
+ * Kept separate from the Asset store() path so the Asset flow can
* continue to use CreateCheckoutRequestAction (which owns the
- * assets-only requests_counter denormalization). Consumables and
- * Components have no counter column, so the trait's request()
- * method is sufficient here.
- *
- * The $requestable / $requestableInScope split is deliberate:
- * $requestable is the row we authorize + operate on, while
- * $requestableInScope is the same row re-fetched through the
- * per-model Requestable*() scope. That second lookup enforces
- * BOTH the requestable flag AND (via the CompanyableTrait global
- * scope) the caller's FMCS + location reach. Missing = 403-ish.
+ * assets-only requests_counter denormalization). The trait's
+ * isFlaggedRequestable() check enforces BOTH the requestable flag
+ * AND (via the CompanyableTrait global scope) the caller's FMCS +
+ * location reach.
*/
- private function createRequestFor($requestable, $requestableInScope): JsonResponse
+ private function createRequestFor($requestable): JsonResponse
{
try {
- if (! $requestable || ! $requestableInScope) {
+ if (! $requestable || ! $requestable->isFlaggedRequestable()) {
return response()->json(
Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.error')),
403,
diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.php
index 150e026604..393717967e 100644
--- a/app/Http/Controllers/Api/ComponentsController.php
+++ b/app/Http/Controllers/Api/ComponentsController.php
@@ -553,7 +553,7 @@ class ComponentsController extends Controller
{
$query = Component::with('category', 'location', 'company', 'manufacturer', 'requests')
->withCount('assets as components_assets_count')
- ->RequestableComponents();
+ ->Requestable();
if ($request->filled('search')) {
$query->TextSearch($request->input('search'));
diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.php
index b7f10a624d..6faead7ce4 100644
--- a/app/Http/Controllers/Api/ConsumablesController.php
+++ b/app/Http/Controllers/Api/ConsumablesController.php
@@ -508,7 +508,7 @@ class ConsumablesController extends Controller
{
$query = Consumable::with('category', 'location', 'company', 'manufacturer', 'requests')
->withCount('users as consumables_users_count')
- ->RequestableConsumables();
+ ->Requestable();
if ($request->filled('search')) {
$query->TextSearch($request->input('search'));
diff --git a/app/Http/Controllers/Api/LicensesController.php b/app/Http/Controllers/Api/LicensesController.php
index 3c3c773708..515d8a7242 100644
--- a/app/Http/Controllers/Api/LicensesController.php
+++ b/app/Http/Controllers/Api/LicensesController.php
@@ -508,7 +508,7 @@ class LicensesController extends Controller
public function requestable(Request $request): array
{
$query = License::with('category', 'company', 'manufacturer', 'requests')
- ->RequestableLicenses();
+ ->Requestable();
if ($request->filled('search')) {
$query->TextSearch($request->input('search'));
diff --git a/app/Http/Controllers/Licenses/LicenseCheckoutController.php b/app/Http/Controllers/Licenses/LicenseCheckoutController.php
index 7c460afeff..bd24ec584f 100644
--- a/app/Http/Controllers/Licenses/LicenseCheckoutController.php
+++ b/app/Http/Controllers/Licenses/LicenseCheckoutController.php
@@ -439,7 +439,6 @@ class LicenseCheckoutController extends Controller
->with('error', trans('admin/hardware/message.requests.no_selection'));
}
- $qtyInputs = (array) $request->input('qty', []);
$userInputs = (array) $request->input('user_id', []);
$noteInputs = (array) $request->input('notes', []);
diff --git a/app/Http/Controllers/ViewAssetsController.php b/app/Http/Controllers/ViewAssetsController.php
index 9185f996e8..9e85ce561b 100755
--- a/app/Http/Controllers/ViewAssetsController.php
+++ b/app/Http/Controllers/ViewAssetsController.php
@@ -160,12 +160,12 @@ class ViewAssetsController extends Controller
// filters, so the counts here stay consistent with what the
// AJAX call will render.
$counts = [
- 'assets' => Asset::Hardware()->RequestableAssets()->count(),
- 'models' => AssetModel::RequestableModels()->count(),
- 'accessories' => Accessory::RequestableAccessories()->count(),
- 'consumables' => Consumable::RequestableConsumables()->count(),
- 'components' => Component::RequestableComponents()->count(),
- 'licenses' => License::RequestableLicenses()->count(),
+ 'assets' => Asset::Hardware()->Requestable()->count(),
+ 'models' => AssetModel::Requestable()->count(),
+ 'accessories' => Accessory::Requestable()->count(),
+ 'consumables' => Consumable::Requestable()->count(),
+ 'components' => Component::Requestable()->count(),
+ 'licenses' => License::Requestable()->count(),
];
return view('account/requestable-assets', compact('counts'));
@@ -182,8 +182,6 @@ class ViewAssetsController extends Controller
// the auth id.
$cancel_by_admin = $requestingUser !== null
&& (int) $requestingUser !== (int) auth()->id();
- $data = [];
- $item = null;
$fullItemType = 'App\\Models\\'.studly_case($itemType);
if ($itemType == 'asset_model') {
@@ -201,27 +199,68 @@ class ViewAssetsController extends Controller
return redirect()->back()->with('error', trans('admin/hardware/message.requests.error'));
}
+ $user = auth()->user();
+ $is_admin = $user->isSuperUser() || $user->isAdmin();
+
+ if ($cancel_by_admin && ! $is_admin) {
+ return redirect()->back()->with('error', trans('general.insufficient_permissions'));
+ }
+
+ $item_request = $item->isRequestedBy($user);
+
+ if ($item_request || ($is_admin && $cancel_by_admin)) {
+ return $this->handleCancelRequest(
+ $request,
+ $item,
+ $fullItemType,
+ $itemType,
+ $item_request ?: null,
+ $is_admin && $cancel_by_admin ? $requestingUser : null,
+ );
+ }
+
+ return $this->handleSubmitRequest($request, $item, $fullItemType, $itemType);
+ }
+
+ /**
+ * Assemble the shared notification/actionlog payload used by both
+ * the submit and cancel paths. Kept as a helper so the request
+ * dispatcher can stay focused on routing.
+ *
+ * @return array{0: Actionlog, 1: array<string, mixed>}
+ */
+ private function buildRequestContext(Request $request, $item, string $fullItemType, string $itemType): array
+ {
$user = auth()->user();
$logaction = new Actionlog;
- $logaction->item_id = $data['asset_id'] = $item->id;
+ $logaction->item_id = $item->id;
$logaction->item_type = $fullItemType;
- $logaction->created_at = $data['requested_date'] = date('Y-m-d H:i:s');
-
+ $logaction->created_at = date('Y-m-d H:i:s');
if ($user->location_id) {
$logaction->location_id = $user->location_id;
}
-
- $logaction->target_id = $data['user_id'] = auth()->id();
+ $logaction->target_id = auth()->id();
$logaction->target_type = User::class;
- $data['item_quantity'] = $request->has('request-quantity') ? e($request->input('request-quantity')) : 1;
- $data['requested_by'] = $user->display_name;
- $data['item'] = $item;
- $data['item_type'] = $itemType;
- $data['target'] = auth()->user();
+ $data = [
+ 'asset_id' => $item->id,
+ 'requested_date' => $logaction->created_at,
+ 'user_id' => auth()->id(),
+ 'item_quantity' => $request->has('request-quantity') ? e($request->input('request-quantity')) : 1,
+ 'requested_by' => $user->display_name,
+ 'item' => $item,
+ 'item_type' => $itemType,
+ 'target' => $user,
+ 'item_url' => $this->resolveItemUrl($fullItemType, $item, $itemType),
+ ];
+
+ return [$logaction, $data];
+ }
- $data['item_url'] = match ($fullItemType) {
+ private function resolveItemUrl(string $fullItemType, $item, string $itemType): string
+ {
+ return match ($fullItemType) {
Asset::class => route('hardware.show', $item->id),
AssetModel::class => route('view/model', $item->id),
Accessory::class => route('accessories.show', $item->id),
@@ -230,121 +269,106 @@ class ViewAssetsController extends Controller
License::class => route('licenses.show', $item->id),
default => route("view/{$itemType}", $item->id),
};
+ }
- $settings = Setting::getSettings();
+ /**
+ * Prefer an explicit active_tab hint over a plain back() so the
+ * requester lands on the tab they submitted from. Falls back to
+ * back() for callers that don't carry the hint (e.g. admin
+ * cancel from /requests).
+ */
+ private function redirectAfterRequestAction(Request $request, string $successKey): RedirectResponse
+ {
+ if ($tab = $this->safeActiveTab($request->input('active_tab'))) {
+ return redirect()->route('account.requestable')
+ ->withFragment($tab)
+ ->with('success', trans($successKey));
+ }
- $is_admin = $user->isSuperUser() || $user->isAdmin();
+ return redirect()->back()->with('success', trans($successKey));
+ }
- if ($cancel_by_admin && ! $is_admin) {
- return redirect()->back()->with('error', trans('general.insufficient_permissions'));
+ private function handleCancelRequest(Request $request, $item, string $fullItemType, string $itemType, $item_request, $requestingUser): RedirectResponse
+ {
+ [$logaction, $data] = $this->buildRequestContext($request, $item, $fullItemType, $itemType);
+
+ $item->cancelRequest($requestingUser);
+ $data['item_quantity'] = $item_request ? $item_request->quantity : 1;
+
+ if ($item_request) {
+ $data['start_date'] = $item_request->start_date;
+ $data['end_date'] = $item_request->end_date;
+ $data['note'] = $item_request->notes;
}
- if (($item_request = $item->isRequestedBy($user)) || ($is_admin && $cancel_by_admin)) {
- $item->cancelRequest($is_admin && $cancel_by_admin ? $requestingUser : null);
- $data['item_quantity'] = ($item_request) ? $item_request->quantity : 1;
- // Surface the reservation window + notes (if any) on the
- // cancel notification so the admin knows exactly which
- // slot was scrapped and what the requester was originally
- // asking for. Only the row we found survives cancellation
- // long enough for us to read here (cancelRequest above
- // sets canceled_at but leaves the other fields intact).
- if ($item_request) {
- $data['start_date'] = $item_request->start_date;
- $data['end_date'] = $item_request->end_date;
- $data['note'] = $item_request->notes;
- }
- $logaction->logaction(ActionType::RequestCanceled);
+ $logaction->logaction(ActionType::RequestCanceled);
- if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) {
- try {
- $settings->notify((new RequestAssetCancelation($data))->locale($settings->locale));
- } catch (Exception $e) {
- Log::warning('Could not send request cancellation notification: '.$e->getMessage());
- }
+ $settings = Setting::getSettings();
+ if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) {
+ try {
+ $settings->notify((new RequestAssetCancelation($data))->locale($settings->locale));
+ } catch (Exception $e) {
+ Log::warning('Could not send request cancellation notification: '.$e->getMessage());
}
+ }
- // Prefer an explicit active_tab hint over a plain back()
- // so the requester lands on the tab they submitted from;
- // fall back to back() for callers that don't carry the
- // hint (e.g. admin cancel from /requests).
- if ($tab = $this->safeActiveTab($request->input('active_tab'))) {
- return redirect()->route('account.requestable')
- ->withFragment($tab)
- ->with('success', trans('admin/hardware/message.requests.canceled'));
- }
+ return $this->redirectAfterRequestAction($request, 'admin/hardware/message.requests.canceled');
+ }
- return redirect()->back()->with('success', trans('admin/hardware/message.requests.canceled'));
- } else {
- // AssetModel was previously missing from this gate, so a
- // POST to /account/request/asset_model/{id} would bypass
- // the model's `requestable` flag entirely and still
- // create a request record. Consumable and Component both
- // gained the Requestable trait alongside a per-row
- // `requestable` flag; extending the gate here keeps the
- // "must be flagged requestable" rule symmetric across
- // every request-eligible type. The Requestable*() scopes
- // rely on the model's global CompanyableScope, so FMCS
- // (and location-scoping when enabled) apply automatically.
- if (($fullItemType === Asset::class && is_null(Asset::RequestableAssets()->find($item->id)))
- || ($fullItemType === Accessory::class && is_null(Accessory::RequestableAccessories()->find($item->id)))
- || ($fullItemType === AssetModel::class && is_null(AssetModel::RequestableModels()->find($item->id)))
- || ($fullItemType === Consumable::class && is_null(Consumable::RequestableConsumables()->find($item->id)))
- || ($fullItemType === Component::class && is_null(Component::RequestableComponents()->find($item->id)))
- || ($fullItemType === License::class && is_null(License::RequestableLicenses()->find($item->id)))) {
- return redirect()->back()->with('error', trans('admin/hardware/message.requests.error'));
- }
+ private function handleSubmitRequest(Request $request, $item, string $fullItemType, string $itemType): RedirectResponse
+ {
+ if (! $item->isFlaggedRequestable()) {
+ return redirect()->back()->with('error', trans('admin/hardware/message.requests.error'));
+ }
- // Optional reservation window. Empty strings from the
- // request-modal date pickers coerce to null so an "I need
- // this whenever" request doesn't accidentally persist
- // today's date as the start. Uses Laravel's built-in
- // validation strings so a bad range gets the framework's
- // localized "after or equal to" message rather than a
- // hand-rolled key we'd have to translate ourselves.
- $reservationValidator = validator($request->only(['start_date', 'end_date']), [
- 'start_date' => 'nullable|date',
- 'end_date' => 'nullable|date|after_or_equal:start_date',
- ]);
- if ($reservationValidator->fails()) {
- return redirect()->back()->withInput()->withErrors($reservationValidator);
- }
- $startDate = $request->filled('start_date') ? $request->input('start_date') : null;
- $endDate = $request->filled('end_date') ? $request->input('end_date') : null;
- // Optional free-text notes the requester attaches to
- // explain what they need. Empty string coerces to null so
- // an untouched textarea doesn't persist a blank row and
- // then leak an empty "Additional Notes" block into the
- // admin's mail.
- $notes = $request->filled('notes') ? $request->input('notes') : null;
-
- // Also feed the notification, so admins see the window
- // right in the "new request" email/slack. Blank values
- // stay out of the mail per the template's isset+non-empty
- // guards. `note` (singular) is the existing template key
- // for the additional-notes row; reusing it means the mail
- // + slack layouts pick this up without changes.
- $data['start_date'] = $startDate;
- $data['end_date'] = $endDate;
- $data['note'] = $notes;
-
- $item->request($data['item_quantity'], $startDate, $endDate, $notes);
- if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) {
- $logaction->logaction('requested');
- try {
- $settings->notify((new RequestAssetNotification($data))->locale($settings->locale));
- } catch (Exception $e) {
- Log::warning('Could not send asset request notification: '.$e->getMessage());
- }
- }
+ // Optional reservation window. Empty strings from the
+ // request-modal date pickers coerce to null so an "I need
+ // this whenever" request doesn't accidentally persist today's
+ // date as the start. Uses Laravel's built-in validation
+ // strings so a bad range gets the framework's localized
+ // "after or equal to" message rather than a hand-rolled key
+ // we'd have to translate ourselves.
+ $reservationValidator = validator($request->only(['start_date', 'end_date']), [
+ 'start_date' => 'nullable|date',
+ 'end_date' => 'nullable|date|after_or_equal:start_date',
+ ]);
+ if ($reservationValidator->fails()) {
+ return redirect()->back()->withInput()->withErrors($reservationValidator);
+ }
- $redirect = redirect()->route('account.requestable')
- ->with('success', trans('admin/hardware/message.requests.success'));
- if ($tab = $this->safeActiveTab($request->input('active_tab'))) {
- $redirect->withFragment($tab);
- }
+ $startDate = $request->filled('start_date') ? $request->input('start_date') : null;
+ $endDate = $request->filled('end_date') ? $request->input('end_date') : null;
+ // Optional free-text notes the requester attaches to explain
+ // what they need. Empty string coerces to null so an untouched
+ // textarea doesn't persist a blank row and then leak an empty
+ // "Additional Notes" block into the admin's mail.
+ $notes = $request->filled('notes') ? $request->input('notes') : null;
- return $redirect;
+ [$logaction, $data] = $this->buildRequestContext($request, $item, $fullItemType, $itemType);
+
+ // Feed the notification so admins see the window right in
+ // the "new request" email/slack. Blank values stay out of
+ // the mail per the template's isset+non-empty guards. `note`
+ // (singular) is the existing template key for the additional-
+ // notes row; reusing it means the mail + slack layouts pick
+ // this up without changes.
+ $data['start_date'] = $startDate;
+ $data['end_date'] = $endDate;
+ $data['note'] = $notes;
+
+ $item->request($data['item_quantity'], $startDate, $endDate, $notes);
+
+ $settings = Setting::getSettings();
+ if (($settings->alert_email != '') && ($settings->alerts_enabled == '1') && (! config('app.lock_passwords'))) {
+ $logaction->logaction('requested');
+ try {
+ $settings->notify((new RequestAssetNotification($data))->locale($settings->locale));
+ } catch (Exception $e) {
+ Log::warning('Could not send asset request notification: '.$e->getMessage());
+ }
}
+
+ return $this->redirectAfterRequestAction($request, 'admin/hardware/message.requests.success');
}
/**
diff --git a/app/Http/Transformers/AccessoriesTransformer.php b/app/Http/Transformers/AccessoriesTransformer.php
index cd0968d964..a5ff707040 100644
--- a/app/Http/Transformers/AccessoriesTransformer.php
+++ b/app/Http/Transformers/AccessoriesTransformer.php
@@ -99,6 +99,7 @@ class AccessoriesTransformer
fn ($request) => $request->user_id === auth()->id() && $request->canceled_at === null
);
+ $permissions_array = [];
$permissions_array['assigned_to_self'] = $userHasOpenRequest;
$permissions_array['available_actions'] = [
@@ -110,7 +111,7 @@ class AccessoriesTransformer
'clone' => Gate::allows('create', Accessory::class),
// Request / cancel: if the requestable flag is off the row
// never surfaces on /account/requestable anyway (scoped out
- // by RequestableAccessories()), but honor it here too for
+ // by Requestable()), but honor it here too for
// any consumer hitting the standard index endpoint.
'request' => (bool) $accessory->requestable && ! $userHasOpenRequest,
'cancel' => (bool) $accessory->requestable && $userHasOpenRequest,
diff --git a/app/Http/Transformers/AssetModelsTransformer.php b/app/Http/Transformers/AssetModelsTransformer.php
index d753ae0285..1a79d281e8 100644
--- a/app/Http/Transformers/AssetModelsTransformer.php
+++ b/app/Http/Transformers/AssetModelsTransformer.php
@@ -111,7 +111,7 @@ class AssetModelsTransformer
'restore' => (Gate::allows('create', AssetModel::class) && ($assetmodel->deleted_at != '')),
// Request / cancel: if the requestable flag is off the row
// never surfaces on /account/requestable anyway (scoped
- // out by RequestableModels()), but honor it here too for
+ // out by Requestable()), but honor it here too for
// any consumer hitting the standard index endpoint.
'request' => (bool) $assetmodel->requestable && ! $userHasOpenRequest,
'cancel' => (bool) $assetmodel->requestable && $userHasOpenRequest,
diff --git a/app/Http/Transformers/CheckoutRequestsTransformer.php b/app/Http/Transformers/CheckoutRequestsTransformer.php
index e8411cfead..675fde058f 100644
--- a/app/Http/Transformers/CheckoutRequestsTransformer.php
+++ b/app/Http/Transformers/CheckoutRequestsTransformer.php
@@ -91,7 +91,7 @@ class CheckoutRequestsTransformer
] : null,
'requestable' => $item ? self::transformRequestable($item, $request) : null,
'pending_requesters' => self::pendingRequestersFor($request, $requesterMap),
- 'available_actions' => self::availableActions($item, $request),
+ 'available_actions' => self::availableActions($item),
];
}
@@ -231,12 +231,6 @@ class CheckoutRequestsTransformer
} else {
$remainingCount = null;
}
- // Replenish gate below still uses the "tracks a qty column"
- // set (accessory / consumable / component) because License
- // + AssetModel don't have an adjust-quantity modal.
- $tracksQty = $item instanceof Accessory
- || $item instanceof Consumable
- || $item instanceof Component;
// Font Awesome class the JS name-formatter prefixes so the
// admin queue reads at a glance which polymorphic type each
@@ -365,7 +359,7 @@ class CheckoutRequestsTransformer
/**
* @return array<string, mixed>
*/
- private static function availableActions($item, CheckoutRequest $request): array
+ private static function availableActions($item): array
{
$cancelable = $item !== null;
diff --git a/app/Http/Transformers/ComponentsTransformer.php b/app/Http/Transformers/ComponentsTransformer.php
index c958489900..ccc0dd5470 100644
--- a/app/Http/Transformers/ComponentsTransformer.php
+++ b/app/Http/Transformers/ComponentsTransformer.php
@@ -92,6 +92,7 @@ class ComponentsTransformer
$userHasOpenRequest = auth()->check() && $component->relationLoaded('requests') && $component->requests->contains(
fn ($request) => $request->user_id === auth()->id() && $request->canceled_at === null
);
+ $permissions_array = [];
$permissions_array['assigned_to_self'] = $userHasOpenRequest;
$permissions_array['available_actions'] = [
diff --git a/app/Http/Transformers/ConsumablesTransformer.php b/app/Http/Transformers/ConsumablesTransformer.php
index c0319a52ac..75fd614e4c 100644
--- a/app/Http/Transformers/ConsumablesTransformer.php
+++ b/app/Http/Transformers/ConsumablesTransformer.php
@@ -83,6 +83,7 @@ class ConsumablesTransformer
'updated_at' => Helper::getFormattedDateObject($consumable->updated_at, 'datetime'),
];
+ $permissions_array = [];
$permissions_array['user_can_checkout'] = false;
if ($consumable->numRemaining() > 0) {
diff --git a/app/Http/Transformers/LicensesTransformer.php b/app/Http/Transformers/LicensesTransformer.php
index c230b92f9e..db642a0f6e 100644
--- a/app/Http/Transformers/LicensesTransformer.php
+++ b/app/Http/Transformers/LicensesTransformer.php
@@ -82,6 +82,7 @@ class LicensesTransformer
$userHasOpenRequest = auth()->check() && $license->relationLoaded('requests') && $license->requests->contains(
fn ($request) => $request->user_id === auth()->id() && $request->canceled_at === null
);
+ $permissions_array = [];
$permissions_array['assigned_to_self'] = $userHasOpenRequest;
$permissions_array['available_actions'] = [
diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php
index b2e0995f5f..a01f976233 100755
--- a/app/Models/Accessory.php
+++ b/app/Models/Accessory.php
@@ -186,7 +186,7 @@ class Accessory extends SnipeModel
* Scope query to only requestable accessories. Unlike assets, accessories
* have no deployable status to check, so the flag is all we need here.
*/
- public function scopeRequestableAccessories($query)
+ public function scopeRequestable($query)
{
return $query->where('accessories.requestable', '1');
}
@@ -598,6 +598,6 @@ class Accessory extends SnipeModel
{
$direction = strtolower($order) === 'asc' ? 'asc' : 'desc';
- return $query->orderByRaw('(accessories.qty - checkouts_count) ' . $direction);
+ return $query->orderByRaw('(accessories.qty - checkouts_count) '.$direction);
}
}
diff --git a/app/Models/Asset.php b/app/Models/Asset.php
index 4e1b2a285a..c9d6cd5ff2 100644
--- a/app/Models/Asset.php
+++ b/app/Models/Asset.php
@@ -1878,7 +1878,7 @@ class Asset extends Depreciable
* @param \Illuminate\Database\Query\Builder $query Query builder instance
* @return \Illuminate\Database\Query\Builder Modified query builder
*/
- public function scopeRequestableAssets($query): Builder
+ public function scopeRequestable($query): Builder
{
$table = $query->getModel()->getTable();
diff --git a/app/Models/AssetModel.php b/app/Models/AssetModel.php
index 4a927f61f6..16f6887b29 100755
--- a/app/Models/AssetModel.php
+++ b/app/Models/AssetModel.php
@@ -373,7 +373,7 @@ class AssetModel extends SnipeModel
*
* @version v3.5
*/
- public function scopeRequestableModels($query)
+ public function scopeRequestable($query)
{
return $query->where('requestable', '1');
}
diff --git a/app/Models/Component.php b/app/Models/Component.php
index 04f9bc7d39..e7bc6eb57e 100644
--- a/app/Models/Component.php
+++ b/app/Models/Component.php
@@ -175,7 +175,7 @@ class Component extends SnipeModel
* applies without any additional wrapping here (matches the
* Accessory scope's shape and rationale).
*/
- public function scopeRequestableComponents($query)
+ public function scopeRequestable($query)
{
return $query->where('components.requestable', '1');
}
diff --git a/app/Models/Consumable.php b/app/Models/Consumable.php
index 08c8d2de19..24cabb3501 100644
--- a/app/Models/Consumable.php
+++ b/app/Models/Consumable.php
@@ -153,7 +153,7 @@ class Consumable extends SnipeModel
* applies without any additional wrapping here (matches the
* Accessory scope's shape and rationale).
*/
- public function scopeRequestableConsumables($query)
+ public function scopeRequestable($query)
{
return $query->where('consumables.requestable', '1');
}
diff --git a/app/Models/License.php b/app/Models/License.php
index 7a639d2a02..d694ea53a7 100755
--- a/app/Models/License.php
+++ b/app/Models/License.php
@@ -207,7 +207,7 @@ class License extends Depreciable
* applies without any additional wrapping here (matches the
* Accessory / Consumable / Component scope shape).
*/
- public function scopeRequestableLicenses($query)
+ public function scopeRequestable($query)
{
return $query->where('licenses.requestable', '1');
}
diff --git a/app/Models/Traits/Requestable.php b/app/Models/Traits/Requestable.php
index 8a4386177e..2857ea478b 100644
--- a/app/Models/Traits/Requestable.php
+++ b/app/Models/Traits/Requestable.php
@@ -58,6 +58,23 @@ trait Requestable
return $this->requests()->where('state', CheckoutRequestState::Pending->value);
}
+ /**
+ * True when this specific row passes the model's own scopeRequestable
+ * filter, which is the single source of truth for "an admin can
+ * receive a request against this item". Delegating to the scope
+ * keeps per-type semantics intact - Asset layers on a deployable-
+ * status check + explicit FMCS on top of the boolean flag, and the
+ * other five types just check the flag. Callers should use this
+ * instead of hand-rolling `Model::requestable()->find($id)`.
+ */
+ public function isFlaggedRequestable(): bool
+ {
+ return static::query()
+ ->requestable()
+ ->whereKey($this->getKey())
+ ->exists();
+ }
+
public function isRequestedBy(User $user)
{
// Fresh query rather than filtering the loaded ->requests
diff --git a/tests/Feature/AssetModels/Api/RequestableAssetModelsApiTest.php b/tests/Feature/AssetModels/Api/RequestableAssetModelsApiTest.php
index 29ff230764..e23568b649 100644
--- a/tests/Feature/AssetModels/Api/RequestableAssetModelsApiTest.php
+++ b/tests/Feature/AssetModels/Api/RequestableAssetModelsApiTest.php
@@ -112,7 +112,7 @@ class RequestableAssetModelsApiTest extends TestCase
// model - but codify the isolation with a test so a future
// refactor doesn't regress it.
$user = User::factory()->create();
- $model = AssetModel::factory()->create(['requestable' => 1]);
+ AssetModel::factory()->create(['requestable' => 1]);
$accessory = Accessory::factory()->create();
CheckoutRequest::factory()->create([
'user_id' => $user->id,
diff --git a/tests/Feature/Requests/AssetModelRequestGateTest.php b/tests/Feature/Requests/AssetModelRequestGateTest.php
index 21cb7fb66d..d543935daa 100644
--- a/tests/Feature/Requests/AssetModelRequestGateTest.php
+++ b/tests/Feature/Requests/AssetModelRequestGateTest.php
@@ -15,7 +15,7 @@ use Tests\TestCase;
* record for a model whose admin had explicitly set
* `requestable = 0`. Fix extends the gate at
* ViewAssetsController::getRequestItem to also validate
- * AssetModel::RequestableModels().
+ * AssetModel::Requestable().
*
* Also covers the adjacent hardening: the route parameter {itemType}
* is now constrained to `asset|asset_model|accessory` at the route
diff --git a/tests/Feature/Requests/Ui/ConsumableRequestTest.php b/tests/Feature/Requests/Ui/ConsumableRequestTest.php
index 6ed1e7d7e5..223160d639 100644
--- a/tests/Feature/Requests/Ui/ConsumableRequestTest.php
+++ b/tests/Feature/Requests/Ui/ConsumableRequestTest.php
@@ -111,7 +111,7 @@ class ConsumableRequestTest extends TestCase
{
// A user in company A must not be able to request a consumable
// that belongs to company B. The requestable-flag gate loads
- // through Consumable::RequestableConsumables which respects
+ // through Consumable::Requestable which respects
// the CompanyableTrait global scope, so the item never
// resolves for the cross-company caller and the request is
// refused with the standard "not requestable" error.