Skip to content

A free open source IT asset/license management system

Renamed request (since it’s not just assets anymore)

snipe08168cc134c0
diff --git a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
index eaa7190339..c20c2c5b11 100644
--- a/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
+++ b/app/Actions/CheckoutRequests/CreateCheckoutRequestAction.php
@@ -2,8 +2,8 @@
namespace App\Actions\CheckoutRequests;
-use App\Exceptions\AssetNotRequestable;
use App\Exceptions\DuplicateCheckoutRequest;
+use App\Exceptions\ItemNotRequestable;
use App\Models\Actionlog;
use App\Models\Asset;
use App\Models\Company;
@@ -11,45 +11,83 @@ use App\Models\Setting;
use App\Models\User;
use App\Notifications\RequestAssetNotification;
use Illuminate\Auth\Access\AuthorizationException;
+use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Log;
class CreateCheckoutRequestAction
{
/**
- * @throws AssetNotRequestable
+ * Polymorphic request-submit path for every requestable type
+ * (Asset, AssetModel, Accessory, Consumable, Component, License).
+ *
+ * Consolidates the three previous submit paths (this action, the
+ * web-side ViewAssetsController::handleSubmitRequest, and the API-
+ * side Api\CheckoutRequest::createRequestFor) into a single flow
+ * that:
+ * - validates $requestable is flagged requestable AND FMCS-reachable
+ * - rejects duplicate open requests from the same (user, item) pair
+ * - writes a single actionlog row (uniform across all six types)
+ * - persists the request via the trait's request() method
+ * - bumps assets.requests_counter (Asset only - the counter is
+ * an Asset-specific denormalization; other types don't have one)
+ * - fires the admin-alert notification
+ *
+ * @param Model $requestable Must be a requestable-trait user
+ * @param int|null $qty Quantity for qty-tracked types (defaults to 1)
+ * @param string|null $startDate Optional reservation window start
+ * @param string|null $endDate Optional reservation window end
+ * @param string|null $notes Optional requester note
+ *
+ * @throws ItemNotRequestable
* @throws AuthorizationException
* @throws DuplicateCheckoutRequest
*/
- public static function run(Asset $asset, User $user): string
- {
- if (! $asset->isFlaggedRequestable()) {
- throw new AssetNotRequestable($asset);
+ public static function run(
+ Model $requestable,
+ User $user,
+ ?int $qty = 1,
+ ?string $startDate = null,
+ ?string $endDate = null,
+ ?string $notes = null,
+ ): bool {
+ if (! method_exists($requestable, 'isFlaggedRequestable') || ! $requestable->isFlaggedRequestable()) {
+ throw new ItemNotRequestable;
}
- if (! Company::isCurrentUserHasAccess($asset)) {
+ if (! Company::isCurrentUserHasAccess($requestable)) {
throw new AuthorizationException;
}
- // Enforce single-active-request-per-user-per-asset. Without
- // this gate the same POST fires repeatedly, adding duplicate
- // pending rows for the same (user, asset) pair. Downstream
- // aggregators (open_requests count, admin queue, requester
- // tab) all reason in terms of "one open row per pair" so
- // duplicates would double-count everywhere.
- if ($asset->isRequestedBy($user)) {
+ // Enforce single-active-request-per-user-per-item. Without this
+ // gate the same POST fires repeatedly, adding duplicate pending
+ // rows for the same (user, item) pair. Downstream aggregators
+ // (open_requests count, admin queue, requester tab) all reason
+ // in terms of "one open row per pair" so duplicates would
+ // double-count everywhere.
+ if ($requestable->isRequestedBy($user)) {
throw new DuplicateCheckoutRequest;
}
- $data['item'] = $asset;
- $data['target'] = $user;
- $data['item_quantity'] = 1;
- $settings = Setting::getSettings();
+ $now = date('Y-m-d H:i:s');
+ $data = [
+ 'item' => $requestable,
+ 'item_type' => strtolower(class_basename($requestable)),
+ 'item_quantity' => $qty ?? 1,
+ 'target' => $user,
+ 'requested_by' => $user->display_name,
+ 'user_id' => auth()->id(),
+ 'asset_id' => $requestable->getKey(),
+ 'requested_date' => $now,
+ 'start_date' => $startDate,
+ 'end_date' => $endDate,
+ 'note' => $notes,
+ ];
$logaction = new Actionlog;
- $logaction->item_id = $data['asset_id'] = $asset->id;
- $logaction->item_type = $data['item_type'] = Asset::class;
- $logaction->created_at = $data['requested_date'] = date('Y-m-d H:i:s');
- $logaction->target_id = $data['user_id'] = auth()->id();
+ $logaction->item_id = $requestable->getKey();
+ $logaction->item_type = $requestable::class;
+ $logaction->created_at = $now;
+ $logaction->target_id = auth()->id();
$logaction->target_type = User::class;
$logaction->location_id = $user->location_id ?? null;
$logaction->logaction('requested');
@@ -59,16 +97,22 @@ class CreateCheckoutRequestAction
// matching row (or vice versa). Counter is the denormalized
// fast-path for open-request reads on the assets list; state
// on the row is the source of truth, counter is a materialized
- // view kept in sync at write time.
- DB::transaction(function () use ($asset) {
- $asset->request();
- $asset->increment('requests_counter', 1);
+ // view kept in sync at write time. Only Asset carries the
+ // counter column, so the increment is guarded on type.
+ DB::transaction(function () use ($requestable, $qty, $startDate, $endDate, $notes) {
+ $requestable->request($qty ?? 1, $startDate, $endDate, $notes);
+ if ($requestable instanceof Asset) {
+ $requestable->increment('requests_counter', 1);
+ }
});
- try {
- $settings->notify((new RequestAssetNotification($data))->locale($settings->locale));
- } catch (\Exception $e) {
- Log::warning($e);
+ $settings = Setting::getSettings();
+ if ($settings->alert_email != '' && $settings->alerts_enabled == '1' && ! config('app.lock_passwords')) {
+ try {
+ $settings->notify((new RequestAssetNotification($data))->locale($settings->locale));
+ } catch (\Exception $e) {
+ Log::warning('Could not send asset request notification: '.$e->getMessage());
+ }
}
return true;
diff --git a/app/Exceptions/AssetNotRequestable.php b/app/Exceptions/ItemNotRequestable.php
similarity index 51%
rename from app/Exceptions/AssetNotRequestable.php
rename to app/Exceptions/ItemNotRequestable.php
index 34e8d91811..34927be45c 100644
--- a/app/Exceptions/AssetNotRequestable.php
+++ b/app/Exceptions/ItemNotRequestable.php
@@ -4,4 +4,4 @@ namespace App\Exceptions;
use Exception;
-class AssetNotRequestable extends Exception {}
+class ItemNotRequestable extends Exception {}
diff --git a/app/Http/Controllers/Api/CheckoutRequest.php b/app/Http/Controllers/Api/CheckoutRequest.php
index 08fdd2e427..bada294dc6 100644
--- a/app/Http/Controllers/Api/CheckoutRequest.php
+++ b/app/Http/Controllers/Api/CheckoutRequest.php
@@ -4,8 +4,8 @@ namespace App\Http\Controllers\Api;
use App\Actions\CheckoutRequests\CancelCheckoutRequestAction;
use App\Actions\CheckoutRequests\CreateCheckoutRequestAction;
-use App\Exceptions\AssetNotRequestable;
use App\Exceptions\DuplicateCheckoutRequest;
+use App\Exceptions\ItemNotRequestable;
use App\Exceptions\NoActiveCheckoutRequest;
use App\Helpers\Helper;
use App\Http\Controllers\Controller;
@@ -153,7 +153,7 @@ class CheckoutRequest extends Controller
CreateCheckoutRequestAction::run($asset, auth()->user());
return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.requests.success')));
- } catch (AssetNotRequestable $e) {
+ } catch (ItemNotRequestable $e) {
return response()->json(Helper::formatStandardApiResponse('error', 'Asset is not requestable'));
} catch (DuplicateCheckoutRequest $e) {
return response()->json(
@@ -221,42 +221,36 @@ class CheckoutRequest extends Controller
/**
* 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). The trait's
- * isFlaggedRequestable() check enforces BOTH the requestable flag
- * AND (via the CompanyableTrait global scope) the caller's FMCS +
- * location reach.
+ * Delegates to CreateCheckoutRequestAction, which owns the uniform
+ * actionlog + notification path across every requestable type
+ * (and gates the Asset-specific requests_counter increment).
*/
private function createRequestFor($requestable): JsonResponse
{
try {
- if (! $requestable || ! $requestable->isFlaggedRequestable()) {
- 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')));
+ CreateCheckoutRequestAction::run($requestable, auth()->user());
+ } catch (ItemNotRequestable $e) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.error')),
+ 403,
+ );
+ } catch (AuthorizationException $e) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('general.insufficient_permissions')),
+ 403,
+ );
+ } catch (DuplicateCheckoutRequest $e) {
+ return response()->json(
+ Helper::formatStandardApiResponse('error', null, trans('admin/hardware/message.requests.duplicate')),
+ 409,
+ );
} catch (Exception $e) {
report($e);
return response()->json(Helper::formatStandardApiResponse('error', null, trans('general.something_went_wrong')));
}
+
+ return response()->json(Helper::formatStandardApiResponse('success', null, trans('admin/hardware/message.requests.success')));
}
/**
diff --git a/app/Http/Controllers/ViewAssetsController.php b/app/Http/Controllers/ViewAssetsController.php
index 9e85ce561b..71caf9707b 100755
--- a/app/Http/Controllers/ViewAssetsController.php
+++ b/app/Http/Controllers/ViewAssetsController.php
@@ -5,7 +5,7 @@ namespace App\Http\Controllers;
use App\Actions\CheckoutRequests\CancelCheckoutRequestAction;
use App\Actions\CheckoutRequests\CreateCheckoutRequestAction;
use App\Enums\ActionType;
-use App\Exceptions\AssetNotRequestable;
+use App\Exceptions\ItemNotRequestable;
use App\Models\Accessory;
use App\Models\Actionlog;
use App\Models\Asset;
@@ -16,7 +16,6 @@ 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\Contracts\View\View;
@@ -219,7 +218,7 @@ class ViewAssetsController extends Controller
);
}
- return $this->handleSubmitRequest($request, $item, $fullItemType, $itemType);
+ return $this->handleSubmitRequest($request, $item);
}
/**
@@ -315,12 +314,8 @@ class ViewAssetsController extends Controller
return $this->redirectAfterRequestAction($request, 'admin/hardware/message.requests.canceled');
}
- private function handleSubmitRequest(Request $request, $item, string $fullItemType, string $itemType): RedirectResponse
+ private function handleSubmitRequest(Request $request, $item): 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
@@ -343,29 +338,25 @@ class ViewAssetsController extends Controller
// 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;
+ $qty = $request->has('request-quantity')
+ ? max(1, (int) $request->input('request-quantity'))
+ : 1;
- [$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());
- }
+ try {
+ CreateCheckoutRequestAction::run(
+ $item,
+ auth()->user(),
+ $qty,
+ $startDate,
+ $endDate,
+ $notes,
+ );
+ } catch (\App\Exceptions\ItemNotRequestable $e) {
+ return redirect()->back()->with('error', trans('admin/hardware/message.requests.error'));
+ } catch (AuthorizationException $e) {
+ return redirect()->back()->with('error', trans('general.insufficient_permissions'));
+ } catch (\App\Exceptions\DuplicateCheckoutRequest $e) {
+ return redirect()->back()->with('error', trans('admin/hardware/message.requests.duplicate'));
}
return $this->redirectAfterRequestAction($request, 'admin/hardware/message.requests.success');
@@ -388,7 +379,7 @@ class ViewAssetsController extends Controller
}
return $redirect;
- } catch (AssetNotRequestable $e) {
+ } catch (ItemNotRequestable $e) {
return redirect()->back()->with('error', 'Asset is not requestable');
} catch (\App\Exceptions\DuplicateCheckoutRequest $e) {
return redirect()->back()->with('error', trans('admin/hardware/message.requests.duplicate'));