A free open source IT asset/license management system
Migrated (I think) the last of the query scopes to builders
snipe6b42fbfa891d
diff --git a/app/Models/AccessoryCheckout.php b/app/Models/AccessoryCheckout.phpindex 6a17294389..f5df682378 100755--- a/app/Models/AccessoryCheckout.php+++ b/app/Models/AccessoryCheckout.php@@ -2,6 +2,7 @@namespace App\Models;+use App\Models\Builders\AccessoryCheckoutQueryBuilder;use App\Models\Traits\CompanyableChildTrait;use App\Models\Traits\Searchable;use App\Presenters\AccessoryPresenter;@@ -133,19 +134,9 @@ class AccessoryCheckout extends Modelreturn $this->assigned_type == Asset::class;}- public function scopeUserAssigned(Builder $query): void+ public function newEloquentBuilder($query): AccessoryCheckoutQueryBuilder{- $query->where('assigned_type', '=', User::class);- }-- public function scopeLocationAssigned(Builder $query): void- {- $query->where('assigned_type', '=', Location::class);- }-- public function scopeAssetsAssigned(Builder $query): void- {- $query->where('assigned_type', '=', Asset::class);+ return new AccessoryCheckoutQueryBuilder($query);}/**diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.phpindex 0b3bc5df46..3c92ec3ad3 100755--- a/app/Models/Actionlog.php+++ b/app/Models/Actionlog.php@@ -4,6 +4,7 @@ namespace App\Models;use App\Enums\ActionType;use App\Enums\FileStorage;+use App\Models\Builders\ActionlogQueryBuilder;use App\Models\Traits\CompanyableTrait;use App\Models\Traits\Searchable;use App\Presenters\ActionlogPresenter;@@ -12,7 +13,6 @@ use Carbon\Carbon;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;-use Illuminate\Database\Eloquent\Relations\MorphTo;use Illuminate\Database\Eloquent\Relations\Relation;use Illuminate\Database\Eloquent\SoftDeletes;use Illuminate\Support\Facades\Schema;@@ -501,27 +501,6 @@ class Actionlog extends SnipeModel);}- /**- * Eager load history relations used by the API transformer to avoid N+1 queries.- */- public function scopeForApiHistory($query)- {- return $query->with([- 'adminuser',- 'location',- 'item' => function (MorphTo $morphTo) {- $morphTo->morphWith([- Asset::class => ['model'],- ]);- },- 'target' => function (MorphTo $morphTo) {- $morphTo->morphWith([- Asset::class => ['model'],- ]);- },- ]);- }-/*** Establishes the actionlog -> location relationship*@@ -772,52 +751,8 @@ class Actionlog extends SnipeModel$this->source = $source;}- public function scopeOrderByCreatedBy($query, $order)- {- return $query->leftJoin('users as admin_sort', 'action_logs.created_by', '=', 'admin_sort.id')->addSelect('action_logs.*')->orderBy('admin_sort.first_name', $order)->orderBy('admin_sort.last_name', $order);- }-- // Audit report (issue #9430): the frontend has advertised location- // as sortable for a while but the API whitelist didn't include it,- // so clicks silently fell back to created_at. action_logs stores- // its own location_id snapshot (see the belongsTo above) so this- // is a plain leftJoin on locations, no polymorphic asset walk.- public function scopeOrderByLocation($query, $order)- {- return $query->leftJoin('locations as location_sort', 'action_logs.location_id', '=', 'location_sort.id')- ->addSelect('action_logs.*')- ->orderBy('location_sort.name', $order);- }-- // Also for the audit report: next_audit_date lives on the asset- // (the log doesn't snapshot it), so we join to assets on the- // polymorphic item_id + item_type pair. Non-Asset item_types get- // NULL from the leftJoin and sort naturally at the end.- public function scopeOrderByAssetNextAuditDate($query, $order)- {- return $query->leftJoin('assets as asset_sort', function ($join) {- $join->on('action_logs.item_id', '=', 'asset_sort.id')- ->where('action_logs.item_type', '=', Asset::class);- })- ->addSelect('action_logs.*')- ->orderBy('asset_sort.next_audit_date', $order);- }-- // Item name sort for the audit report (#9430). Only Assets get- // audited, so the action_type=audit filter upstream guarantees- // item_type=Asset here and a straight Asset join is correct.- // Sibling activity reports that sort by item on other action_types- // (checkout/checkin/etc.) will get NULL names for non-Asset rows- // and sort them at the ends; that matches the pre-refactor state- // where item sort silently fell back to created_at, and fixing- // truly-polymorphic item sort is a bigger separate change.- public function scopeOrderByItemName($query, $order)+ public function newEloquentBuilder($query): ActionlogQueryBuilder{- return $query->leftJoin('assets as asset_item_sort', function ($join) {- $join->on('action_logs.item_id', '=', 'asset_item_sort.id')- ->where('action_logs.item_type', '=', Asset::class);- })- ->addSelect('action_logs.*')- ->orderBy('asset_item_sort.name', $order);+ return new ActionlogQueryBuilder($query);}}diff --git a/app/Models/Asset.php b/app/Models/Asset.phpindex 2ca5ec1e62..d60308a70b 100644--- a/app/Models/Asset.php+++ b/app/Models/Asset.php@@ -7,6 +7,7 @@ use App\Events\CheckoutableCheckedOut;use App\Exceptions\CheckoutNotAllowed;use App\Helpers\Helper;use App\Http\Traits\UniqueUndeletedTrait;+use App\Models\Builders\AssetQueryBuilder;use App\Models\Traits\Acceptable;use App\Models\Traits\CompanyableTrait;use App\Models\Traits\HasCalendarEvents;@@ -1657,282 +1658,6 @@ class Asset extends Depreciablereturn $query;}- /**- * Query builder scope for hardware- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeHardware($query)- {- return $query->where('physical', '=', '1');- }-- /**- * Query builder scope for pending assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopePending($query)- {- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- $ids = Statuslabel::idsFor('pending');-- return $query->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);- }-- /**- * Query builder scope for searching location- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeAssetsByLocation($query, $location)- {- return $query->where(- function ($query) use ($location) {- $query->whereHas(- 'assignedTo', function ($query) use ($location) {- $query->where(- [- ['users.location_id', '=', $location->id],- ['assets.assigned_type', '=', User::class],- ]- )->orWhere(- [- ['locations.id', '=', $location->id],- ['assets.assigned_type', '=', Location::class],- ]- )->orWhere(- [- ['assets.rtd_location_id', '=', $location->id],- ['assets.assigned_type', '=', self::class],- ]- );- }- )->orWhere(- function ($query) use ($location) {- $query->where('assets.rtd_location_id', '=', $location->id);- $query->whereNull('assets.assigned_to');- }- );- }- );- }-- /**- * Query builder scope for RTD assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeRTD($query)- {- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- $ids = Statuslabel::idsFor('deployable');-- return $query->whereNull('assets.assigned_to')- ->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);- }-- /**- * Query builder scope for Undeployable assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeUndeployable($query)- {- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- $ids = Statuslabel::idsFor('undeployable');-- return $query->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);- }-- /**- * Query builder scope for non-Archived assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeNotArchived($query)- {- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- $ids = Statuslabel::idsFor('not_archived');-- return $query->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);- }-- /**- * Query builder scope for Assets that are due for auditing, based on the assets.next_audit_date- * and settings.audit_warning_days.- *- * This is/will be used in the artisan command snipeit:upcoming-audits and also- * for an upcoming API call for retrieving a report on assets that will need to be audited.- *- * Due for audit soon:- * next_audit_date greater than or equal to now (must be in the future)- * and (next_audit_date - threshold days) <= now ()- *- * Example:- * next_audit_date = May 4, 2025- * threshold for alerts = 30 days- * now = May 4, 2019- *- * @author A. Gianotto <[email protected]>- *- * @since v4.6.16- *- * @param Setting $settings- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeDueForAudit($query, $settings)- {- $interval = (int) $settings->audit_warning_days ?? 0;- $today = Carbon::now();- $interval_date = $today->copy()->addDays($interval)->format('Y-m-d');-- return $query->whereNotNull('assets.next_audit_date')- ->whereBetween('assets.next_audit_date', [$today->format('Y-m-d'), $interval_date])- ->where('assets.archived', '=', 0)- ->NotArchived();- }-- /**- * Query builder scope for Assets that are OVERDUE for auditing, based on the assets.next_audit_date- * and settings.audit_warning_days. It checks to see if assets.next audit_date is before now- *- * This is/will be used in the artisan command snipeit:upcoming-audits and also- * for an upcoming API call for retrieving a report on overdue assets.- *- * @author A. Gianotto <[email protected]>- *- * @since v4.6.16- *- * @param Setting $settings- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOverdueForAudit($query)- {- return $query->whereNotNull('assets.next_audit_date')- ->where('assets.next_audit_date', '<', Carbon::now()->format('Y-m-d'))- ->where('assets.archived', '=', 0)- ->NotArchived();- }-- /**- * Query builder scope for Assets whose asset_eol_date is in the past. Used by- * the NeedsAttention dashboard tile count and the hardware/past-eol view.- *- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopePastEol($query)- {- return $query->whereNotNull('assets.asset_eol_date')- ->where('assets.asset_eol_date', '<', Carbon::now()->format('Y-m-d'))- ->NotArchived();- }-- /**- * Query builder scope for Assets that are due for auditing OR overdue, based on the assets.next_audit_date- * and settings.audit_warning_days.- *- * This is/will be used in the artisan command snipeit:upcoming-audits and also- * for an upcoming API call for retrieving a report on assets that will need to be audited.- *- * @author A. Gianotto <[email protected]>- *- * @since v4.6.16- *- * @param Setting $settings- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeDueOrOverdueForAudit($query, $settings)- {-- return $query->where(- function ($query) {- $query->OverdueForAudit();- }- )->orWhere(- function ($query) use ($settings) {- $query->DueForAudit($settings);- }- );- }-- /**- * Query builder scope for Assets that are DUE for checkin, based on the assets.expected_checkin- * and settings.audit_warning_days. It checks to see if assets.expected_checkin is now- *- * @author A. Gianotto <[email protected]>- *- * @since v6.4.0- *- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeDueForCheckin($query, $settings)- {- $interval = (int) $settings->due_checkin_days ?? 0;- // expected_checkin is a DATETIME. Use startOfDay/endOfDay explicitly so- // an asset due back on the last day of the interval at (say) 2:30 PM- // still falls inside the range. Formatting only Y-m-d silently widens- // to midnight and would exclude anything later that day.- $windowStart = Carbon::now()->startOfDay();- $windowEnd = Carbon::now()->addDays($interval)->endOfDay();-- return $query->whereNotNull('assets.expected_checkin')- ->whereBetween('assets.expected_checkin', [$windowStart, $windowEnd])- ->where('assets.archived', '=', 0)- ->whereNotNull('assets.assigned_to')- ->NotArchived();- }-- /**- * Query builder scope for Assets that are overdue for checkin OR overdue- *- * @author A. Gianotto <[email protected]>- *- * @since v6.4.0- *- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOverdueForCheckin($query)- {- // expected_checkin is a DATETIME, so "overdue" is time-aware: an- // asset due back this morning at 09:00 is overdue by 09:01. Compare- // against Carbon::now() instead of today's midnight so mid-day- // dashboard views reflect what's actually late right now.- return $query->whereNotNull('assets.expected_checkin')- ->where('assets.expected_checkin', '<', Carbon::now())- ->where('assets.archived', '=', 0)- ->whereNotNull('assets.assigned_to')- ->NotArchived();- }-- /**- * Query builder scope for Assets that are due for checkin OR overdue- *- * @author A. Gianotto <[email protected]>- *- * @since v6.4.0- *- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeDueOrOverdueForCheckin($query, $settings)- {- return $query->where(- function ($query) {- $query->OverdueForCheckin();- }- )->orWhere(- function ($query) use ($settings) {- $query->DueForCheckin($settings);- }- );- }-public function calendarEventCompanyId(): ?int{return $this->company_id;@@ -1984,478 +1709,9 @@ class Asset extends Depreciable];}- public function scopeAssetsForShow($query)+ public function newEloquentBuilder($query): AssetQueryBuilder{- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- if (Setting::getSettings()->show_archived_in_list != 1) {- $validStatusIds = Statuslabel::idsFor('not_archived');-- return $query->whereIn('assets.status_id', $validStatusIds->isEmpty() ? [0] : $validStatusIds);- }-- return $query;- }-- /**- * Query builder scope for Archived assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeArchived($query)- {- // Pluck IDs then whereIn — do NOT replace with whereHas. whereHas generates a correlated EXISTS per row and causes severe slowdowns in withCount contexts.- $ids = Statuslabel::idsFor('archived');-- return $query->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);- }-- /**- * Query builder scope for Deployed assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeDeployed($query)- {- return $query->where('assigned_to', '>', '0');- }-- /**- * Query builder scope for Requestable assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeRequestable($query): Builder- {- $table = $query->getModel()->getTable();-- return Company::scopeCompanyables($query->where($table.'.requestable', '=', 1))- ->whereHas(- 'status', function ($query) {- $query->where(- function ($query) {- $query->where('deployable', '=', 1)- ->where('archived', '=', 0); // you definitely can't request something that's archived- }- )->orWhere('pending', '=', 1); // we've decided that even though an asset may be 'pending', you can still request it- }- );- }-- /**- * scopeInModelList- * Get all assets in the provided listing of model ids- *- *- * @return mixed- *- * @author Vincent Sposato <[email protected]>- *- * @version v1.0- */- public function scopeInModelList($query, array $modelIdListing)- {- return $query->whereIn('assets.model_id', $modelIdListing);- }-- /**- * Query builder scope to get not-yet-accepted assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeNotYetAccepted($query)- {- return $query->where('accepted', '=', 'pending');- }-- /**- * Query builder scope to get rejected assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeRejected($query)- {- return $query->where('accepted', '=', 'rejected');- }-- /**- * Query builder scope to get accepted assets- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeAccepted($query)- {- return $query->where('accepted', '=', 'accepted');- }-- /**- * Query builder scope to search on text for complex Bootstrap Tables API.- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $search Search term- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeAssignedSearch($query, $search)- {- $search = explode(' OR ', $search);-- return $query->leftJoin(- 'users as assets_users', function ($leftJoin) {- $leftJoin->on('assets_users.id', '=', 'assets.assigned_to')- ->where('assets.assigned_type', '=', User::class);- }- )->leftJoin(- 'locations as assets_locations', function ($leftJoin) {- $leftJoin->on('assets_locations.id', '=', 'assets.assigned_to')- ->where('assets.assigned_type', '=', Location::class);- }- )->leftJoin(- 'assets as assigned_assets', function ($leftJoin) {- $leftJoin->on('assigned_assets.id', '=', 'assets.assigned_to')- ->where('assets.assigned_type', '=', self::class);- }- )->where(- function ($query) use ($search) {- foreach ($search as $search) {- $query->whereHas(- 'model', function ($query) use ($search) {- $query->whereHas(- 'category', function ($query) use ($search) {- $query->where(- function ($query) use ($search) {- $query->where('categories.name', 'LIKE', '%'.$search.'%')- ->orWhere('models.name', 'LIKE', '%'.$search.'%')- ->orWhere('models.model_number', 'LIKE', '%'.$search.'%');- }- );- }- );- }- )->orWhereHas(- 'model', function ($query) use ($search) {- $query->whereHas(- 'manufacturer', function ($query) use ($search) {- $query->where(- function ($query) use ($search) {- $query->where('manufacturers.name', 'LIKE', '%'.$search.'%');- }- );- }- );- }- )->orWhere(- function ($query) use ($search) {- $query->where('assets_users.first_name', 'LIKE', '%'.$search.'%')- ->orWhere('assets_users.last_name', 'LIKE', '%'.$search.'%')- ->orWhere('assets_users.username', 'LIKE', '%'.$search.'%')- ->orWhere('assets_users.jobtitle', 'LIKE', '%'.$search.'%')- ->orWhereMultipleColumns(- [- 'assets_users.first_name',- 'assets_users.last_name',- 'assets_users.jobtitle',- ], $search- )- ->orWhere('assets_locations.name', 'LIKE', '%'.$search.'%')- ->orWhere('assigned_assets.name', 'LIKE', '%'.$search.'%');- }- )->orWhere('assets.name', 'LIKE', '%'.$search.'%')- ->orWhere('assets.asset_tag', 'LIKE', '%'.$search.'%')- ->orWhere('assets.serial', 'LIKE', '%'.$search.'%')- ->orWhere('assets.order_number', 'LIKE', '%'.$search.'%')- ->orWhere('assets.notes', 'LIKE', '%'.$search.'%');- }-- }- )->withTrashed()->whereNull('assets.deleted_at'); // workaround for laravel bug- }-- /**- * Query builder scope to search the department ID of users assigned to assets- *- * @author [A. Gianotto] [<[email protected]>]- *- * @since [v5.0]- *- * @return string | false- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeCheckedOutToTargetInDepartment($query, $search)- {- return $query->leftJoin(- 'users as assets_dept_users', function ($leftJoin) {- $leftJoin->on('assets_dept_users.id', '=', 'assets.assigned_to')- ->where('assets.assigned_type', '=', User::class);- }- )->where(- function ($query) use ($search) {- $query->whereIn('assets_dept_users.department_id', $search);-- }- )->withTrashed()->whereNull('assets.deleted_at'); // workaround for laravel bug- }-- /**- * Query builder scope to order on model- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderModels($query, $order)- {- return $query->join('models as asset_models', 'assets.model_id', '=', 'asset_models.id')->orderBy('asset_models.name', $order);- }-- /**- * Query builder scope to order on model number- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderModelNumber($query, $order)- {- return $query->leftJoin('models as model_number_sort', 'assets.model_id', '=', 'model_number_sort.id')->orderBy('model_number_sort.model_number', $order);- }-- /**- * Query builder scope to order on created_by name- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderByCreatedByName($query, $order)- {- // addSelect rather than select, so prior withCount subqueries- // (which append their count-expressions to the select list)- // don't get wiped by the join and trigger an N+1 on the- // reload.- return $query- ->leftJoin('users as admin_sort', 'assets.created_by', '=', 'admin_sort.id')- ->addSelect('assets.*')- ->orderBy('admin_sort.first_name', $order)- ->orderBy('admin_sort.last_name', $order);- }-- /**- * Query builder scope to order on assigned user- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderAssigned($query, $order)- {- return $query- ->leftJoin('users as users_sort', function ($join) {- $join->on('assets.assigned_to', '=', 'users_sort.id')- ->where('assets.assigned_type', '=', User::class);- })- ->addSelect('assets.*')- ->orderBy('users_sort.first_name', $order)- ->orderBy('users_sort.last_name', $order);- }-- /**- * Query builder scope to order on status- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderStatus($query, $order)- {- return $query->join('status_labels as status_sort', 'assets.status_id', '=', 'status_sort.id')->orderBy('status_sort.name', $order);- }-- /**- * Query builder scope to order on company- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderCompany($query, $order)- {- return $query->leftJoin('companies as company_sort', 'assets.company_id', '=', 'company_sort.id')->orderBy('company_sort.name', $order);- }-- /**- * Sort by a sync-adapter external-source column (primary_mac,- * primary_ip, os, os_version, last_seen). LeftJoin so unsynced- * assets sort as nulls rather than dropping out. Join is on the- * unique asset_id index in asset_external_sources, so cost is- * an index lookup per row.- *- * Column argument is whitelisted by the caller (AssetsController's- * sort switch) so it's never user-controlled at this layer, but- * we still validate against the known column set as defense-in-- * depth against a caller regression.- */- public function scopeOrderExternalSource($query, string $order, string $column)- {- if (! in_array($column, ['primary_mac', 'primary_ip', 'os', 'os_version', 'last_seen'], true)) {- return $query;- }-- return $query->leftJoin(- 'asset_external_sources as ext_src_sort',- 'assets.id',- '=',- 'ext_src_sort.asset_id',- )->orderBy('ext_src_sort.'.$column, $order);- }-- /**- * Query builder scope to return results of a category- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeInCategory($query, $category_id)- {- return $query->join('models as category_models', 'assets.model_id', '=', 'category_models.id')- ->join('categories', 'category_models.category_id', '=', 'categories.id')- ->whereIn('category_models.category_id', (! is_array($category_id) ? explode(',', $category_id) : $category_id));- // ->whereIn('category_models.category_id', $category_id);- }-- /**- * Query builder scope to return results of a manufacturer- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeByManufacturer($query, $manufacturer_id)- {- return $query->join('models', 'assets.model_id', '=', 'models.id')- ->join('manufacturers', 'models.manufacturer_id', '=', 'manufacturers.id')->whereIn('models.manufacturer_id', (! is_array($manufacturer_id) ? explode(',', $manufacturer_id) : $manufacturer_id));- }-- /**- * Query builder scope to order on category- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderCategory($query, $order)- {- return $query->join('models as order_model_category', 'assets.model_id', '=', 'order_model_category.id')- ->join('categories as category_order', 'order_model_category.category_id', '=', 'category_order.id')- ->orderBy('category_order.name', $order);- }-- /**- * Query builder scope to order on manufacturer- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderManufacturer($query, $order)- {- return $query->join('models as order_asset_model', 'assets.model_id', '=', 'order_asset_model.id')- ->leftjoin('manufacturers as manufacturer_order', 'order_asset_model.manufacturer_id', '=', 'manufacturer_order.id')- ->orderBy('manufacturer_order.name', $order);- }-- /**- * Query builder scope to order on location- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderLocation($query, $order)- {- return $query->leftJoin('locations as asset_locations', 'asset_locations.id', '=', 'assets.location_id')->orderBy('asset_locations.name', $order);- }-- /**- * Query builder scope to order on default- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderRtdLocation($query, $order)- {- return $query->leftJoin('locations as rtd_asset_locations', 'rtd_asset_locations.id', '=', 'assets.rtd_location_id')->orderBy('rtd_asset_locations.name', $order);- }-- /**- * Query builder scope to order on supplier name- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderSupplier($query, $order)- {- return $query->leftJoin('suppliers as suppliers_assets', 'assets.supplier_id', '=', 'suppliers_assets.id')->orderBy('suppliers_assets.name', $order);- }-- /**- * Query builder scope to order on supplier name- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $order Order- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeOrderByJobTitle($query, $order)- {- return $query- ->leftJoin('users as users_sort', function ($join) {- $join->on('assets.assigned_to', '=', 'users_sort.id')- ->where('assets.assigned_type', '=', User::class);- })- ->addSelect('assets.*')- ->orderBy('users_sort.jobtitle', $order);- }-- /**- * Query builder scope to search on location ID- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $search Search term- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeByLocationId($query, $search)- {- return $query->where(- function ($query) use ($search) {- $query->whereHas(- 'location', function ($query) use ($search) {- $query->where('locations.id', '=', $search);- }- );- }- );-- }-- /**- * Query builder scope to search on depreciation name- *- * @param \Illuminate\Database\Query\Builder $query Query builder instance- * @param text $search Search term- * @return \Illuminate\Database\Query\Builder Modified query builder- */- public function scopeByDepreciationId($query, $search)- {- return $query->join('models', 'assets.model_id', '=', 'models.id')- ->join('depreciations', 'models.depreciation_id', '=', 'depreciations.id')->where('models.depreciation_id', '=', $search);-+ return new AssetQueryBuilder($query);}/**diff --git a/app/Models/Builders/AccessoryCheckoutQueryBuilder.php b/app/Models/Builders/AccessoryCheckoutQueryBuilder.phpnew file mode 100644index 0000000000..cfc36bfa46--- /dev/null+++ b/app/Models/Builders/AccessoryCheckoutQueryBuilder.php@@ -0,0 +1,26 @@+<?php++namespace App\Models\Builders;++use App\Models\Asset;+use App\Models\Location;+use App\Models\User;+use Illuminate\Database\Eloquent\Builder;++class AccessoryCheckoutQueryBuilder extends Builder+{+ public function userAssigned(): static+ {+ return $this->where('assigned_type', '=', User::class);+ }++ public function locationAssigned(): static+ {+ return $this->where('assigned_type', '=', Location::class);+ }++ public function assetsAssigned(): static+ {+ return $this->where('assigned_type', '=', Asset::class);+ }+}diff --git a/app/Models/Builders/ActionlogQueryBuilder.php b/app/Models/Builders/ActionlogQueryBuilder.phpnew file mode 100644index 0000000000..d3deb0d001--- /dev/null+++ b/app/Models/Builders/ActionlogQueryBuilder.php@@ -0,0 +1,77 @@+<?php++namespace App\Models\Builders;++use App\Models\Asset;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Database\Eloquent\Relations\MorphTo;++class ActionlogQueryBuilder extends Builder+{+ /**+ * Eager load history relations used by the API transformer to avoid+ * N+1 queries.+ */+ public function forApiHistory(): static+ {+ return $this->with([+ 'adminuser',+ 'location',+ 'item' => function (MorphTo $morphTo) {+ $morphTo->morphWith([+ Asset::class => ['model'],+ ]);+ },+ 'target' => function (MorphTo $morphTo) {+ $morphTo->morphWith([+ Asset::class => ['model'],+ ]);+ },+ ]);+ }++ public function orderByCreatedBy(string $order): static+ {+ return $this+ ->leftJoin('users as admin_sort', 'action_logs.created_by', '=', 'admin_sort.id')+ ->addSelect('action_logs.*')+ ->orderBy('admin_sort.first_name', $order)+ ->orderBy('admin_sort.last_name', $order);+ }++ public function orderByLocation(string $order): static+ {+ return $this+ ->leftJoin('locations as location_sort', 'action_logs.location_id', '=', 'location_sort.id')+ ->addSelect('action_logs.*')+ ->orderBy('location_sort.name', $order);+ }++ public function orderByAssetNextAuditDate(string $order): static+ {+ return $this+ ->leftJoin('assets as asset_sort', function ($join) {+ $join->on('action_logs.item_id', '=', 'asset_sort.id')+ ->where('action_logs.item_type', '=', Asset::class);+ })+ ->addSelect('action_logs.*')+ ->orderBy('asset_sort.next_audit_date', $order);+ }++ /**+ * Item name sort for the audit report (#9430). Only Assets get+ * audited, so the action_type=audit filter upstream guarantees+ * item_type=Asset. Fixing truly-polymorphic item sort is a bigger+ * change.+ */+ public function orderByItemName(string $order): static+ {+ return $this+ ->leftJoin('assets as asset_item_sort', function ($join) {+ $join->on('action_logs.item_id', '=', 'asset_item_sort.id')+ ->where('action_logs.item_type', '=', Asset::class);+ })+ ->addSelect('action_logs.*')+ ->orderBy('asset_item_sort.name', $order);+ }+}diff --git a/app/Models/Builders/AssetQueryBuilder.php b/app/Models/Builders/AssetQueryBuilder.phpnew file mode 100644index 0000000000..2626f8400b--- /dev/null+++ b/app/Models/Builders/AssetQueryBuilder.php@@ -0,0 +1,435 @@+<?php++namespace App\Models\Builders;++use App\Models\Asset;+use App\Models\Company;+use App\Models\Location;+use App\Models\Setting;+use App\Models\Statuslabel;+use App\Models\User;+use Carbon\Carbon;+use Illuminate\Database\Eloquent\Builder;++class AssetQueryBuilder extends Builder+{+ public function hardware(): static+ {+ return $this->where('physical', '=', '1');+ }++ public function pending(): static+ {+ // Pluck IDs then whereIn. Do NOT replace with whereHas. whereHas+ // generates a correlated EXISTS per row and causes severe+ // slowdowns in withCount contexts.+ $ids = Statuslabel::idsFor('pending');++ return $this->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);+ }++ public function assetsByLocation(Location $location): static+ {+ return $this->where(function ($query) use ($location) {+ $query->whereHas('assignedTo', function ($query) use ($location) {+ $query->where([+ ['users.location_id', '=', $location->id],+ ['assets.assigned_type', '=', User::class],+ ])->orWhere([+ ['locations.id', '=', $location->id],+ ['assets.assigned_type', '=', Location::class],+ ])->orWhere([+ ['assets.rtd_location_id', '=', $location->id],+ ['assets.assigned_type', '=', Asset::class],+ ]);+ })->orWhere(function ($query) use ($location) {+ $query->where('assets.rtd_location_id', '=', $location->id);+ $query->whereNull('assets.assigned_to');+ });+ });+ }++ public function rtd(): static+ {+ $ids = Statuslabel::idsFor('deployable');++ return $this->whereNull('assets.assigned_to')+ ->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);+ }++ public function undeployable(): static+ {+ $ids = Statuslabel::idsFor('undeployable');++ return $this->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);+ }++ public function notArchived(): static+ {+ $ids = Statuslabel::idsFor('not_archived');++ return $this->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);+ }++ public function dueForAudit(Setting $settings): static+ {+ $interval = (int) $settings->audit_warning_days ?? 0;+ $today = Carbon::now();+ $interval_date = $today->copy()->addDays($interval)->format('Y-m-d');++ return $this->whereNotNull('assets.next_audit_date')+ ->whereBetween('assets.next_audit_date', [$today->format('Y-m-d'), $interval_date])+ ->where('assets.archived', '=', 0)+ ->notArchived();+ }++ public function overdueForAudit(): static+ {+ return $this->whereNotNull('assets.next_audit_date')+ ->where('assets.next_audit_date', '<', Carbon::now()->format('Y-m-d'))+ ->where('assets.archived', '=', 0)+ ->notArchived();+ }++ public function pastEol(): static+ {+ return $this->whereNotNull('assets.asset_eol_date')+ ->where('assets.asset_eol_date', '<', Carbon::now()->format('Y-m-d'))+ ->notArchived();+ }++ public function dueOrOverdueForAudit(Setting $settings): static+ {+ return $this->where(function ($query) {+ $query->overdueForAudit();+ })->orWhere(function ($query) use ($settings) {+ $query->dueForAudit($settings);+ });+ }++ public function dueForCheckin(Setting $settings): static+ {+ $interval = (int) $settings->due_checkin_days ?? 0;+ // expected_checkin is a DATETIME. Use startOfDay / endOfDay+ // explicitly so an asset due back on the last day of the+ // interval at (say) 2:30 PM still falls inside the range.+ // Formatting only Y-m-d silently widens to midnight and would+ // exclude anything later that day.+ $windowStart = Carbon::now()->startOfDay();+ $windowEnd = Carbon::now()->addDays($interval)->endOfDay();++ return $this->whereNotNull('assets.expected_checkin')+ ->whereBetween('assets.expected_checkin', [$windowStart, $windowEnd])+ ->where('assets.archived', '=', 0)+ ->whereNotNull('assets.assigned_to')+ ->notArchived();+ }++ public function overdueForCheckin(): static+ {+ // expected_checkin is a DATETIME, so "overdue" is time-aware: an+ // asset due back this morning at 09:00 is overdue by 09:01.+ // Compare against Carbon::now() instead of today's midnight so+ // mid-day dashboard views reflect what's actually late right+ // now.+ return $this->whereNotNull('assets.expected_checkin')+ ->where('assets.expected_checkin', '<', Carbon::now())+ ->where('assets.archived', '=', 0)+ ->whereNotNull('assets.assigned_to')+ ->notArchived();+ }++ public function dueOrOverdueForCheckin(Setting $settings): static+ {+ return $this->where(function ($query) {+ $query->overdueForCheckin();+ })->orWhere(function ($query) use ($settings) {+ $query->dueForCheckin($settings);+ });+ }++ public function assetsForShow(): static+ {+ // Pluck IDs then whereIn. Do NOT replace with whereHas.+ if (Setting::getSettings()->show_archived_in_list != 1) {+ $validStatusIds = Statuslabel::idsFor('not_archived');++ return $this->whereIn('assets.status_id', $validStatusIds->isEmpty() ? [0] : $validStatusIds);+ }++ return $this;+ }++ public function archived(): static+ {+ $ids = Statuslabel::idsFor('archived');++ return $this->whereIn('assets.status_id', $ids->isEmpty() ? [0] : $ids);+ }++ public function deployed(): static+ {+ return $this->where('assigned_to', '>', '0');+ }++ public function requestable(): static+ {+ $table = $this->getModel()->getTable();++ return Company::scopeCompanyables($this->where($table.'.requestable', '=', 1))+ ->whereHas('status', function ($query) {+ $query->where(function ($query) {+ $query->where('deployable', '=', 1)+ ->where('archived', '=', 0); // you definitely can't request something that's archived+ })->orWhere('pending', '=', 1); // we've decided that even though an asset may be 'pending', you can still request it+ });+ }++ /**+ * @param array<int, int> $modelIdListing+ */+ public function inModelList(array $modelIdListing): static+ {+ return $this->whereIn('assets.model_id', $modelIdListing);+ }++ public function notYetAccepted(): static+ {+ return $this->where('accepted', '=', 'pending');+ }++ public function rejected(): static+ {+ return $this->where('accepted', '=', 'rejected');+ }++ public function accepted(): static+ {+ return $this->where('accepted', '=', 'accepted');+ }++ public function assignedSearch(string $search): static+ {+ $search = explode(' OR ', $search);++ return $this->leftJoin('users as assets_users', function ($leftJoin) {+ $leftJoin->on('assets_users.id', '=', 'assets.assigned_to')+ ->where('assets.assigned_type', '=', User::class);+ })->leftJoin('locations as assets_locations', function ($leftJoin) {+ $leftJoin->on('assets_locations.id', '=', 'assets.assigned_to')+ ->where('assets.assigned_type', '=', Location::class);+ })->leftJoin('assets as assigned_assets', function ($leftJoin) {+ $leftJoin->on('assigned_assets.id', '=', 'assets.assigned_to')+ ->where('assets.assigned_type', '=', Asset::class);+ })->where(function ($query) use ($search) {+ foreach ($search as $search) {+ $query->whereHas('model', function ($query) use ($search) {+ $query->whereHas('category', function ($query) use ($search) {+ $query->where(function ($query) use ($search) {+ $query->where('categories.name', 'LIKE', '%'.$search.'%')+ ->orWhere('models.name', 'LIKE', '%'.$search.'%')+ ->orWhere('models.model_number', 'LIKE', '%'.$search.'%');+ });+ });+ })->orWhereHas('model', function ($query) use ($search) {+ $query->whereHas('manufacturer', function ($query) use ($search) {+ $query->where(function ($query) use ($search) {+ $query->where('manufacturers.name', 'LIKE', '%'.$search.'%');+ });+ });+ })->orWhere(function ($query) use ($search) {+ $query->where('assets_users.first_name', 'LIKE', '%'.$search.'%')+ ->orWhere('assets_users.last_name', 'LIKE', '%'.$search.'%')+ ->orWhere('assets_users.username', 'LIKE', '%'.$search.'%')+ ->orWhere('assets_users.jobtitle', 'LIKE', '%'.$search.'%')+ ->orWhereMultipleColumns(+ [+ 'assets_users.first_name',+ 'assets_users.last_name',+ 'assets_users.jobtitle',+ ], $search+ )+ ->orWhere('assets_locations.name', 'LIKE', '%'.$search.'%')+ ->orWhere('assigned_assets.name', 'LIKE', '%'.$search.'%');+ })->orWhere('assets.name', 'LIKE', '%'.$search.'%')+ ->orWhere('assets.asset_tag', 'LIKE', '%'.$search.'%')+ ->orWhere('assets.serial', 'LIKE', '%'.$search.'%')+ ->orWhere('assets.order_number', 'LIKE', '%'.$search.'%')+ ->orWhere('assets.notes', 'LIKE', '%'.$search.'%');+ }+ })->withTrashed()->whereNull('assets.deleted_at'); // workaround for laravel bug+ }++ /**+ * Query builder scope to search the department ID of users+ * assigned to assets.+ *+ * @param array<int, int> $search+ */+ public function checkedOutToTargetInDepartment(array $search): static+ {+ return $this->leftJoin('users as assets_dept_users', function ($leftJoin) {+ $leftJoin->on('assets_dept_users.id', '=', 'assets.assigned_to')+ ->where('assets.assigned_type', '=', User::class);+ })->where(function ($query) use ($search) {+ $query->whereIn('assets_dept_users.department_id', $search);+ })->withTrashed()->whereNull('assets.deleted_at'); // workaround for laravel bug+ }++ public function orderModels(string $order): static+ {+ return $this+ ->join('models as asset_models', 'assets.model_id', '=', 'asset_models.id')+ ->orderBy('asset_models.name', $order);+ }++ public function orderModelNumber(string $order): static+ {+ return $this+ ->leftJoin('models as model_number_sort', 'assets.model_id', '=', 'model_number_sort.id')+ ->orderBy('model_number_sort.model_number', $order);+ }++ public function orderByCreatedByName(string $order): static+ {+ // addSelect rather than select, so prior withCount subqueries+ // (which append their count-expressions to the select list)+ // don't get wiped by the join and trigger an N+1 on the+ // reload.+ return $this+ ->leftJoin('users as admin_sort', 'assets.created_by', '=', 'admin_sort.id')+ ->addSelect('assets.*')+ ->orderBy('admin_sort.first_name', $order)+ ->orderBy('admin_sort.last_name', $order);+ }++ public function orderAssigned(string $order): static+ {+ return $this+ ->leftJoin('users as users_sort', function ($join) {+ $join->on('assets.assigned_to', '=', 'users_sort.id')+ ->where('assets.assigned_type', '=', User::class);+ })+ ->addSelect('assets.*')+ ->orderBy('users_sort.first_name', $order)+ ->orderBy('users_sort.last_name', $order);+ }++ public function orderStatus(string $order): static+ {+ return $this+ ->join('status_labels as status_sort', 'assets.status_id', '=', 'status_sort.id')+ ->orderBy('status_sort.name', $order);+ }++ public function orderCompany(string $order): static+ {+ return $this+ ->leftJoin('companies as company_sort', 'assets.company_id', '=', 'company_sort.id')+ ->orderBy('company_sort.name', $order);+ }++ /**+ * Sort by a sync-adapter external-source column (primary_mac,+ * primary_ip, os, os_version, last_seen). LeftJoin so unsynced+ * assets sort as nulls rather than dropping out. Join is on the+ * unique asset_id index in asset_external_sources, so cost is an+ * index lookup per row.+ *+ * Column argument is whitelisted by the caller+ * (AssetsController's sort switch) so it's never user-controlled+ * at this layer, but we still validate against the known column+ * set as defense-in-depth against a caller regression.+ */+ public function orderExternalSource(string $order, string $column): static+ {+ if (! in_array($column, ['primary_mac', 'primary_ip', 'os', 'os_version', 'last_seen'], true)) {+ return $this;+ }++ return $this+ ->leftJoin('asset_external_sources as ext_src_sort', 'assets.id', '=', 'ext_src_sort.asset_id')+ ->orderBy('ext_src_sort.'.$column, $order);+ }++ public function inCategory(string|array $category_id): static+ {+ return $this+ ->join('models as category_models', 'assets.model_id', '=', 'category_models.id')+ ->join('categories', 'category_models.category_id', '=', 'categories.id')+ ->whereIn('category_models.category_id', (! is_array($category_id) ? explode(',', $category_id) : $category_id));+ }++ public function byManufacturer(string|array $manufacturer_id): static+ {+ return $this+ ->join('models', 'assets.model_id', '=', 'models.id')+ ->join('manufacturers', 'models.manufacturer_id', '=', 'manufacturers.id')+ ->whereIn('models.manufacturer_id', (! is_array($manufacturer_id) ? explode(',', $manufacturer_id) : $manufacturer_id));+ }++ public function orderCategory(string $order): static+ {+ return $this+ ->join('models as order_model_category', 'assets.model_id', '=', 'order_model_category.id')+ ->join('categories as category_order', 'order_model_category.category_id', '=', 'category_order.id')+ ->orderBy('category_order.name', $order);+ }++ public function orderManufacturer(string $order): static+ {+ return $this+ ->join('models as order_asset_model', 'assets.model_id', '=', 'order_asset_model.id')+ ->leftJoin('manufacturers as manufacturer_order', 'order_asset_model.manufacturer_id', '=', 'manufacturer_order.id')+ ->orderBy('manufacturer_order.name', $order);+ }++ public function orderLocation(string $order): static+ {+ return $this+ ->leftJoin('locations as asset_locations', 'asset_locations.id', '=', 'assets.location_id')+ ->orderBy('asset_locations.name', $order);+ }++ public function orderRtdLocation(string $order): static+ {+ return $this+ ->leftJoin('locations as rtd_asset_locations', 'rtd_asset_locations.id', '=', 'assets.rtd_location_id')+ ->orderBy('rtd_asset_locations.name', $order);+ }++ public function orderSupplier(string $order): static+ {+ return $this+ ->leftJoin('suppliers as suppliers_assets', 'assets.supplier_id', '=', 'suppliers_assets.id')+ ->orderBy('suppliers_assets.name', $order);+ }++ public function orderByJobTitle(string $order): static+ {+ return $this+ ->leftJoin('users as users_sort', function ($join) {+ $join->on('assets.assigned_to', '=', 'users_sort.id')+ ->where('assets.assigned_type', '=', User::class);+ })+ ->addSelect('assets.*')+ ->orderBy('users_sort.jobtitle', $order);+ }++ public function byLocationId(int $search): static+ {+ return $this->where(function ($query) use ($search) {+ $query->whereHas('location', function ($query) use ($search) {+ $query->where('locations.id', '=', $search);+ });+ });+ }++ public function byDepreciationId(int $search): static+ {+ return $this+ ->join('models', 'assets.model_id', '=', 'models.id')+ ->join('depreciations', 'models.depreciation_id', '=', 'depreciations.id')+ ->where('models.depreciation_id', '=', $search);+ }+}diff --git a/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php b/app/Models/Builders/CheckoutAcceptanceQueryBuilder.phpnew file mode 100644index 0000000000..ac36d7d9ee--- /dev/null+++ b/app/Models/Builders/CheckoutAcceptanceQueryBuilder.php@@ -0,0 +1,24 @@+<?php++namespace App\Models\Builders;++use App\Models\User;+use Illuminate\Database\Eloquent\Builder;++class CheckoutAcceptanceQueryBuilder extends Builder+{+ public function forUser(User $user): static+ {+ return $this->where('assigned_to_id', $user->id);+ }++ public function pending(): static+ {+ return $this->whereNull('accepted_at')->whereNull('declined_at');+ }++ public function declined(): static+ {+ return $this->whereNull('accepted_at')->whereNotNull('declined_at');+ }+}diff --git a/app/Models/Builders/CheckoutRequestQueryBuilder.php b/app/Models/Builders/CheckoutRequestQueryBuilder.phpnew file mode 100644index 0000000000..6bb4af47c8--- /dev/null+++ b/app/Models/Builders/CheckoutRequestQueryBuilder.php@@ -0,0 +1,29 @@+<?php++namespace App\Models\Builders;++use App\Enums\CheckoutRequestState;+use Illuminate\Database\Eloquent\Builder;++class CheckoutRequestQueryBuilder extends Builder+{+ public function open(): static+ {+ return $this->where('state', CheckoutRequestState::Pending->value);+ }++ public function pending(): static+ {+ return $this->where('state', CheckoutRequestState::Pending->value);+ }++ public function fulfilled(): static+ {+ return $this->where('state', CheckoutRequestState::Fulfilled->value);+ }++ public function canceled(): static+ {+ return $this->where('state', CheckoutRequestState::Canceled->value);+ }+}diff --git a/app/Models/Builders/CompanyQueryBuilder.php b/app/Models/Builders/CompanyQueryBuilder.phpnew file mode 100644index 0000000000..9b492cfcf9--- /dev/null+++ b/app/Models/Builders/CompanyQueryBuilder.php@@ -0,0 +1,25 @@+<?php++namespace App\Models\Builders;++use Illuminate\Database\Eloquent\Builder;++class CompanyQueryBuilder extends Builder+{+ public function orderParent(string $order): static+ {+ return $this+ ->leftJoin('companies as parent_co', 'companies.parent_id', '=', 'parent_co.id')+ ->addSelect('companies.*')+ ->orderBy('parent_co.name', $order);+ }++ public function orderByCreatedBy(string $order): static+ {+ return $this+ ->leftJoin('users as admin_sort', 'companies.created_by', '=', 'admin_sort.id')+ ->addSelect('companies.*')+ ->orderBy('admin_sort.first_name', $order)+ ->orderBy('admin_sort.last_name', $order);+ }+}diff --git a/app/Models/Builders/ComponentAssignmentQueryBuilder.php b/app/Models/Builders/ComponentAssignmentQueryBuilder.phpnew file mode 100644index 0000000000..68925d2142--- /dev/null+++ b/app/Models/Builders/ComponentAssignmentQueryBuilder.php@@ -0,0 +1,25 @@+<?php++namespace App\Models\Builders;++use Illuminate\Database\Eloquent\Builder;++class ComponentAssignmentQueryBuilder extends Builder+{+ public function orderByCreatedByName(string $order): static+ {+ return $this+ ->leftJoin('users as checkout_users_sort', 'components_assets.created_by', '=', 'checkout_users_sort.id')+ ->addSelect('components_assets.*')+ ->orderBy('checkout_users_sort.first_name', $order)+ ->orderBy('checkout_users_sort.last_name', $order);+ }++ public function orderByComponentName(string $order): static+ {+ return $this+ ->leftJoin('components as component_sort', 'components_assets.id', '=', 'component_sort.id')+ ->addSelect('components_assets.*')+ ->orderBy('component_sort.name', $order);+ }+}diff --git a/app/Models/Builders/LicenseQueryBuilder.php b/app/Models/Builders/LicenseQueryBuilder.phpnew file mode 100644index 0000000000..ded2e755ab--- /dev/null+++ b/app/Models/Builders/LicenseQueryBuilder.php@@ -0,0 +1,126 @@+<?php++namespace App\Models\Builders;++use Carbon\Carbon;+use Illuminate\Database\Eloquent\Builder;++class LicenseQueryBuilder extends Builder+{+ public function requestable(): static+ {+ return $this->where('licenses.requestable', '1');+ }++ public function activeLicenses(): static+ {+ return $this->whereNull('licenses.deleted_at')+ // The termination date is null or within range+ ->where(function ($query) {+ $query->whereNull('termination_date')+ ->orWhereDate('termination_date', '>', [Carbon::now()]);+ })+ ->where(function ($query) {+ $query->whereNull('expiration_date')+ ->orWhereDate('expiration_date', '>', [Carbon::now()]);+ });+ }++ public function expiredLicenses(): static+ {+ return $this->whereDate('termination_date', '<=', Carbon::now())+ ->orWhere(function ($query) {+ $query->whereDate('expiration_date', '<=', Carbon::now());+ })+ ->whereNull('licenses.deleted_at');+ }++ /**+ * This checks if:+ *+ * 1) The license has not been deleted+ * 2) The expiration date is between now and the number of days specified+ * 3) There is an expiration date set and the termination date has not passed+ * 4) The license termination date is null or has not passed+ *+ * @see SendExpiringLicenseNotifications+ */+ public function expiringLicenses(int $days = 60, bool $includeExpired = false): static+ {+ return $this+ // The termination date is null or within range+ ->where(function ($query) use ($days) {+ $query->whereNull('termination_date')+ ->orWhereBetween('termination_date', [Carbon::now(), Carbon::now()->addDays($days)]);+ })+ ->where(function ($query) use ($days, $includeExpired) {+ $query->whereNotNull('expiration_date')+ // Handle expiring licenses without termination dates+ ->where(function ($query) use ($days, $includeExpired) {+ $query->whereNull('termination_date')+ ->whereBetween('expiration_date', [Carbon::now(), Carbon::now()->addDays($days)])+ // include expired licenses if requested+ ->when($includeExpired, function ($query) {+ $query->orwhereDate('expiration_date', '<=', Carbon::now());+ });+ })+ // Handle expiring licenses with termination dates in the future+ ->orWhere(function ($query) use ($days) {+ $query->whereBetween('termination_date', [Carbon::now(), Carbon::now()->addDays($days)]);+ });+ });+ }++ public function orderManufacturer(string $order): static+ {+ return $this+ ->leftJoin('manufacturers', 'licenses.manufacturer_id', '=', 'manufacturers.id')+ ->addSelect('licenses.*')+ ->orderBy('manufacturers.name', $order);+ }++ public function orderSupplier(string $order): static+ {+ return $this+ ->leftJoin('suppliers', 'licenses.supplier_id', '=', 'suppliers.id')+ ->addSelect('licenses.*')+ ->orderBy('suppliers.name', $order);+ }++ public function orderCompany(string $order): static+ {+ return $this+ ->leftJoin('companies as companies', 'licenses.company_id', '=', 'companies.id')+ ->addSelect('licenses.*')+ ->orderBy('companies.name', $order);+ }++ public function orderByCreatedBy(string $order): static+ {+ return $this+ ->leftJoin('users as admin_sort', 'licenses.created_by', '=', 'admin_sort.id')+ ->addSelect('licenses.*')+ ->orderBy('admin_sort.first_name', $order)+ ->orderBy('admin_sort.last_name', $order);+ }++ /**+ * Mirrors License::percentRemaining(): available_seats / total_seats+ * * 100. free_seats_count is added by withCount() in the API index()+ * as the count of unassigned seats. seats is a real column on+ * licenses. Guards against division by zero for licenses with no+ * seats.+ *+ * PostgreSQL note: references a SELECT-list alias inside a+ * compound ORDER BY expression, which PostgreSQL rejects per SQL+ * standard. Snipe-IT officially supports MySQL/MariaDB and tests+ * on SQLite (both allow this). Moving to PostgreSQL would require+ * inlining the subquery or wrapping the query in an outer SELECT.+ */+ public function orderPercentRemaining(string $order): static+ {+ $order = strtolower($order) === 'asc' ? 'asc' : 'desc';++ return $this->orderByRaw('CASE WHEN licenses.seats = 0 THEN 0 ELSE (free_seats_count * 100.0 / licenses.seats) END '.$order);+ }+}diff --git a/app/Models/Builders/LicenseSeatQueryBuilder.php b/app/Models/Builders/LicenseSeatQueryBuilder.phpnew file mode 100644index 0000000000..c236c11828--- /dev/null+++ b/app/Models/Builders/LicenseSeatQueryBuilder.php@@ -0,0 +1,34 @@+<?php++namespace App\Models\Builders;++use Illuminate\Database\Eloquent\Builder;++class LicenseSeatQueryBuilder extends Builder+{+ public function orderDepartments(string $order): static+ {+ return $this+ ->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id')+ ->leftJoin('departments as license_user_dept', 'license_user_dept.id', '=', 'license_seat_users.department_id')+ ->whereNotNull('license_seats.assigned_to')+ ->orderBy('license_user_dept.name', $order);+ }++ public function orderCompany(string $order): static+ {+ return $this+ ->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id')+ ->leftJoin('companies as license_user_company', 'license_user_company.id', '=', 'license_seat_users.company_id')+ ->whereNotNull('license_seats.assigned_to')+ ->orderBy('license_user_company.name', $order);+ }++ public function byAssigned(): static+ {+ return $this->where(function ($query) {+ $query->whereNotNull('assigned_to')+ ->orWhereNotNull('asset_id');+ });+ }+}diff --git a/app/Models/Builders/UserQueryBuilder.php b/app/Models/Builders/UserQueryBuilder.phpnew file mode 100644index 0000000000..96a6dbb713--- /dev/null+++ b/app/Models/Builders/UserQueryBuilder.php@@ -0,0 +1,212 @@+<?php++namespace App\Models\Builders;++use App\Models\User;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Support\Facades\DB;++class UserQueryBuilder extends Builder+{+ public function getNotDeleted(): static+ {+ return $this->whereNull('deleted_at');+ }++ public function matchEmailOrUsername(string $user_username, string $user_email): static+ {+ return $this->where('email', '=', $user_email)+ ->orWhere('username', '=', $user_username)+ ->orWhere('username', '=', $user_email);+ }++ public function simpleNameSearch(string $search): static+ {+ return $this->where('first_name', 'LIKE', '%'.$search.'%')+ ->orWhere('last_name', 'LIKE', '%'.$search.'%')+ ->orWhere('display_name', 'LIKE', '%'.$search.'%')+ ->orWhereMultipleColumns(+ [+ 'users.first_name',+ 'users.last_name',+ ], $search+ );+ }++ public function byGroup(int $id): static+ {+ return $this->whereHas('groups', function ($query) use ($id) {+ $query->where('permission_groups.id', '=', $id);+ });+ }++ public function onlySuperAdmins(): static+ {+ return $this->where('users.permissions', 'LIKE', '%"superuser":"1"%')+ ->orWhere('users.permissions', 'LIKE', '%"superuser":1%')+ ->orWhereHas('groups', function ($query) {+ $query->where('permission_groups.permissions', 'LIKE', '%"superuser":"1"%')+ ->orWhere('permission_groups.permissions', 'LIKE', '%"superuser":1%');+ });+ }++ public function onlyAdminsAndSuperAdmins(): static+ {+ return $this->where('users.permissions', 'LIKE', '%"superuser":"1"%')+ ->orWhere('users.permissions', 'LIKE', '%"superuser":1%')+ ->orWhere('users.permissions', 'LIKE', '%"admin":1%')+ ->orWhere('users.permissions', 'LIKE', '%"admin":"1"%')+ ->orWhereHas('groups', function ($query) {+ $query->where('permission_groups.permissions', 'LIKE', '%"superuser":"1"%')+ ->orWhere('permission_groups.permissions', 'LIKE', '%"superuser":1%')+ ->orWhere('permission_groups.permissions', 'LIKE', '%"admin":1%')+ ->orWhere('permission_groups.permissions', 'LIKE', '%"admin":"1"%');+ });+ }++ public function orderManager(string $order): static+ {+ // Left join here, or it will only return results with parents+ return $this+ ->leftJoin('users as users_manager', 'users.manager_id', '=', 'users_manager.id')+ ->orderBy('users_manager.first_name', $order)+ ->orderBy('users_manager.last_name', $order);+ }++ public function orderLocation(string $order): static+ {+ return $this+ ->leftJoin('locations as locations_users', 'users.location_id', '=', 'locations_users.id')+ ->orderBy('locations_users.name', $order);+ }++ public function orderDepartment(string $order): static+ {+ return $this+ ->leftJoin('departments as departments_users', 'users.department_id', '=', 'departments_users.id')+ ->orderBy('departments_users.name', $order);+ }++ public function orderByCreatedBy(string $order): static+ {+ // Left join here, or it will only return results with parents+ return $this+ ->leftJoin('users as admin_user', 'users.created_by', '=', 'admin_user.id')+ ->orderBy('admin_user.first_name', $order)+ ->orderBy('admin_user.last_name', $order);+ }++ public function orderCompany(string $order): static+ {+ // The MIN(...) aggregate has to go through DB::raw, which+ // bypasses Laravel's grammar, so the `companies` table+ // reference inside the raw string won't get DB_PREFIX applied+ // automatically. Same pattern as Api\AssetsController::index's+ // natural-sort branch.+ $prefix = DB::getTablePrefix();+ $sub = DB::table('company_user')+ ->join('companies', 'companies.id', '=', 'company_user.company_id')+ ->select('company_user.user_id', DB::raw('MIN('.$prefix.'companies.name) as min_company_name'))+ ->groupBy('company_user.user_id');++ return $this+ ->leftJoinSub($sub, 'companies_sort', 'companies_sort.user_id', '=', 'users.id')+ ->orderBy('companies_sort.min_company_name', $order);+ }++ public function userLocation(int $location, string $search): static+ {+ return $this->where('location_id', '=', $location)+ ->where('users.first_name', 'LIKE', '%'.$search.'%')+ ->orWhere('users.email', 'LIKE', '%'.$search.'%')+ ->orWhere('users.last_name', 'LIKE', '%'.$search.'%')+ ->orWhere('users.permissions', 'LIKE', '%'.$search.'%')+ ->orWhere('users.country', 'LIKE', '%'.$search.'%')+ ->orWhere('users.phone', 'LIKE', '%'.$search.'%')+ ->orWhere('users.jobtitle', 'LIKE', '%'.$search.'%')+ ->orWhere('users.employee_num', 'LIKE', '%'.$search.'%')+ ->orWhere('users.username', 'LIKE', '%'.$search.'%')+ ->orWhere('users.display_name', 'LIKE', '%'.$search.'%')+ ->orWhereRaw('CONCAT(users.first_name," ",users.last_name) LIKE ?', [$search.'%']);+ }++ public function withInventoryRelations(+ int $id,+ bool $withAssets = true,+ bool $withLicenses = true,+ bool $withAccessories = true,+ bool $withConsumables = true,+ bool $withComponents = true,+ ): static {+ $with = [];++ if ($withAssets) {+ $with = array_merge($with, [+ 'assets.log' => fn ($query) => $query->withTrashed()+ ->where('target_type', User::class)+ ->where('target_id', $id)+ ->where('action_type', 'accepted'),+ 'assets.defaultLoc',+ 'assets.location',+ 'assets.model.category',+ 'assets.assignedAssets.log' => fn ($query) => $query->withTrashed()+ ->where('target_type', User::class)+ ->where('target_id', $id)+ ->where('action_type', 'accepted'),+ 'assets.assignedAssets.assignedTo',+ 'assets.assignedAssets.defaultLoc',+ 'assets.assignedAssets.location',+ 'assets.assignedAssets.model.category',+ ]);++ if ($withComponents) {+ $with[] = 'assets.components.category';+ }++ if ($withLicenses) {+ $with = array_merge($with, [+ 'assets.licenses',+ 'assets.licenses.category',+ ]);+ }++ if ($withAccessories) {+ $with = array_merge($with, [+ 'assets.assignedAccessories',+ 'assets.assignedAccessories.accessory.category',+ ]);+ }+ }++ if ($withLicenses) {+ $with = array_merge($with, [+ 'directLicenses.category',+ 'licenses.category',+ ]);+ }++ if ($withAccessories) {+ $with = array_merge($with, [+ 'accessories.log' => fn ($query) => $query->withTrashed()+ ->where('target_type', User::class)+ ->where('target_id', $id)+ ->where('action_type', 'accepted'),+ 'accessories.category',+ 'accessories.manufacturer',+ ]);+ }++ if ($withConsumables) {+ $with = array_merge($with, [+ 'consumables.log' => fn ($query) => $query->withTrashed()+ ->where('target_type', User::class)+ ->where('target_id', $id)+ ->where('action_type', 'accepted'),+ 'consumables.category',+ 'consumables.manufacturer',+ ]);+ }++ return $this->where('id', $id)->with($with)->withTrashed();+ }+}diff --git a/app/Models/CheckoutAcceptance.php b/app/Models/CheckoutAcceptance.phpindex ba278bba3c..334f1437eb 100644--- a/app/Models/CheckoutAcceptance.php+++ b/app/Models/CheckoutAcceptance.php@@ -3,6 +3,7 @@namespace App\Models;use App\Helpers\Helper;+use App\Models\Builders\CheckoutAcceptanceQueryBuilder;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -191,29 +192,9 @@ class CheckoutAcceptance extends Modelreturn true;}- /**- * Filter checkout acceptences by the user- *- * @return Builder- */- public function scopeForUser(Builder $query, User $user)- {- return $query->where('assigned_to_id', $user->id);- }-- /**- * Filter to only get pending acceptances- *- * @return Builder- */- public function scopePending(Builder $query)- {- return $query->whereNull('accepted_at')->whereNull('declined_at');- }-- public function scopeDeclined(Builder $query)+ public function newEloquentBuilder($query): CheckoutAcceptanceQueryBuilder{- return $query->whereNull('accepted_at')->whereNotNull('declined_at');+ return new CheckoutAcceptanceQueryBuilder($query);}/**diff --git a/app/Models/CheckoutRequest.php b/app/Models/CheckoutRequest.phpindex 08f91536f8..742eb0e0cc 100644--- a/app/Models/CheckoutRequest.php+++ b/app/Models/CheckoutRequest.php@@ -4,6 +4,7 @@ namespace App\Models;use App\Enums\CheckoutRequestState;use App\Exceptions\InvalidCheckoutRequestTransition;+use App\Models\Builders\CheckoutRequestQueryBuilder;use App\Models\Traits\HasCalendarEvents;use App\Models\Traits\Searchable;use Illuminate\Database\Eloquent\Builder;@@ -273,7 +274,7 @@ class CheckoutRequest extends Model{$item = $this->itemRequested();- if (!$item) {+ if (! $item) {return '';}@@ -315,24 +316,9 @@ class CheckoutRequest extends Model* 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+ public function newEloquentBuilder($query): CheckoutRequestQueryBuilder{- return $query->where('state', CheckoutRequestState::Canceled->value);+ return new CheckoutRequestQueryBuilder($query);}public function isReservation(): booldiff --git a/app/Models/Company.php b/app/Models/Company.phpindex 95bb295490..f995f5ec21 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -4,6 +4,7 @@ namespace App\Models;use App\Enums\FileStorage;use App\Http\Traits\UniqueUndeletedTrait;+use App\Models\Builders\CompanyQueryBuilder;use App\Models\Traits\CompanyableTrait;use App\Models\Traits\HasUploads;use App\Models\Traits\Loggable;@@ -552,22 +553,6 @@ final class Company extends SnipeModelreturn $this->hasMany(self::class, 'parent_id')->withoutGlobalScopes([CompanyableScope::class]);}- /**- * Sort the company list by the parent company's name. Left join so that- * top-level companies (parent_id IS NULL) still appear in the results.- *- * Use addSelect (not select) so prior withCount subqueries on the query- * survive — select() replaces the whole columns list and would strip the- * eager *_count columns, forcing isDeletable() and the transformer into a- * 7-query-per-row N+1.- */- public function scopeOrderParent($query, $order)- {- return $query->leftJoin('companies as parent_co', 'companies.parent_id', '=', 'parent_co.id')- ->addSelect('companies.*')- ->orderBy('parent_co.name', $order);- }-public function assets(){return $this->hasMany(Asset::class, 'company_id');@@ -837,11 +822,8 @@ final class Company extends SnipeModel* Use addSelect (not select) so prior withCount subqueries on the query* survive — see scopeOrderParent() for the same rationale.*/- public function scopeOrderByCreatedBy($query, $order)+ public function newEloquentBuilder($query): CompanyQueryBuilder{- return $query->leftJoin('users as admin_sort', 'companies.created_by', '=', 'admin_sort.id')- ->addSelect('companies.*')- ->orderBy('admin_sort.first_name', $order)- ->orderBy('admin_sort.last_name', $order);+ return new CompanyQueryBuilder($query);}}diff --git a/app/Models/ComponentAssignment.php b/app/Models/ComponentAssignment.phpindex 8233dc85a6..6d2eea81be 100644--- a/app/Models/ComponentAssignment.php+++ b/app/Models/ComponentAssignment.php@@ -2,6 +2,7 @@namespace App\Models;+use App\Models\Builders\ComponentAssignmentQueryBuilder;use App\Models\Traits\Searchable;use App\Presenters\ComponentPresenter;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -68,13 +69,8 @@ class ComponentAssignment extends Modelreturn $this->belongsTo(User::class, 'created_by')->withTrashed();}- public function scopeOrderByCreatedByName($query, $order)+ public function newEloquentBuilder($query): ComponentAssignmentQueryBuilder{- return $query->leftJoin('users as checkout_users_sort', 'components_assets.created_by', '=', 'checkout_users_sort.id')->addSelect('components_assets.*')->orderBy('checkout_users_sort.first_name', $order)->orderBy('checkout_users_sort.last_name', $order);- }-- public function scopeOrderByComponentName($query, $order)- {- return $query->leftJoin('components as component_sort', 'components_assets.id', '=', 'component_sort.id')->addSelect('components_assets.*')->orderBy('component_sort.name', $order);+ return new ComponentAssignmentQueryBuilder($query);}}diff --git a/app/Models/License.php b/app/Models/License.phpindex 4b35bf59f9..d2b5140971 100755--- a/app/Models/License.php+++ b/app/Models/License.php@@ -2,8 +2,8 @@namespace App\Models;-use App\Console\Commands\SendExpiringLicenseNotifications;use App\Helpers\Helper;+use App\Models\Builders\LicenseQueryBuilder;use App\Models\Traits\CompanyableTrait;use App\Models\Traits\HasCalendarEvents;use App\Models\Traits\HasUploads;@@ -18,7 +18,6 @@ use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\Relation;use Illuminate\Database\Eloquent\SoftDeletes;-use Illuminate\Database\Query\Builder;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Gate;use Illuminate\Support\Facades\Session;@@ -232,10 +231,6 @@ class License extends Depreciable* applies without any additional wrapping here (matches the* Accessory / Consumable / Component scope shape).*/- public function scopeRequestable($query)- {- return $query->where('licenses.requestable', '1');- }/*** @return Attribute<string|null, never>@@ -911,6 +906,9 @@ class License extends Depreciable* set for the duration of the call. Used by the API index for callers* who lack the `viewKeys` permission, so search / filter parameters* cannot be used as an existence oracle against license product keys.+ *+ * Stays on the model (not the builder) because it needs internal+ * access to the model's protected $searchableAttributes property.*/public function scopeTextSearchWithoutSerial($query, $search){@@ -928,150 +926,8 @@ class License extends Depreciable}}- public function scopeActiveLicenses($query)+ public function newEloquentBuilder($query): LicenseQueryBuilder{-- return $query->whereNull('licenses.deleted_at')-- // The termination date is null or within range- ->where(function ($query) {- $query->whereNull('termination_date')- ->orWhereDate('termination_date', '>', [Carbon::now()]);- })- ->where(function ($query) {- $query->whereNull('expiration_date')- ->orWhereDate('expiration_date', '>', [Carbon::now()]);- });- }-- /**- * Expiried/terminated licenses scope- *- * @author A. Gianotto <[email protected]>- *- * @since [v1.0]- *- * @return Relation- *- * @see SendExpiringLicenseNotifications- */- public function scopeExpiredLicenses($query)- {- return $query->whereDate('termination_date', '<=', Carbon::now())// The termination date is null or within range- ->orWhere(function ($query) {- $query->whereDate('expiration_date', '<=', Carbon::now());- })- ->whereNull('licenses.deleted_at');- }-- /**- * Expiring/terminating licenses scope- *- * This checks if:- *- * 1) The license has not been deleted- * 2) The expiration date is between now and the number of days specified- * 3) There is an expiration date set and the termination date has not passed- * 4) The license termination date is null or has not passed- *- * @author A. Gianotto <[email protected]>- *- * @since [v1.0]- *- * @return Relation- *- * @see SendExpiringLicenseNotifications- */- public function scopeExpiringLicenses($query, $days = 60, $includeExpired = false)- {- return $query// The termination date is null or within range- ->where(function ($query) use ($days) {- $query->whereNull('termination_date')- ->orWhereBetween('termination_date', [Carbon::now(), Carbon::now()->addDays($days)]);- })- ->where(function ($query) use ($days, $includeExpired) {- $query->whereNotNull('expiration_date')- // Handle expiring licenses without termination dates- ->where(function ($query) use ($days, $includeExpired) {- $query->whereNull('termination_date')- ->whereBetween('expiration_date', [Carbon::now(), Carbon::now()->addDays($days)])- // include expired licenses if requested- ->when($includeExpired, function ($query) {- $query->orwhereDate('expiration_date', '<=', Carbon::now());- });- })- // Handle expiring licenses with termination dates in the future- ->orWhere(function ($query) use ($days) {- $query->whereBetween('termination_date', [Carbon::now(), Carbon::now()->addDays($days)]);- });- });- }-- /**- * Query builder scope to order on manufacturer- *- * @param Builder $query Query builder instance- * @param string $order Order- * @return Builder Modified query builder- */- public function scopeOrderManufacturer($query, $order)- {- return $query->leftJoin('manufacturers', 'licenses.manufacturer_id', '=', 'manufacturers.id')->addSelect('licenses.*')- ->orderBy('manufacturers.name', $order);- }-- /**- * Query builder scope to order on supplier- *- * @param Builder $query Query builder instance- * @param string $order Order- * @return Builder Modified query builder- */- public function scopeOrderSupplier($query, $order)- {- return $query->leftJoin('suppliers', 'licenses.supplier_id', '=', 'suppliers.id')->addSelect('licenses.*')- ->orderBy('suppliers.name', $order);- }-- /**- * Query builder scope to order on company- *- * @param Builder $query Query builder instance- * @param text $order Order- * @return Builder Modified query builder- */- public function scopeOrderCompany($query, $order)- {- return $query->leftJoin('companies as companies', 'licenses.company_id', '=', 'companies.id')->addSelect('licenses.*')- ->orderBy('companies.name', $order);- }-- /**- * Query builder scope to order on the user that created it- */- public function scopeOrderByCreatedBy($query, $order)- {- return $query->leftJoin('users as admin_sort', 'licenses.created_by', '=', 'admin_sort.id')->addSelect('licenses.*')->orderBy('admin_sort.first_name', $order)->orderBy('admin_sort.last_name', $order);- }-- /**- * Query builder scope to sort by the calculated `% remaining` column.- *- * Mirrors License::percentRemaining(): available_seats / total_seats * 100.- * free_seats_count is added by withCount() in the API index() as the- * count of unassigned seats; seats is a real column on licenses.- * Guards against division by zero for licenses with no seats.- *- * PostgreSQL note: references a SELECT-list alias inside a compound- * ORDER BY expression, which PostgreSQL rejects per SQL standard.- * Snipe-IT officially supports MySQL/MariaDB and tests on SQLite- * (both allow this); moving to PostgreSQL would require inlining- * the subquery or wrapping the query in an outer SELECT.- */- public function scopeOrderPercentRemaining($query, $order)- {- $order = strtolower($order) === 'asc' ? 'asc' : 'desc';-- return $query->orderByRaw('CASE WHEN licenses.seats = 0 THEN 0 ELSE (free_seats_count * 100.0 / licenses.seats) END '.$order);+ return new LicenseQueryBuilder($query);}}diff --git a/app/Models/LicenseSeat.php b/app/Models/LicenseSeat.phpindex 9ac21448d2..46e031cdcf 100755--- a/app/Models/LicenseSeat.php+++ b/app/Models/LicenseSeat.php@@ -2,6 +2,7 @@namespace App\Models;+use App\Models\Builders\LicenseSeatQueryBuilder;use App\Models\Traits\Acceptable;use App\Models\Traits\CompanyableChildTrait;use App\Models\Traits\Loggable;@@ -12,7 +13,6 @@ use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Relations\Relation;use Illuminate\Database\Eloquent\SoftDeletes;-use Illuminate\Database\Query\Builder;/*** @mixin IdeHelperLicenseSeat@@ -208,39 +208,8 @@ class LicenseSeat extends SnipeModel implements ICompanyableChildreturn $this->hasMany(Actionlog::class, 'item_id')->where('item_type', self::class)->orderBy('created_at', 'desc')->withTrashed();}- /**- * Query builder scope to order on department- *- * @param Builder $query Query builder instance- * @param text $order Order- * @return Builder Modified query builder- */- public function scopeOrderDepartments($query, $order)+ public function newEloquentBuilder($query): LicenseSeatQueryBuilder{- return $query->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id')- ->leftJoin('departments as license_user_dept', 'license_user_dept.id', '=', 'license_seat_users.department_id')- ->whereNotNull('license_seats.assigned_to')- ->orderBy('license_user_dept.name', $order);- }-- public function scopeOrderCompany($query, $order)- {-- return $query->leftJoin('users as license_seat_users', 'license_seats.assigned_to', '=', 'license_seat_users.id')- ->leftJoin('companies as license_user_company', 'license_user_company.id', '=', 'license_seat_users.company_id')- ->whereNotNull('license_seats.assigned_to')- ->orderBy('license_user_company.name', $order);- }-- public function scopeByAssigned($query)- {-- return $query->where(- function ($query) {- $query->whereNotNull('assigned_to')- ->orWhereNotNull('asset_id');- }- );-+ return new LicenseSeatQueryBuilder($query);}}diff --git a/app/Models/User.php b/app/Models/User.phpindex 07b447bece..6ba8208052 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -4,6 +4,7 @@ namespace App\Models;use App\Enums\FileStorage;use App\Http\Traits\UniqueUndeletedTrait;+use App\Models\Builders\UserQueryBuilder;use App\Models\Traits\CompanyableTrait;use App\Models\Traits\HasCalendarEvents;use App\Models\Traits\HasImageUpload;@@ -1065,7 +1066,7 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo$editorChildren = empty($editorDirect) ? [] : DB::table('companies')->whereIn('parent_id', $editorDirect)->pluck('id')- ->map(fn($id) => (int) $id)+ ->map(fn ($id) => (int) $id)->all();$editorVisible = array_values(array_unique(array_merge($editorDirect, $editorChildren)));@@ -1583,10 +1584,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $query* @return \Illuminate\Database\Query\Builder*/- public function scopeGetNotDeleted($query)- {- return $query->whereNull('deleted_at');- }/*** Query builder scope to return users by email or username@@ -1600,12 +1597,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $user_email* @return \Illuminate\Database\Query\Builder*/- public function scopeMatchEmailOrUsername($query, $user_username, $user_email)- {- return $query->where('email', '=', $user_email)- ->orWhere('username', '=', $user_username)- ->orWhere('username', '=', $user_email);- }/*** Generate email from full name@@ -1814,18 +1805,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param array $terms The search terms* @return \Illuminate\Database\Query\Builder*/- public function scopeSimpleNameSearch($query, $search)- {- return $query->where('first_name', 'LIKE', '%'.$search.'%')- ->orWhere('last_name', 'LIKE', '%'.$search.'%')- ->orWhere('display_name', 'LIKE', '%'.$search.'%')- ->orWhereMultipleColumns(- [- 'users.first_name',- 'users.last_name',- ], $search- );- }/*** Run additional, advanced searches.@@ -1855,56 +1834,18 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param int $id* @return \Illuminate\Database\Query\Builder*/- public function scopeByGroup($query, $id)- {- return $query->whereHas(- 'groups', function ($query) use ($id) {- $query->where('permission_groups.id', '=', $id);- }- );- }/*** Return only admins and superusers** @param \Illuminate\Database\Query\Builder $query Query builder instance*/- public function scopeOnlySuperAdmins($query)- {-- return $query->where('users.permissions', 'LIKE', '%"superuser":"1"%')- ->orWhere('users.permissions', 'LIKE', '%"superuser":1%')- ->orWhereHas(- 'groups', function ($query) {- $query->where('permission_groups.permissions', 'LIKE', '%"superuser":"1"%')- ->orWhere('permission_groups.permissions', 'LIKE', '%"superuser":1%');- }- );-- }/*** Return only admins and superusers** @param \Illuminate\Database\Query\Builder $query Query builder instance*/- public function scopeOnlyAdminsAndSuperAdmins($query)- {-- return $query->where('users.permissions', 'LIKE', '%"superuser":"1"%')- ->orWhere('users.permissions', 'LIKE', '%"superuser":1%')- ->orWhere('users.permissions', 'LIKE', '%"admin":1%')- ->orWhere('users.permissions', 'LIKE', '%"admin":"1"%')- ->orWhereHas(- 'groups', function ($query) {- $query->where('permission_groups.permissions', 'LIKE', '%"superuser":"1"%')- ->orWhere('permission_groups.permissions', 'LIKE', '%"superuser":1%')- ->orWhere('permission_groups.permissions', 'LIKE', '%"admin":1%')- ->orWhere('permission_groups.permissions', 'LIKE', '%"admin":"1"%');- }- );-- }/*** Query builder scope to order on manager@@ -1913,11 +1854,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $order Order* @return \Illuminate\Database\Query\Builder Modified query builder*/- public function scopeOrderManager($query, $order)- {- // Left join here, or it will only return results with parents- return $query->leftJoin('users as users_manager', 'users.manager_id', '=', 'users_manager.id')->orderBy('users_manager.first_name', $order)->orderBy('users_manager.last_name', $order);- }/*** Query builder scope to order on company@@ -1926,10 +1862,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $order Order* @return \Illuminate\Database\Query\Builder Modified query builder*/- public function scopeOrderLocation($query, $order)- {- return $query->leftJoin('locations as locations_users', 'users.location_id', '=', 'locations_users.id')->orderBy('locations_users.name', $order);- }/*** Query builder scope to order on department@@ -1938,10 +1870,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $order Order* @return \Illuminate\Database\Query\Builder Modified query builder*/- public function scopeOrderDepartment($query, $order)- {- return $query->leftJoin('departments as departments_users', 'users.department_id', '=', 'departments_users.id')->orderBy('departments_users.name', $order);- }/*** Query builder scope to order on admin user@@ -1950,13 +1878,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param string $order Order* @return \Illuminate\Database\Query\Builder Modified query builder*/- public function scopeOrderByCreatedBy($query, $order)- {- // Left join here, or it will only return results with parents- return $query->leftJoin('users as admin_user', 'users.created_by', '=', 'admin_user.id')- ->orderBy('admin_user.first_name', $order)- ->orderBy('admin_user.last_name', $order);- }/*** Query builder scope to order on company@@ -1965,22 +1886,6 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCo* @param text $order Order* @return Illuminate\Database\Query\Builder Modified query builder*/- public function scopeOrderCompany($query, $order)- {- // The MIN(...) aggregate has to go through DB::raw, which bypasses- // Laravel's grammar — so the `companies` table reference inside the- // raw string won't get DB_PREFIX applied automatically. Same pattern- // as Api\AssetsController::index's natural-sort branch.- $prefix = DB::getTablePrefix();- $sub = DB::table('company_user')- ->join('companies', 'companies.id', '=', 'company_user.company_id')- ->select('company_user.user_id', DB::raw('MIN('.$prefix.'companies.name) as min_company_name'))- ->groupBy('company_user.user_id');-- return $query- ->leftJoinSub($sub, 'companies_sort', 'companies_sort.user_id', '=', 'users.id')- ->orderBy('companies_sort.min_company_name', $order);- }/*** Get the preferred locale for the user.@@ -2069,103 +1974,9 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCoreturn $total;}- public function scopeUserLocation($query, $location, $search)- {-- return $query->where('location_id', '=', $location)- ->where('users.first_name', 'LIKE', '%'.$search.'%')- ->orWhere('users.email', 'LIKE', '%'.$search.'%')- ->orWhere('users.last_name', 'LIKE', '%'.$search.'%')- ->orWhere('users.permissions', 'LIKE', '%'.$search.'%')- ->orWhere('users.country', 'LIKE', '%'.$search.'%')- ->orWhere('users.phone', 'LIKE', '%'.$search.'%')- ->orWhere('users.jobtitle', 'LIKE', '%'.$search.'%')- ->orWhere('users.employee_num', 'LIKE', '%'.$search.'%')- ->orWhere('users.username', 'LIKE', '%'.$search.'%')- ->orWhere('users.display_name', 'LIKE', '%'.$search.'%')- ->orWhereRaw('CONCAT(users.first_name," ",users.last_name) LIKE ?', [$search.'%']);-- }-- public function scopeWithInventoryRelations(- $query,- int $id,- bool $withAssets = true,- bool $withLicenses = true,- bool $withAccessories = true,- bool $withConsumables = true,- bool $withComponents = true,- ) {- $with = [];-- if ($withAssets) {- $with = array_merge($with, [- 'assets.log' => fn ($query) => $query->withTrashed()- ->where('target_type', User::class)- ->where('target_id', $id)- ->where('action_type', 'accepted'),- 'assets.defaultLoc',- 'assets.location',- 'assets.model.category',- 'assets.assignedAssets.log' => fn ($query) => $query->withTrashed()- ->where('target_type', User::class)- ->where('target_id', $id)- ->where('action_type', 'accepted'),- 'assets.assignedAssets.assignedTo',- 'assets.assignedAssets.defaultLoc',- 'assets.assignedAssets.location',- 'assets.assignedAssets.model.category',- ]);-- if ($withComponents) {- $with[] = 'assets.components.category';- }-- if ($withLicenses) {- $with = array_merge($with, [- 'assets.licenses',- 'assets.licenses.category',- ]);- }-- if ($withAccessories) {- $with = array_merge($with, [- 'assets.assignedAccessories',- 'assets.assignedAccessories.accessory.category',- ]);- }- }-- if ($withLicenses) {- $with = array_merge($with, [- 'directLicenses.category',- 'licenses.category',- ]);- }-- if ($withAccessories) {- $with = array_merge($with, [- 'accessories.log' => fn ($query) => $query->withTrashed()- ->where('target_type', User::class)- ->where('target_id', $id)- ->where('action_type', 'accepted'),- 'accessories.category',- 'accessories.manufacturer',- ]);- }-- if ($withConsumables) {- $with = array_merge($with, [- 'consumables.log' => fn ($query) => $query->withTrashed()- ->where('target_type', User::class)- ->where('target_id', $id)- ->where('action_type', 'accepted'),- 'consumables.category',- 'consumables.manufacturer',- ]);- }-- return $query->where('id', $id)->with($with)->withTrashed();+ public function newEloquentBuilder($query): UserQueryBuilder+ {+ return new UserQueryBuilder($query);}/**diff --git a/tests/Feature/Api/IndexSortRegressionTest.php b/tests/Feature/Api/IndexSortRegressionTest.phpindex 5541621161..7082777497 100644--- a/tests/Feature/Api/IndexSortRegressionTest.php+++ b/tests/Feature/Api/IndexSortRegressionTest.php@@ -6,6 +6,7 @@ use App\Models\Accessory;use App\Models\Asset;use App\Models\AssetModel;use App\Models\Category;+use App\Models\Company;use App\Models\Component;use App\Models\Consumable;use App\Models\Department;@@ -64,6 +65,8 @@ class IndexSortRegressionTest extends TestCase'consumables by manufacturer' => ['api.consumables.index', 'manufacturer'],'consumables by company' => ['api.consumables.index', 'company'],'consumables by supplier' => ['api.consumables.index', 'supplier'],+ 'companies by created_by' => ['api.companies.index', 'created_by'],+ 'companies by parent' => ['api.companies.index', 'parent'],'departments by created_by' => ['api.departments.index', 'created_by'],'departments by location' => ['api.departments.index', 'location'],'departments by manager' => ['api.departments.index', 'manager'],@@ -115,6 +118,7 @@ class IndexSortRegressionTest extends TestCase'api.categories.index' => Category::factory()->forAssets()->create(),'api.components.index' => Component::factory()->create(),'api.consumables.index' => Consumable::factory()->create(),+ 'api.companies.index' => Company::factory()->create(),'api.departments.index' => Department::factory()->create(),'api.depreciations.index' => Depreciation::factory()->create(),'api.groups.index' => Group::factory()->create(),