A free open source IT asset/license management system
Added searchable relations to checkout request model
snipe502414d8bc13
diff --git a/app/Models/CheckoutRequest.php b/app/Models/CheckoutRequest.phpindex 1320d31093..9fd21c7d96 100644--- a/app/Models/CheckoutRequest.php+++ b/app/Models/CheckoutRequest.php@@ -2,25 +2,118 @@namespace App\Models;+use App\Enums\CheckoutRequestState;+use App\Exceptions\InvalidCheckoutRequestTransition;+use App\Models\Traits\Searchable;+use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;+use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\SoftDeletes;+use Illuminate\Support\Collection;+/**+ * @property CheckoutRequestState $state+ */class CheckoutRequest extends Model{use HasFactory;+ use Searchable;use SoftDeletes;- protected $fillable = ['user_id', 'quantity', 'start_date', 'end_date'];+ protected $fillable = [+ 'user_id',+ 'quantity',+ 'fulfilled_quantity',+ 'start_date',+ 'end_date',+ 'notes',+ 'state',+ ];protected $table = 'checkout_requests';+ /**+ * Direct-column search targets for TextSearch (called by+ * Api\CheckoutRequest::index's ?search= handler).+ */+ protected $searchableAttributes = ['notes'];++ /**+ * Relation-scoped search targets. The requester side goes here;+ * the polymorphic requestable side is handled in+ * advancedTextSearch() below since Searchable doesn't understand+ * morphTo.+ */+ protected $searchableRelations = [+ 'user' => ['first_name', 'last_name', 'username', 'email'],+ ];+protected $casts = ['start_date' => 'date','end_date' => 'date',+ 'canceled_at' => 'datetime',+ 'fulfilled_at' => 'datetime',+ 'quantity' => 'integer',+ 'fulfilled_quantity' => 'integer',+ 'state' => CheckoutRequestState::class,];- public function user()+ protected $attributes = [+ 'state' => 'pending',+ 'fulfilled_quantity' => 0,+ ];++ /**+ * Remaining qty on this request. Requested minus fulfilled;+ * capped at 0 so an accidental over-fulfill upstream can't+ * return a negative here. Used by the partial-fulfillment+ * flow to figure out how much of an incoming fulfillment+ * should count against this row.+ */+ public function remainingQuantity(): int+ {+ return max(0, (int) $this->quantity - (int) $this->fulfilled_quantity);+ }++ /**+ * True when at least one unit has been fulfilled but the row+ * hasn't been fully satisfied yet. Renders as an in-between+ * badge on the admin queue + requester tab so both parties+ * see "partial" as distinct from "untouched pending".+ */+ public function isPartiallyFulfilled(): bool+ {+ return $this->state === CheckoutRequestState::Pending+ && $this->fulfilled_quantity > 0+ && $this->fulfilled_quantity < $this->quantity;+ }++ /**+ * Keep canceled_at + state in lockstep for the "one field says+ * WHEN, the other says WHAT" pattern the migration comment+ * calls out. Anyone assigning canceled_at directly (factories+ * with legacy `'canceled_at' => now()` shape, older callsites+ * that predate the state machine) gets state=canceled for free+ * so the pending-state scopes stay accurate.+ *+ * fulfilled_at is deliberately NOT mirrored here. FulfillCheckoutRequestAction+ * is the only fulfillment path (via the checkout-hook listener)+ * and sets both explicitly, so a synthetic mutator would just+ * hide bugs where someone reaches around the action.+ */+ protected static function booted(): void+ {+ static::saving(function (self $request): void {+ if ($request->canceled_at !== null+ && $request->state === CheckoutRequestState::Pending+ ) {+ $request->state = CheckoutRequestState::Canceled;+ }+ });+ }++ public function user(): BelongsTo{return $this->belongsTo(User::class, 'user_id', 'id');}@@ -35,6 +128,18 @@ class CheckoutRequest extends Modelreturn $this->morphTo('requestable');}+ /**+ * Standard-name morphTo. Same shape as requestedItem() above;+ * exists so Eloquent morph helpers (whereHasMorph, morphEager+ * loads) that infer the relation name from the column pair+ * requestable_type/requestable_id find it under the expected+ * key. Older callers keep using requestedItem() unchanged.+ */+ public function requestable()+ {+ return $this->morphTo();+ }+public function itemRequested() // Workaround for laravel polymorphic issue that's not being solved :({return $this->requestedItem()->first();@@ -58,4 +163,212 @@ class CheckoutRequest extends Modelreturn $this->itemRequested()->name;}++ public function fulfilledBy(): BelongsTo+ {+ return $this->belongsTo(User::class, 'fulfilled_by', 'id');+ }++ public function checkoutActionlog(): BelongsTo+ {+ return $this->belongsTo(Actionlog::class, 'checkout_actionlog_id', 'id');+ }++ /**+ * Open = still awaiting resolution. Drives the admin queue+ * default filter, the /account/requested tab default, and the+ * Requestable::isRequestedBy() gate. Terminal-state rows (+ * fulfilled, canceled) are excluded.+ */+ public function scopeOpen(Builder $query): Builder+ {+ return $query->where('state', CheckoutRequestState::Pending->value);+ }++ public function scopePending(Builder $query): Builder+ {+ return $query->where('state', CheckoutRequestState::Pending->value);+ }++ public function scopeFulfilled(Builder $query): Builder+ {+ return $query->where('state', CheckoutRequestState::Fulfilled->value);+ }++ public function scopeCanceled(Builder $query): Builder+ {+ return $query->where('state', CheckoutRequestState::Canceled->value);+ }++ public function isReservation(): bool+ {+ return $this->start_date !== null || $this->end_date !== null;+ }++ /**+ * Extend TextSearch with the polymorphic requestable side. The+ * standard Searchable trait only understands direct columns and+ * named relations; it has no way to spell "search the .name of+ * whatever requestable this row points at." This override adds+ * an orWhereHasMorph across the six requestable types so a+ * search hits the requestable name, location, category, and+ * company in the same query as the notes / requester side.+ *+ * Per-morph-type branching is needed because:+ * - Asset uses display_name AND asset_tag AND serial as its+ * primary identifiers; the rest use `name`.+ * - Asset's category is nested through model.category; every+ * other type has a direct category relation.+ * - AssetModel has no company relation (asset models are+ * shared across companies), so its branch skips company.+ *+ * @return Builder+ */+ public function advancedTextSearch(Builder $query, array $terms)+ {+ if (empty($terms)) {+ return $query;+ }++ $morphTypes = [+ Asset::class,+ AssetModel::class,+ Accessory::class,+ Consumable::class,+ Component::class,+ License::class,+ ];++ return $query->orWhereHasMorph('requestable', $morphTypes, function (Builder $q, string $type) use ($terms): void {+ $q->where(function (Builder $inner) use ($type, $terms): void {+ foreach ($terms as $term) {+ $like = '%'.$term.'%';++ // Primary name column varies by type. Asset uses+ // display_name (computed) so we search the+ // underlying storage columns instead.+ if ($type === Asset::class) {+ $inner->orWhere('name', 'LIKE', $like)+ ->orWhere('asset_tag', 'LIKE', $like)+ ->orWhere('serial', 'LIKE', $like);+ } else {+ $inner->orWhere('name', 'LIKE', $like);+ }++ // Category path is nested through model on Asset,+ // direct on every other type.+ if ($type === Asset::class) {+ $inner->orWhereHas('model.category', fn (Builder $r) => $r->where('name', 'LIKE', $like));+ } else {+ $inner->orWhereHas('category', fn (Builder $r) => $r->where('name', 'LIKE', $like));+ }++ // Location is only on the physical types (asset,+ // accessory, consumable, component). License is+ // intangible (no location); AssetModel is a+ // template (no location either).+ if (in_array($type, [Asset::class, Accessory::class, Consumable::class, Component::class], true)) {+ $inner->orWhereHas('location', fn (Builder $r) => $r->where('name', 'LIKE', $like));+ }++ // Company is direct on every FMCS-scoped type+ // (all except AssetModel, which is shared across+ // companies).+ if ($type !== AssetModel::class) {+ $inner->orWhereHas('company', fn (Builder $r) => $r->where('name', 'LIKE', $like));+ }+ }+ });+ });+ }++ /**+ * Transition guard. Throws when the caller tries to move a row+ * from a terminal state OR to a state that the current state+ * doesn't permit. Every state-machine Action calls this before+ * writing. Terminal states (fulfilled, canceled) are irreversible.+ */+ public function assertCanTransitionTo(CheckoutRequestState $target): void+ {+ // Same-state writes are a no-op transition and shouldn't+ // throw - callers rely on idempotent semantics for retry+ // safety (e.g. the fulfillment hook firing twice for a race+ // during a rapid double-submit).+ if ($this->state === $target) {+ return;+ }++ if ($this->state->isTerminal()) {+ throw new InvalidCheckoutRequestTransition($this, $this->state, $target);+ }++ // Currently only pending -> fulfilled and pending -> canceled+ // are legal. If more states land later (approved / denied /+ // expired), extend this matrix instead of dropping the guard.+ $legal = [+ CheckoutRequestState::Pending->value => [+ CheckoutRequestState::Fulfilled,+ CheckoutRequestState::Canceled,+ ],+ ];++ $permitted = $legal[$this->state->value] ?? [];+ if (! in_array($target, $permitted, true)) {+ throw new InvalidCheckoutRequestTransition($this, $this->state, $target);+ }+ }++ /**+ * Resolve the context needed to render the "you got here from a+ * /requests row" panel on the various checkout screens. Guards+ * against URL twiddling: the request row has to exist, be open+ * (pending state), target THIS specific requestable (both id and+ * polymorphic type), and belong to a still-existing user. Any+ * miss returns nulls / empty so callers can render nothing.+ *+ * @return array{checkoutRequest: ?self, requestingUserId: ?int, otherPendingRequests: Collection<int, self>}+ */+ public static function contextForCheckout(?int $requestId, string $requestableType, int $requestableId): array+ {+ $empty = [+ 'checkoutRequest' => null,+ 'requestingUserId' => null,+ 'otherPendingRequests' => collect(),+ ];++ if (! $requestId) {+ return $empty;+ }++ $checkoutRequest = static::where('id', $requestId)+ ->where('requestable_id', $requestableId)+ ->where('requestable_type', $requestableType)+ ->pending()+ ->with('user')+ ->first();++ if (! $checkoutRequest || ! $checkoutRequest->user) {+ return $empty;+ }++ // Every other open request for the same requestable, oldest+ // first (waiting-list semantic). Drops the current row and+ // any rows whose requester has since been hard-deleted.+ $otherPendingRequests = static::where('requestable_id', $requestableId)+ ->where('requestable_type', $requestableType)+ ->where('id', '!=', $checkoutRequest->id)+ ->pending()+ ->with('user')+ ->orderBy('created_at')+ ->orderBy('id')+ ->get()+ ->filter(fn (self $r) => $r->user !== null)+ ->values();++ return [+ 'checkoutRequest' => $checkoutRequest,+ 'requestingUserId' => $checkoutRequest->user->id,+ 'otherPendingRequests' => $otherPendingRequests,+ ];+ }}