Skip to content

A free open source IT asset/license management system

Added requestable method

snipef98601744926
diff --git a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php b/app/Http/Controllers/Accessories/AccessoryCheckoutController.php
index 02ff2c8d6b..3406d9488e 100644
--- a/app/Http/Controllers/Accessories/AccessoryCheckoutController.php
+++ b/app/Http/Controllers/Accessories/AccessoryCheckoutController.php
@@ -11,12 +11,14 @@ use App\Http\Traits\CheckInOutTrait;
use App\Models\Accessory;
use App\Models\AccessoryCheckout;
use App\Models\CheckoutAcceptance;
+use App\Models\CheckoutRequest;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Log;
class AccessoryCheckoutController extends Controller
{
@@ -29,7 +31,7 @@ class AccessoryCheckoutController extends Controller
*
* @param int $id
*/
- public function create(Accessory $accessory): View|RedirectResponse
+ public function create(Request $request, Accessory $accessory): View|RedirectResponse
{
$this->authorize('checkout', $accessory);
@@ -40,8 +42,21 @@ class AccessoryCheckoutController extends Controller
return redirect()->route('accessories.index')->with('error', trans('admin/accessories/message.checkout.unavailable'));
}
- // Return the checkout view
- return view('accessories/checkout', compact('accessory'));
+ // Optional ?request_id hint. Present when the admin
+ // reached this screen from a /requests row. Drives the
+ // side-panel context box (who asked + waiting list).
+ // CheckoutRequest::contextForCheckout handles the URL-
+ // twiddle guards; a miss returns nulls / empty so the
+ // panel renders nothing.
+ $context = CheckoutRequest::contextForCheckout(
+ $request->integer('request_id') ?: null,
+ Accessory::class,
+ $accessory->id,
+ );
+
+ return view('accessories/checkout', compact('accessory'))
+ ->with('checkoutRequest', $context['checkoutRequest'])
+ ->with('otherPendingRequests', $context['otherPendingRequests']);
}
// Invalid category
@@ -175,4 +190,182 @@ class AccessoryCheckoutController extends Controller
return Helper::getRedirectOption($request, $accessory->id, 'Accessories')
->with('success', trans('admin/accessories/message.checkout.success'));
}
+
+ /**
+ * Bulk-fulfill screen: list every pending CheckoutRequest for
+ * this accessory so an admin can process the waiting list in
+ * one pass. Reached from the "Fulfill Multiple" trigger on the
+ * /requests admin queue when ≥2 pending requests exist for the
+ * same accessory. The per-row shape is the shared
+ * <x-checkout.recipient-row> component; the store method below
+ * iterates the ticked rows.
+ */
+ public function bulkFulfillCreate(Accessory $accessory): View|RedirectResponse
+ {
+ $this->authorize('checkout', $accessory);
+
+ if ($accessory->numRemaining() <= 0) {
+ return redirect()->route('accessories.show', $accessory)
+ ->with('error', trans('admin/accessories/message.checkout.unavailable'));
+ }
+
+ $pendingRequests = CheckoutRequest::pending()
+ ->where('requestable_type', Accessory::class)
+ ->where('requestable_id', $accessory->id)
+ ->with('user')
+ ->orderBy('created_at')
+ ->orderBy('id')
+ ->get()
+ ->filter(fn (CheckoutRequest $r) => $r->user !== null)
+ ->values();
+
+ if ($pendingRequests->isEmpty()) {
+ return redirect()->route('accessories.show', $accessory)
+ ->with('info', trans('admin/hardware/message.requests.no_active'));
+ }
+
+ return view('checkouts/fulfill-multiple', [
+ 'item' => $accessory,
+ 'pendingRequests' => $pendingRequests,
+ 'formRoute' => route('accessories.fulfill-requests.store', $accessory),
+ 'remaining' => (int) $accessory->numRemaining(),
+ ]);
+ }
+
+ /**
+ * Iterate the ticked rows and fulfill each in its own
+ * transaction (partial-success semantics matching the license
+ * bulk-checkout pattern). Each successful fulfillment fires
+ * CheckoutableCheckedOut, which the state-machine listener
+ * picks up to close the matching request row.
+ *
+ * Rolls per-row rather than per-batch so one bad target (company
+ * mismatch, deleted user, over-allocated qty) doesn't nuke the
+ * whole batch. The response summarizes fulfilled + skipped
+ * counts and any per-row error messages so the admin knows what
+ * to re-try.
+ */
+ public function bulkFulfillStore(Request $request, Accessory $accessory): RedirectResponse
+ {
+ $this->authorize('checkout', $accessory);
+
+ $enabledIds = collect((array) $request->input('enabled_requests', []))
+ ->map(fn ($id) => (int) $id)
+ ->filter()
+ ->unique()
+ ->values();
+
+ if ($enabledIds->isEmpty()) {
+ return redirect()->route('accessories.fulfill-requests.create', $accessory)
+ ->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', []);
+
+ $requests = CheckoutRequest::pending()
+ ->where('requestable_type', Accessory::class)
+ ->where('requestable_id', $accessory->id)
+ ->whereIn('id', $enabledIds)
+ ->with('user')
+ ->get()
+ ->keyBy('id');
+
+ $fulfilled = 0;
+ $errors = [];
+
+ foreach ($enabledIds as $requestId) {
+ /** @var CheckoutRequest|null $checkoutRequest */
+ $checkoutRequest = $requests->get($requestId);
+ if (! $checkoutRequest) {
+ $errors[] = trans('admin/hardware/message.requests.row_stale', ['id' => $requestId]);
+
+ continue;
+ }
+
+ $targetUserId = (int) ($userInputs[$requestId] ?? $checkoutRequest->user_id);
+ $qty = (int) ($qtyInputs[$requestId] ?? $checkoutRequest->quantity);
+ $note = $noteInputs[$requestId] ?? $checkoutRequest->notes;
+
+ if ($qty < 1) {
+ $errors[] = trans('admin/hardware/message.requests.row_qty_invalid', ['id' => $requestId]);
+
+ continue;
+ }
+
+ $targetUser = User::find($targetUserId);
+ if (! $targetUser) {
+ $errors[] = trans('admin/hardware/message.requests.row_user_missing', ['id' => $requestId]);
+
+ continue;
+ }
+
+ if (! $accessory->canCheckoutTo($targetUser)) {
+ $errors[] = trans('admin/hardware/message.requests.row_company_mismatch', [
+ 'id' => $requestId,
+ 'user' => $targetUser->display_name,
+ ]);
+
+ continue;
+ }
+
+ $overAllocated = false;
+
+ DB::transaction(function () use ($accessory, $targetUser, $qty, $note, &$overAllocated): void {
+ $locked = Accessory::whereKey($accessory->id)->lockForUpdate()->first();
+
+ if (! $locked || $locked->numRemaining() < $qty) {
+ $overAllocated = true;
+
+ return;
+ }
+
+ for ($i = 0; $i < $qty; $i++) {
+ $accessory_checkout = new AccessoryCheckout([
+ 'accessory_id' => $accessory->id,
+ 'created_at' => Carbon::now(),
+ 'assigned_to' => $targetUser->id,
+ 'assigned_type' => User::class,
+ 'note' => $note,
+ ]);
+ $accessory_checkout->created_by = auth()->id();
+ $accessory_checkout->save();
+ }
+ });
+
+ if ($overAllocated) {
+ $errors[] = trans('admin/hardware/message.requests.row_over_allocated', [
+ 'id' => $requestId,
+ ]);
+
+ continue;
+ }
+
+ try {
+ event(new CheckoutableCheckedOut(
+ $accessory,
+ $targetUser,
+ auth()->user(),
+ $note,
+ [],
+ $qty,
+ false,
+ ));
+ } catch (\Throwable $e) {
+ Log::warning('Bulk-fulfill event dispatch failed for request '.$requestId.': '.$e->getMessage());
+ }
+
+ $fulfilled++;
+ }
+
+ $summary = trans('admin/hardware/message.requests.bulk_summary', [
+ 'fulfilled' => $fulfilled,
+ 'total' => $enabledIds->count(),
+ ]);
+
+ return redirect()->route('requests.index')
+ ->with($fulfilled > 0 ? 'success' : 'warning', $summary)
+ ->with('multi_error_messages', $errors);
+ }
}
diff --git a/app/Http/Controllers/Api/AccessoriesController.php b/app/Http/Controllers/Api/AccessoriesController.php
index fb81f14f4e..2c11182d81 100644
--- a/app/Http/Controllers/Api/AccessoriesController.php
+++ b/app/Http/Controllers/Api/AccessoriesController.php
@@ -559,4 +559,35 @@ class AccessoriesController extends Controller
return response()->json((new ActionlogsTransformer)->transformActionlogs($history, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
+
+ /**
+ * List accessories that are requestable AND reachable by the
+ * 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
+ * the CompanyableTrait global scope ensures the caller only sees
+ * rows they can act on.
+ */
+ public function requestable(Request $request): array
+ {
+ $query = Accessory::with('category', 'location', 'company', 'manufacturer', 'requests')
+ ->withCount('checkouts as checkouts_count')
+ ->RequestableAccessories();
+
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ $total = $query->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+
+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sort = in_array($request->input('sort'), ['name', 'created_at'], true) ? $request->input('sort') : 'name';
+
+ $rows = $query->orderBy($sort, $order)->skip($offset)->take($limit)->get();
+
+ return (new AccessoriesTransformer)->transformAccessories($rows, $total);
+ }
}
diff --git a/app/Http/Controllers/Api/AssetModelsController.php b/app/Http/Controllers/Api/AssetModelsController.php
index 497fda1b72..e31f1d40be 100644
--- a/app/Http/Controllers/Api/AssetModelsController.php
+++ b/app/Http/Controllers/Api/AssetModelsController.php
@@ -379,4 +379,36 @@ class AssetModelsController extends Controller
return response()->json((new ActionlogsTransformer)->transformActionlogs($history, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
+
+ /**
+ * List asset models that are requestable AND reachable by the
+ * current caller (per FMCS + location scoping). Hydrates the
+ * models tab on /account/requestable so the shell page can drop
+ * its server-rendered @foreach and match the pattern the other
+ * requestable tabs (accessory / consumable / component / license)
+ * already use. Row shape carries assigned_to_self plus
+ * available_actions.request/cancel so the JS actions formatter
+ * can pick the right button per row without a second query.
+ */
+ public function requestable(Request $request): array
+ {
+ $query = AssetModel::with('category', 'manufacturer', 'requests')
+ ->withCount('availableAssets as remaining')
+ ->RequestableModels();
+
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ $total = $query->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+
+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sort = in_array($request->input('sort'), ['name', 'created_at'], true) ? $request->input('sort') : 'name';
+
+ $rows = $query->orderBy($sort, $order)->skip($offset)->take($limit)->get();
+
+ return (new AssetModelsTransformer)->transformAssetModels($rows, $total);
+ }
}
diff --git a/app/Http/Controllers/Api/AssetsController.php b/app/Http/Controllers/Api/AssetsController.php
index 24bc2e86cf..9384759eaf 100644
--- a/app/Http/Controllers/Api/AssetsController.php
+++ b/app/Http/Controllers/Api/AssetsController.php
@@ -655,6 +655,20 @@ class AssetsController extends Controller
$assets->where('assets.id', '!=', (int) $request->input('excludeId'));
}
+ // Pre-scope the picker to a specific user's assigned assets.
+ // Used by the components-checkout screen when reached via a
+ // /requests row: an admin fulfilling a component request wants
+ // to install the part into one of the requester's existing
+ // assets, not hunt across the whole fleet. Empty result is the
+ // honest answer here - if the requester has nothing assigned,
+ // there's no valid install target and the admin should see
+ // that instead of a fallback to the full fleet.
+ if ($request->filled('assignedTo')) {
+ $assignedUserId = (int) $request->input('assignedTo');
+ $assets->where('assets.assigned_to', $assignedUserId)
+ ->where('assets.assigned_type', User::class);
+ }
+
if ($request->filled('statusType') && $request->input('statusType') === 'RTD') {
$assets = $assets->RTD();
}
diff --git a/app/Http/Controllers/Api/CheckoutRequest.php b/app/Http/Controllers/Api/CheckoutRequest.php
index c314e1c92b..97935f57cf 100644
--- a/app/Http/Controllers/Api/CheckoutRequest.php
+++ b/app/Http/Controllers/Api/CheckoutRequest.php
@@ -9,13 +9,144 @@ use App\Exceptions\DuplicateCheckoutRequest;
use App\Exceptions\NoActiveCheckoutRequest;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
+use App\Http\Transformers\CheckoutRequestsTransformer;
+use App\Models\Accessory;
use App\Models\Asset;
+use App\Models\AssetModel;
+use App\Models\CheckoutRequest as CheckoutRequestModel;
+use App\Models\Company;
+use App\Models\Component;
+use App\Models\Consumable;
+use App\Models\License;
+use App\Models\Setting;
+use App\Models\User;
+use App\Notifications\RequestAssetCancelation;
+use App\Notifications\RequestAssetNotification;
use Exception;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\JsonResponse;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Log;
class CheckoutRequest extends Controller
{
+ /**
+ * Admin-scoped list of open (not-yet-canceled) checkout requests
+ * across all users. Mirrors the /requests Blade view so
+ * integrators can build their own approval / fulfilment UI (kiosk,
+ * mobile app, chat bot) against the same data set.
+ *
+ * FMCS scoping matches the Blade side exactly: rows are loaded, then
+ * a post-hoc Company::isCurrentUserHasAccess filter runs for
+ * non-superusers. That is O(rows) work rather than a whereHasMorph
+ * at the DB layer, but the request table stays small in practice
+ * and this behavior is what admins already see on the web page. If
+ * request volume ever justifies it, pushing the filter into a
+ * whereHasMorph across Asset/Accessory/Consumable/Component would
+ * move the cost back to the database.
+ */
+ public function index(Request $request): array
+ {
+ // Endpoint-level gate: allow through when the caller can
+ // checkout at least one of the five checkoutable types.
+ // The viewAnyCheckoutRequests gate (see AuthServiceProvider)
+ // wraps that OR - reused here + on the nav link in
+ // layouts/default.blade.php so both surfaces answer the
+ // "should this user see /requests at all?" question
+ // identically.
+ $this->authorize('viewAnyCheckoutRequests');
+
+ $user = auth()->user();
+
+ $query = CheckoutRequestModel::with('user', 'requestedItem')
+ ->pending();
+
+ if ($request->filled('user_id')) {
+ $query->where('user_id', $request->integer('user_id'));
+ }
+
+ if ($request->filled('requestable_type')) {
+ $query->where('requestable_type', $request->input('requestable_type'));
+ }
+
+ // ?search= hits notes + requester (Searchable trait's
+ // standard shape) AND the polymorphic requestable's name /
+ // location / category / company (via the model's
+ // advancedTextSearch override which whereHasMorphs across
+ // every requestable type). All at the DB layer, so search
+ // narrows the row set before the sort / FMCS filter below.
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ // Pull the (search-narrowed) set; sort happens in PHP after
+ // the FMCS filter below since the controller loads all-then-
+ // slice anyway. This also lets `remaining` sort work
+ // uniformly across the polymorphic requestable types (each
+ // computes numRemaining() differently, so a single DB
+ // orderBy wouldn't cover them). Default sort: most recent
+ // first, matches the pre-change behavior when no client-side
+ // header is chosen.
+ $requests = $query->get();
+
+ if (Company::isFullMultipleCompanySupportEnabled() && ! auth()->user()->isSuperUser()) {
+ $requests = $requests->filter(
+ fn (CheckoutRequestModel $r) => $r->requestable
+ && Company::isCurrentUserHasAccess($r->requestable)
+ )->values();
+ }
+
+ // Per-row checkout-permission filter. A caller who can
+ // checkout accessories but not assets sees accessory rows
+ // and no asset rows; the endpoint-level gate above only
+ // checks "any checkoutable type at all", so this second
+ // pass narrows to what they can actually fulfill.
+ // AssetModel rows map back to Asset for the check because
+ // fulfillment is via asset checkout. Skipped for superusers
+ // since Gate short-circuits true for them anyway.
+ if (! $user->isSuperUser()) {
+ $requests = $requests->filter(function (CheckoutRequestModel $r) use ($user): bool {
+ if (! $r->requestable_type) {
+ return false;
+ }
+ $permissionType = $r->requestable_type === AssetModel::class
+ ? Asset::class
+ : $r->requestable_type;
+
+ return $user->can('checkout', $permissionType);
+ })->values();
+ }
+
+ // Whitelist of sort keys mapped to the value extractor used
+ // for the in-PHP sort. Any other value the client sends is
+ // ignored - defends against a bs-tables regression that would
+ // otherwise let a caller sort by an unexpected attribute
+ // (raw property access on a polymorphic morphTo would throw
+ // on the first row where the attribute doesn't exist).
+ $sortKey = $request->input('sort', 'requested_at');
+ $direction = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sorters = [
+ 'requested_at' => fn (CheckoutRequestModel $r) => $r->created_at,
+ 'start_date' => fn (CheckoutRequestModel $r) => $r->start_date,
+ 'end_date' => fn (CheckoutRequestModel $r) => $r->end_date,
+ 'quantity' => fn (CheckoutRequestModel $r) => $r->quantity,
+ 'requestable.remaining' => fn (CheckoutRequestModel $r) => method_exists($r->requestable, 'numRemaining')
+ ? $r->requestable->numRemaining()
+ : null,
+ ];
+ $sorter = $sorters[$sortKey] ?? $sorters['requested_at'];
+ $requests = $direction === 'asc'
+ ? $requests->sortBy($sorter)->values()
+ : $requests->sortByDesc($sorter)->values();
+
+ $total = $requests->count();
+ $offset = (int) $request->input('offset', 0);
+ $limit = min((int) $request->input('limit', 50), 500);
+ $page = $requests->slice($offset, $limit)->values();
+
+ return (new CheckoutRequestsTransformer)->transformCheckoutRequests($page, $total);
+ }
+
public function store(Asset $asset): JsonResponse
{
try {
@@ -57,4 +188,148 @@ class CheckoutRequest extends Controller
return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.something_went_wrong')));
}
}
+
+ public function storeConsumable(Consumable $consumable): JsonResponse
+ {
+ return $this->createRequestFor($consumable, Consumable::RequestableConsumables()->find($consumable->id));
+ }
+
+ public function destroyConsumable(Consumable $consumable): JsonResponse
+ {
+ return $this->cancelRequestFor($consumable);
+ }
+
+ public function storeComponent(Component $component): JsonResponse
+ {
+ return $this->createRequestFor($component, Component::RequestableComponents()->find($component->id));
+ }
+
+ public function destroyComponent(Component $component): JsonResponse
+ {
+ return $this->cancelRequestFor($component);
+ }
+
+ public function storeLicense(License $license): JsonResponse
+ {
+ return $this->createRequestFor($license, License::RequestableLicenses()->find($license->id));
+ }
+
+ public function destroyLicense(License $license): JsonResponse
+ {
+ return $this->cancelRequestFor($license);
+ }
+
+ /**
+ * Shared create-request flow for Consumable + Component. 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.
+ */
+ private function createRequestFor($requestable, $requestableInScope): JsonResponse
+ {
+ try {
+ if (! $requestable || ! $requestableInScope) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.error')),
+ 403,
+ );
+ }
+
+ $user = auth()->user();
+
+ if ($requestable->isRequestedBy($user)) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.duplicate')),
+ 409,
+ );
+ }
+
+ $requestable->request();
+
+ $this->fireRequestNotification($requestable, $user, 'requested');
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.requests.success')));
+ } catch (Exception $e) {
+ report($e);
+
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.something_went_wrong')));
+ }
+ }
+
+ /**
+ * Shared cancel flow for Consumable + Component (self-cancel by
+ * the currently authenticated requester). FMCS scoping falls out
+ * of the model's global CompanyableScope on the reachable-check
+ * inside the notification firing.
+ */
+ private function cancelRequestFor($requestable): JsonResponse
+ {
+ try {
+ if (! Company::isCurrentUserHasAccess($requestable)) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('general.insufficient_permissions')),
+ 403,
+ );
+ }
+
+ $user = auth()->user();
+ $affected = $requestable->cancelRequest($user->id);
+
+ if ($affected === 0) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.no_active')),
+ 404,
+ );
+ }
+
+ $this->fireRequestNotification($requestable, $user, 'canceled');
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.requests.canceled')));
+ } catch (Exception $e) {
+ report($e);
+
+ return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.something_went_wrong')));
+ }
+ }
+
+ /**
+ * Fire the admin-alert notification for a request event. Failures
+ * are logged but don't fail the request, matching the tolerance
+ * the web-side ViewAssetsController::getRequestItem already has
+ * for a broken mail transport.
+ */
+ private function fireRequestNotification($requestable, User $user, string $action): void
+ {
+ $settings = Setting::getSettings();
+ if ($settings->alert_email === '' || $settings->alerts_enabled !== '1' || config('app.lock_passwords')) {
+ return;
+ }
+
+ $data = [
+ 'item' => $requestable,
+ 'item_type' => strtolower(class_basename($requestable)),
+ 'item_quantity' => 1,
+ 'target' => $user,
+ 'requested_by' => $user->display_name,
+ 'requested_date' => date('Y-m-d H:i:s'),
+ ];
+
+ try {
+ $notification = $action === 'canceled'
+ ? new RequestAssetCancelation($data)
+ : new RequestAssetNotification($data);
+ $settings->notify($notification->locale($settings->locale));
+ } catch (Exception $e) {
+ Log::warning('Could not send checkout-request notification: '.$e->getMessage());
+ }
+ }
}
diff --git a/app/Http/Controllers/Api/ComponentsController.php b/app/Http/Controllers/Api/ComponentsController.php
index 640a9aa787..150e026604 100644
--- a/app/Http/Controllers/Api/ComponentsController.php
+++ b/app/Http/Controllers/Api/ComponentsController.php
@@ -542,4 +542,32 @@ class ComponentsController extends Controller
return response()->json((new ActionlogsTransformer)->transformActionlogs($history, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
+
+ /**
+ * List components that are requestable AND reachable by the
+ * current caller (per FMCS + location scoping). Hydrates the
+ * components tab on /account/requestable. See the sibling
+ * AccessoriesController::requestable for design rationale.
+ */
+ public function requestable(Request $request): array
+ {
+ $query = Component::with('category', 'location', 'company', 'manufacturer', 'requests')
+ ->withCount('assets as components_assets_count')
+ ->RequestableComponents();
+
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ $total = $query->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+
+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sort = in_array($request->input('sort'), ['name', 'created_at'], true) ? $request->input('sort') : 'name';
+
+ $rows = $query->orderBy($sort, $order)->skip($offset)->take($limit)->get();
+
+ return (new ComponentsTransformer)->transformComponents($rows, $total);
+ }
}
diff --git a/app/Http/Controllers/Api/ConsumablesController.php b/app/Http/Controllers/Api/ConsumablesController.php
index 1f6c7e0ad7..b7f10a624d 100644
--- a/app/Http/Controllers/Api/ConsumablesController.php
+++ b/app/Http/Controllers/Api/ConsumablesController.php
@@ -497,4 +497,32 @@ class ConsumablesController extends Controller
return response()->json((new ActionlogsTransformer)->transformActionlogs($history, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
+
+ /**
+ * List consumables that are requestable AND reachable by the
+ * current caller (per FMCS + location scoping). Hydrates the
+ * consumables tab on /account/requestable. See the sibling
+ * AccessoriesController::requestable for design rationale.
+ */
+ public function requestable(Request $request): array
+ {
+ $query = Consumable::with('category', 'location', 'company', 'manufacturer', 'requests')
+ ->withCount('users as consumables_users_count')
+ ->RequestableConsumables();
+
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ $total = $query->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+
+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sort = in_array($request->input('sort'), ['name', 'created_at'], true) ? $request->input('sort') : 'name';
+
+ $rows = $query->orderBy($sort, $order)->skip($offset)->take($limit)->get();
+
+ return (new ConsumablesTransformer)->transformConsumables($rows, $total);
+ }
}
diff --git a/app/Http/Controllers/Api/LicensesController.php b/app/Http/Controllers/Api/LicensesController.php
index 19c4ccb4bb..3c3c773708 100644
--- a/app/Http/Controllers/Api/LicensesController.php
+++ b/app/Http/Controllers/Api/LicensesController.php
@@ -498,4 +498,31 @@ class LicensesController extends Controller
return response()->json((new ActionlogsTransformer)->transformActionlogs($history, $total), 200, ['Content-Type' => 'application/json;charset=utf8'], JSON_UNESCAPED_UNICODE);
}
+
+ /**
+ * List licenses that are requestable AND reachable by the current
+ * caller (per FMCS + location scoping). Hydrates the licenses tab
+ * on /account/requestable. See the sibling
+ * AccessoriesController::requestable for design rationale.
+ */
+ public function requestable(Request $request): array
+ {
+ $query = License::with('category', 'company', 'manufacturer', 'requests')
+ ->RequestableLicenses();
+
+ if ($request->filled('search')) {
+ $query->TextSearch($request->input('search'));
+ }
+
+ $total = $query->count();
+ $offset = ($request->input('offset') > $total) ? $total : app('api_offset_value');
+ $limit = app('api_limit_value');
+
+ $order = $request->input('order') === 'asc' ? 'asc' : 'desc';
+ $sort = in_array($request->input('sort'), ['name', 'created_at'], true) ? $request->input('sort') : 'name';
+
+ $rows = $query->orderBy($sort, $order)->skip($offset)->take($limit)->get();
+
+ return (new LicensesTransformer)->transformLicenses($rows, $total);
+ }
}