Skip to content

A free open source IT asset/license management system

Added filterableFields to models

snipe92d4b5b052d0
diff --git a/_ide_helper_models.php b/_ide_helper_models.php
index eae0503d1d..0ec5a57e76 100644
--- a/_ide_helper_models.php
+++ b/_ide_helper_models.php
@@ -2979,6 +2979,48 @@ namespace App\Models{
class IdeHelperSamlNonce {}
}
+namespace App\Models{
+/**
+ * Named filter-preset for a listing page's advanced-search. Each
+ * record stores a URL query string (filter[.
+ *
+ * ..] + filter_operator)
+ * captured from the advanced-search modal. Loading a saved search
+ * means navigating back to the originating listing route with the
+ * stored query string re-attached. Private to the creator for v1
+ * (no sharing/default yet).
+ *
+ * table_name holds the bs-table idTable (e.g. 'accessoriesListingTable')
+ * so a single table's saved-searches dropdown only lists its own.
+ *
+ * @property int $id
+ * @property int $created_by
+ * @property string $table_name
+ * @property string|null $model
+ * @property string $name
+ * @property string $query_string
+ * @property \Illuminate\Support\Carbon|null $created_at
+ * @property \Illuminate\Support\Carbon|null $updated_at
+ * @property-read \App\Models\User|null $creator
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch forTable(string $tableName)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch newModelQuery()
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch newQuery()
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch ownedByCurrent()
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch query()
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereCreatedAt($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereCreatedBy($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereId($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereModel($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereName($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereQueryString($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereTableName($value)
+ * @method static \Illuminate\Database\Eloquent\Builder<static>|SavedSearch whereUpdatedAt($value)
+ * @mixin \Eloquent
+ */
+ #[\AllowDynamicProperties]
+ class IdeHelperSavedSearch {}
+}
+
namespace App\Models{
/**
* Settings model.
diff --git a/app/Models/Accessory.php b/app/Models/Accessory.php
index 5164fedb85..588dcae428 100755
--- a/app/Models/Accessory.php
+++ b/app/Models/Accessory.php
@@ -70,6 +70,281 @@ class Accessory extends SnipeModel implements Importable
'notes',
];
+ /**
+ * Advanced-search filterable connections.
+ *
+ * Field types:
+ * - fk: FK dropdown, backed by `column` on this
+ * table and `endpoint` for the selectlist.
+ * - date-range: YYYY-MM-DD..YYYY-MM-DD, backed by `field` on
+ * this table (or routed via applyCustomFilter
+ * if the column lives on a related table).
+ * - boolean: Two-checkbox yes/no, backed by `field` on
+ * this table.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => 'category_id',
+ 'endpoint' => 'categories/accessory',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => 'manufacturer_id',
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ // Supplier lives on default_supplier_id, not supplier_id, since
+ // the per-order supplier moved to the Orders table and the parent
+ // column is now the default/template value.
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'default_supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'location',
+ 'type' => 'fk',
+ 'column' => 'location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('general.location'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'requestable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.requestable'),
+ ],
+ [
+ 'field' => 'qty',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.total'),
+ ],
+ [
+ 'field' => 'min_amt',
+ 'type' => 'numeric',
+ 'label' => trans('general.min_amt'),
+ ],
+ // remaining = qty - checkouts_count. Not a column on
+ // accessories. Routed via applyCustomFilter below, same
+ // pattern as purchase_date.
+ [
+ 'field' => 'remaining',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.remaining'),
+ ],
+ // purchase_cost = last OrderItem.price for this accessory.
+ // Routed via applyCustomFilter.
+ [
+ 'field' => 'purchase_cost',
+ 'type' => 'numeric',
+ 'label' => trans('general.last_unit_cost'),
+ ],
+ // checkouts_count = COUNT(active checkouts). Routed via
+ // applyCustomFilter.
+ [
+ 'field' => 'checkouts_count',
+ 'type' => 'numeric',
+ 'label' => trans('general.checked_out'),
+ ],
+ // purchase_date is derived from the Orders relation, not a
+ // column on accessories. Routed via Accessory::applyCustomFilter
+ // rather than the standard filterableDateRanges whitelist path.
+ [
+ 'field' => 'purchase_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.last_purchase_date'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. Routes advanced-search filter
+ * keys that can't be resolved against a column on the accessories
+ * table (because the value is derived from a related table) to
+ * their matching correlated-subquery predicate. Default list
+ * queries never pay the subquery cost. This only runs when the
+ * matching filter key is on the request.
+ *
+ * Handled keys:
+ * - purchase_date (date range, YYYY-MM-DD..YYYY-MM-DD): matches
+ * "the last purchase date" per scopeOrderByLastPurchaseDate.
+ * - remaining (numeric range, gt:X / lt:Y / gt:X,lt:Y): matches
+ * qty - COUNT(active checkouts).
+ * - purchase_cost (same shape as remaining): matches the price
+ * on the latest OrderItem per scopeOrderByLastPurchaseCost.
+ * - checkouts_count (same shape as remaining): matches
+ * COUNT(active checkouts) directly.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey === 'purchase_date') {
+ if (!preg_match('/^(\d{4}-\d{2}-\d{2})?\.\.(\d{4}-\d{2}-\d{2})?$/', trim($filterValue), $m)) {
+ return null;
+ }
+ $start = $m[1] !== '' ? $m[1] : null;
+ $end = $m[2] !== '' ? $m[2] : null;
+ if ($start === null && $end === null) {
+ return null;
+ }
+
+ // Correlated subquery resolving to "the purchase_date of
+ // the Order attached to the latest OrderItem for this
+ // accessory" (mirror of scopeOrderByLastPurchaseDate).
+ $lastDateSub = \App\Models\OrderItem::query()
+ ->join('orders', 'orders.id', '=', 'order_items.order_id')
+ ->whereColumn('order_items.item_id', 'accessories.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('orders.purchase_date');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastDateSub, $start, $end) {
+ if ($start !== null && $end !== null) {
+ $nested->whereBetween($lastDateSub, [$start, $end]);
+ } elseif ($start !== null) {
+ $nested->where($lastDateSub, '>=', $start);
+ } elseif ($end !== null) {
+ $nested->where($lastDateSub, '<=', $end);
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'remaining') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ // Correlated subquery resolving to the active-checkout
+ // count for this accessory. The display column is
+ // `qty - checkouts_count`, so the filter compares against
+ // that same expression.
+ $checkoutCountSub = \App\Models\AccessoryCheckout::query()
+ ->whereColumn('accessory_checkouts.accessory_id', 'accessories.id')
+ ->selectRaw('COUNT(*)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($checkoutCountSub, $gt, $lt) {
+ // "qty - (count)" cannot be built from whereColumn
+ // alone, so whereRaw with the subquery SQL spliced
+ // in. Values are bound as parameters, the comparison
+ // operator is a validated literal from the regex.
+ [$countSql, $countBindings] = [$checkoutCountSub->toSql(), $checkoutCountSub->getBindings()];
+ if ($gt !== null) {
+ $nested->whereRaw(
+ "(accessories.qty - ({$countSql})) > ?",
+ array_merge($countBindings, [$gt])
+ );
+ }
+ if ($lt !== null) {
+ $nested->whereRaw(
+ "(accessories.qty - ({$countSql})) < ?",
+ array_merge($countBindings, [$lt])
+ );
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'purchase_cost') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ // Correlated subquery resolving to the price on the
+ // latest OrderItem for this accessory, mirror of
+ // scopeOrderByLastPurchaseCost.
+ $lastCostSub = \App\Models\OrderItem::query()
+ ->whereColumn('order_items.item_id', 'accessories.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('order_items.price');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastCostSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($lastCostSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($lastCostSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'checkouts_count') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ // Correlated subquery resolving to the active-checkout
+ // count for this accessory. Same shape as the subquery
+ // the `remaining` filter uses, compared against directly
+ // rather than through the qty - count arithmetic.
+ $checkoutCountSub = \App\Models\AccessoryCheckout::query()
+ ->whereColumn('accessory_checkouts.accessory_id', 'accessories.id')
+ ->selectRaw('COUNT(*)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($checkoutCountSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($checkoutCountSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($checkoutCountSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
+ return null;
+ }
+
/**
* The relations and their attributes that should be included when searching the model.
*
@@ -81,7 +356,7 @@ class Accessory extends SnipeModel implements Importable
'location' => ['name'],
'manufacturer' => ['name'],
// Search by the parent's "typical supplier" template. Historical
- // per-order supplier lookups belong on the Orders tab; this join
+ // per-order supplier lookups belong on the Orders tab. This join
// keeps parent-level list-page search predictable.
'defaultSupplier' => ['name'],
// Order numbers moved to a dedicated Orders / OrderItems data
diff --git a/app/Models/Actionlog.php b/app/Models/Actionlog.php
index fe5936f071..7597bc96c9 100755
--- a/app/Models/Actionlog.php
+++ b/app/Models/Actionlog.php
@@ -153,6 +153,116 @@ class Actionlog extends SnipeModel
'accessories.defaultSupplier' => ['name', 'notes'],
];
+ /**
+ * Advanced-search filterable fields for the activity report.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ $typeOptions = array_map(
+ fn(\App\Enums\ActivityItemType $case) => [
+ 'value' => $case->value,
+ 'label' => $case->label(),
+ ],
+ \App\Enums\ActivityItemType::cases()
+ );
+
+ $actionTypeOptions = array_map(
+ fn(\App\Enums\ActionType $case) => [
+ 'value' => $case->value,
+ 'label' => ucwords($case->value),
+ ],
+ \App\Enums\ActionType::cases()
+ );
+
+ return [
+ [
+ 'field' => 'item',
+ 'type' => 'enum',
+ 'options' => $typeOptions,
+ 'label' => trans('general.item_type_label'),
+ ],
+ [
+ 'field' => 'target',
+ 'type' => 'enum',
+ 'options' => $typeOptions,
+ 'label' => trans('general.target_type_label'),
+ ],
+ [
+ 'field' => 'action_type',
+ 'type' => 'enum',
+ 'column' => 'action_type',
+ 'options' => $actionTypeOptions,
+ 'label' => trans('general.action_type_label'),
+ ],
+ [
+ 'field' => 'action_source',
+ 'type' => 'enum',
+ 'column' => 'action_source',
+ 'options' => [
+ ['value' => 'gui', 'label' => 'GUI'],
+ ['value' => 'api', 'label' => 'API'],
+ ['value' => 'cli/unknown', 'label' => 'CLI'],
+ ],
+ 'label' => trans('general.action_source'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'action_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.action_date'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. The `item` and `target` filters
+ * carry ActivityItemType short-name tokens from the modal widgets
+ * (asset, accessory, user, ...). action_logs stores the FQCN,
+ * so resolve each short name to its class string before the
+ * whereIn against item_type / target_type.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey !== 'item' && $filterKey !== 'target') {
+ return null;
+ }
+
+ $tokens = array_values(array_filter(array_map('trim', explode(',', $filterValue)), 'strlen'));
+ if ($tokens === []) {
+ return null;
+ }
+
+ $classes = [];
+ foreach ($tokens as $token) {
+ $case = \App\Enums\ActivityItemType::tryFromAny($token);
+ if ($case !== null) {
+ $classes[] = $case->class();
+ }
+ }
+ if ($classes === []) {
+ return null;
+ }
+
+ $column = $filterKey === 'item' ? 'item_type' : 'target_type';
+ $method = $boolean === 'or' ? 'orWhereIn' : 'whereIn';
+ $query->{$method}('action_logs.' . $column, array_values(array_unique($classes)));
+
+ return $query;
+ }
+
/**
* Override from Builder to automatically add the company
*
diff --git a/app/Models/Asset.php b/app/Models/Asset.php
index 7149d936be..dbd0e4d193 100644
--- a/app/Models/Asset.php
+++ b/app/Models/Asset.php
@@ -103,11 +103,6 @@ class Asset extends Depreciable implements Importable
*/
protected $table = 'assets';
- /**
- * Leaving this commented out, since we need to test further, but this would eager load the model relationship every single
- * time the asset model is loaded.
- */
-
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
@@ -273,6 +268,270 @@ class Asset extends Depreciable implements Importable
'externalSource' => ['primary_mac', 'primary_ip', 'os', 'os_version'],
];
+ /**
+ * Advanced-search filterable fields for the hardware index. First
+ * pass covers the direct-column FKs, booleans, numeric columns,
+ * and date columns admins commonly filter on.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'model',
+ 'type' => 'fk',
+ 'column' => 'model_id',
+ 'endpoint' => 'models',
+ 'label' => trans('admin/hardware/form.model'),
+ ],
+
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'categories/asset',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ [
+ 'field' => 'status',
+ 'type' => 'fk',
+ 'column' => 'status_id',
+ 'endpoint' => 'statuslabels',
+ 'label' => trans('general.status'),
+ ],
+
+ [
+ 'field' => 'status_type',
+ 'type' => 'enum',
+ 'options' => [
+ ['value' => 'deployable', 'label' => trans('admin/statuslabels/table.deployable')],
+ ['value' => 'pending', 'label' => trans('admin/statuslabels/table.pending')],
+ ['value' => 'undeployable', 'label' => trans('admin/statuslabels/table.undeployable')],
+ ['value' => 'archived', 'label' => trans('admin/statuslabels/table.archived')],
+ ],
+ 'label' => trans('admin/statuslabels/table.status_type'),
+ ],
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'location',
+ 'type' => 'fk',
+ 'column' => 'location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('general.location'),
+ ],
+ [
+ 'field' => 'rtd_location',
+ 'type' => 'fk',
+ 'column' => 'rtd_location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('admin/hardware/form.default_location'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ // assigned_to is polymorphic so gets three fields in the advanced search
+ [
+ 'field' => 'assigned_user',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'users',
+ 'label' => trans('admin/hardware/table.assigned_to') . ' - ' . trans('general.user'),
+ ],
+ [
+ 'field' => 'assigned_asset',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'hardware',
+ 'label' => trans('admin/hardware/table.assigned_to') . ' - ' . trans('general.asset'),
+ ],
+ [
+ 'field' => 'assigned_location',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'locations',
+ 'label' => trans('admin/hardware/table.assigned_to') . ' - ' . trans('general.location'),
+ ],
+ [
+ 'field' => 'requestable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.requestable'),
+ ],
+ [
+ 'field' => 'byod',
+ 'type' => 'boolean',
+ 'label' => trans('general.byod'),
+ ],
+ [
+ 'field' => 'purchase_cost',
+ 'type' => 'numeric',
+ 'label' => trans('general.purchase_cost'),
+ ],
+ [
+ 'field' => 'warranty_months',
+ 'type' => 'numeric',
+ 'label' => trans('admin/hardware/form.warranty'),
+ ],
+ [
+ 'field' => 'purchase_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.purchase_date'),
+ ],
+ [
+ 'field' => 'last_checkout',
+ 'type' => 'date-range',
+ 'label' => trans('admin/hardware/table.checkout_date'),
+ ],
+ [
+ 'field' => 'last_checkin',
+ 'type' => 'date-range',
+ 'label' => trans('admin/hardware/table.last_checkin_date'),
+ ],
+ [
+ 'field' => 'last_audit_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.last_audit'),
+ ],
+ [
+ 'field' => 'next_audit_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.next_audit_date'),
+ ],
+ [
+ 'field' => 'asset_eol_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/hardware/form.eol_date'),
+ ],
+ [
+ 'field' => 'expected_checkin',
+ 'type' => 'date-range',
+ 'label' => trans('admin/hardware/form.expected_checkin'),
+ ],
+ // warranty_expires is purchase_date + warranty_months.
+ // Not a stored column, routed via applyCustomFilter.
+ [
+ 'field' => 'warranty_expires',
+ 'type' => 'date-range',
+ 'label' => trans('admin/hardware/form.warranty_expires'),
+ ],
+ // age in years since purchase_date, computed via
+ // TIMESTAMPDIFF. Routed via applyCustomFilter.
+ [
+ 'field' => 'age',
+ 'type' => 'numeric',
+ 'label' => trans('general.age'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ...static::customFieldFilterableWidgets(),
+ ];
+ }
+
+ /**
+ * Dynamic tail of filterableFields built from the custom_fields
+ * table. One widget per field whose fieldset is attached to at
+ * least one AssetModel. The widget type is picked from the
+ * field's `element` column (the UI widget shape):
+ * - date_picker / datetime_picker → date-range (stored as
+ * native date / datetime column, standard whereBetween).
+ * - listbox / radio → enum (single stored value, whereIn
+ * against the field_values).
+ * - checkbox → set (multi-value stored as `implode(', ',
+ * $values)` in AssetsController. Searchable's set-type
+ * path uses CONCAT-wrap + positional LIKE to match each
+ * selected token against the comma-joined storage).
+ * - text / textarea / markdown-textarea → skipped. bs-table
+ * auto-renders a text input for the searchable column, and
+ * Searchable's custom-field LIKE path already handles the
+ * filter payload. No new widget needed.
+ *
+ * This matches the shape AssetPresenter uses to emit custom
+ * field columns, so the field names (db_column) line up for
+ * carrier-matching inside the modal.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ protected static function customFieldFilterableWidgets(): array
+ {
+ $widgets = [];
+ $fields = CustomField::whereHas('fieldset', function ($query) {
+ $query->whereHas('models');
+ })->get();
+
+ foreach ($fields as $field) {
+ $type = match ($field->element) {
+ 'date_picker', 'datetime_picker' => 'date-range',
+ 'listbox', 'radio' => 'enum',
+ 'checkbox' => 'set',
+ default => null,
+ };
+
+ if ($type === null) {
+ continue;
+ }
+
+ $widget = [
+ 'field' => $field->db_column,
+ 'type' => $type,
+ 'label' => $field->name,
+ ];
+
+ if ($type === 'enum' || $type === 'set') {
+ $options = [];
+ foreach ($field->formatFieldValuesAsArray() as $value => $label) {
+ // The accessor prepends an empty-key "Select X"
+ // placeholder for listbox / radio. That's a form-
+ // facing affordance, not a stored value, so drop
+ // it from the filter widget options.
+ if ($value === '') {
+ continue;
+ }
+ $options[] = [
+ 'value' => (string) $value,
+ 'label' => (string) $label,
+ ];
+ }
+ $widget['options'] = $options;
+ }
+
+ $widgets[] = $widget;
+ }
+
+ return $widgets;
+ }
+
/**
* Maps the field names exposed by the API / transformers to the actual
* Eloquent relation names used in $searchableRelations.
@@ -348,6 +607,201 @@ class Asset extends Depreciable implements Importable
});
}
+ /**
+ * Override hook from Searchable. Routes category / manufacturer
+ * through semi-joins on the AssetModel table because those two
+ * values live on `models` rather than directly on `assets`. The
+ * "null" sentinel resolves to "assets whose model has that FK
+ * null, OR assets with no model at all" so an admin looking for
+ * uncategorized hardware sees everything that can't be assigned
+ * a category by its model.
+ *
+ * Default list queries never pay the subquery cost. Only runs
+ * when a matching filter key is on the request.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ $modelFkByKey = [
+ 'category' => 'category_id',
+ 'manufacturer' => 'manufacturer_id',
+ ];
+
+ if (array_key_exists($filterKey, $modelFkByKey)) {
+ $parsed = $this->parseIdsAndNullSentinel($filterValue);
+ if ($parsed === null) {
+ return null;
+ }
+ [$ids, $includeNull] = $parsed;
+ $modelFkColumn = $modelFkByKey[$filterKey];
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($modelFkColumn, $ids, $includeNull) {
+ if (!empty($ids)) {
+ $nested->whereIn('assets.model_id', function ($q) use ($modelFkColumn, $ids) {
+ $q->from('models')
+ ->whereIn('models.' . $modelFkColumn, $ids)
+ ->select('models.id');
+ });
+ }
+ if ($includeNull) {
+ $nullMatcher = function ($q) use ($modelFkColumn) {
+ $q->whereIn('assets.model_id', function ($sub) use ($modelFkColumn) {
+ $sub->from('models')
+ ->whereNull('models.' . $modelFkColumn)
+ ->select('models.id');
+ })->orWhereNull('assets.model_id');
+ };
+ if (empty($ids)) {
+ $nullMatcher($nested);
+ } else {
+ $nested->orWhereIn('assets.model_id', function ($sub) use ($modelFkColumn) {
+ $sub->from('models')
+ ->whereNull('models.' . $modelFkColumn)
+ ->select('models.id');
+ })->orWhereNull('assets.model_id');
+ }
+ }
+ });
+
+ return $query;
+ }
+
+ // warranty_expires is purchase_date + warranty_months.
+ // Not a stored column, so compute inline. DATE_ADD returns
+ // NULL when either operand is NULL, and BETWEEN excludes
+ // NULLs, so assets without a purchase date or without a
+ // warranty duration naturally fall out of the match.
+ if ($filterKey === 'warranty_expires') {
+ if (!preg_match('/^(\d{4}-\d{2}-\d{2})?\.\.(\d{4}-\d{2}-\d{2})?$/', trim($filterValue), $m)) {
+ return null;
+ }
+ $start = $m[1] !== '' ? $m[1] : null;
+ $end = $m[2] !== '' ? $m[2] : null;
+ if ($start === null && $end === null) {
+ return null;
+ }
+
+ $expr = 'DATE_ADD(assets.purchase_date, INTERVAL assets.warranty_months MONTH)';
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($expr, $start, $end) {
+ if ($start !== null && $end !== null) {
+ $nested->whereRaw("$expr BETWEEN ? AND ?", [$start, $end]);
+ } elseif ($start !== null) {
+ $nested->whereRaw("$expr >= ?", [$start]);
+ } elseif ($end !== null) {
+ $nested->whereRaw("$expr <= ?", [$end]);
+ }
+ });
+
+ return $query;
+ }
+
+ // age in years since purchase_date. TIMESTAMPDIFF returns
+ // NULL for NULL purchase_date, so BETWEEN / > / < drop
+ // never-purchased assets automatically.
+ if ($filterKey === 'age') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $expr = 'TIMESTAMPDIFF(YEAR, assets.purchase_date, NOW())';
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($expr, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->whereRaw("$expr > ?", [$gt]);
+ }
+ if ($lt !== null) {
+ $nested->whereRaw("$expr < ?", [$lt]);
+ }
+ });
+
+ return $query;
+ }
+
+ // status_type is the fixed-enum variant of the status
+ // filter. Each selected type resolves to the set of
+ // status_label ids currently matching that category via
+ // the cached Statuslabel::idsFor() helper (deployable /
+ // pending / undeployable / archived). Multi-select unions
+ // the id sets so picking "deployable" + "pending" filters
+ // assets whose current status is in EITHER bucket.
+ if ($filterKey === 'status_type') {
+ $validTypes = ['deployable', 'pending', 'undeployable', 'archived'];
+ $requested = array_map('trim', explode(',', trim($filterValue)));
+ $types = array_values(array_intersect($validTypes, $requested));
+ if (empty($types)) {
+ return null;
+ }
+
+ $allIds = [];
+ foreach ($types as $type) {
+ $allIds = array_merge($allIds, Statuslabel::idsFor($type)->all());
+ }
+ $allIds = array_values(array_unique(array_map('intval', $allIds)));
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ if (empty($allIds)) {
+ // No status labels of any requested type exist on
+ // this install. Keep intent: zero results instead
+ // of silently dropping the filter.
+ $query->{$outerBoolean}(function ($nested) {
+ $nested->whereRaw('1 = 0');
+ });
+ } else {
+ $whereInMethod = $boolean === 'or' ? 'orWhereIn' : 'whereIn';
+ $query->{$whereInMethod}('assets.status_id', $allIds);
+ }
+
+ return $query;
+ }
+
+ // Polymorphic assigned_to split into three per-type widgets.
+ // The query pins both `assets.assigned_type` AND
+ // `assets.assigned_to` so the id list only matches rows
+ // currently checked out to that specific class. Null
+ // sentinel resolves to `assigned_to IS NULL` (completely
+ // unassigned) regardless of which type the admin opened the
+ // sentinel from, so "not checked out to anyone" has one
+ // answer across all three dropdowns.
+ $assignedTypeByKey = [
+ 'assigned_user' => User::class,
+ 'assigned_asset' => self::class,
+ 'assigned_location' => Location::class,
+ ];
+
+ if (array_key_exists($filterKey, $assignedTypeByKey)) {
+ $parsed = $this->parseIdsAndNullSentinel($filterValue);
+ if ($parsed === null) {
+ return null;
+ }
+ [$ids, $includeNull] = $parsed;
+ $assignedType = $assignedTypeByKey[$filterKey];
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($assignedType, $ids, $includeNull) {
+ if (!empty($ids)) {
+ $nested->where(function ($q) use ($assignedType, $ids) {
+ $q->where('assets.assigned_type', $assignedType)
+ ->whereIn('assets.assigned_to', $ids);
+ });
+ }
+ if ($includeNull) {
+ if (empty($ids)) {
+ $nested->whereNull('assets.assigned_to');
+ } else {
+ $nested->orWhereNull('assets.assigned_to');
+ }
+ }
+ });
+
+ return $query;
+ }
+
+ return null;
+ }
+
public function setExpectedCheckinAttribute($value)
{
if ($value == '') {
diff --git a/app/Models/AssetModel.php b/app/Models/AssetModel.php
index 1dc70ba8ef..be95c9fc1a 100755
--- a/app/Models/AssetModel.php
+++ b/app/Models/AssetModel.php
@@ -26,6 +26,7 @@ use Watson\Validating\ValidatingTrait;
* attributes that are common among the same type of asset.
*
* @version v1.0
+ *
* @mixin IdeHelperAssetModel
*/
class AssetModel extends SnipeModel implements Importable
@@ -131,6 +132,121 @@ class AssetModel extends SnipeModel implements Importable
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields. assets_count is a withCount
+ * alias so it routes through applyCustomFilter below rather than
+ * resolving to a direct column.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => 'category_id',
+ 'endpoint' => 'categories/asset',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => 'manufacturer_id',
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'requestable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.requestable'),
+ ],
+ [
+ 'field' => 'require_serial',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.require_serial'),
+ ],
+ [
+ 'field' => 'eol',
+ 'type' => 'numeric',
+ 'label' => trans('admin/hardware/form.eol_rate'),
+ ],
+ [
+ 'field' => 'min_amt',
+ 'type' => 'numeric',
+ 'label' => trans('general.min_amt'),
+ ],
+ [
+ 'field' => 'assets_count',
+ 'type' => 'numeric',
+ 'label' => trans('general.assets'),
+ ],
+ [
+ 'field' => 'mfg_release_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/models/general.mfg_release_date'),
+ ],
+ [
+ 'field' => 'mfg_discontinued_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/models/general.mfg_discontinued_date'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. Routes assets_count through a
+ * correlated subquery that counts non-trashed assets on this
+ * model, matching the withCount alias the API controller uses to
+ * populate the displayed column.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey !== 'assets_count') {
+ return null;
+ }
+
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $assetsCountSub = \Illuminate\Support\Facades\DB::table('assets')
+ ->whereColumn('assets.model_id', 'models.id')
+ ->whereNull('assets.deleted_at')
+ ->selectRaw('COUNT(*)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($assetsCountSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($assetsCountSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($assetsCountSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
/**
* Computed aliases (withCount/withSum) that can be searched via TextSearch filters.
*
diff --git a/app/Models/Category.php b/app/Models/Category.php
index 97264cdfa6..bcb5442696 100755
--- a/app/Models/Category.php
+++ b/app/Models/Category.php
@@ -70,7 +70,7 @@ class Category extends SnipeModel implements Importable
use ValidatingTrait;
/**
- * The attributes that are mass assignable.
+ * The attributes that are mass-assignable.
*
* @var list<string>
*/
@@ -110,6 +110,108 @@ class Category extends SnipeModel implements Importable
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'category_type',
+ 'type' => 'enum',
+ 'options' => [
+ ['value' => 'asset', 'label' => trans('general.asset')],
+ ['value' => 'accessory', 'label' => trans('general.accessory')],
+ ['value' => 'consumable', 'label' => trans('general.consumable')],
+ ['value' => 'component', 'label' => trans('general.component')],
+ ['value' => 'license', 'label' => trans('general.license')],
+ ],
+ 'label' => trans('admin/categories/general.import_category_type'),
+ ],
+ [
+ 'field' => 'require_acceptance',
+ 'type' => 'boolean',
+ 'label' => trans('admin/categories/table.require_acceptance'),
+ ],
+ [
+ 'field' => 'use_default_eula',
+ 'type' => 'boolean',
+ 'label' => trans('admin/settings/general.default_eula_text'),
+ ],
+ [
+ 'field' => 'checkin_email',
+ 'type' => 'boolean',
+ 'label' => trans('general.send_email'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ [
+ 'field' => 'item_count',
+ 'type' => 'numeric',
+ 'label' => trans('general.qty'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. The displayed "qty" column
+ * (item_count) is derived per row from the category_type and the
+ * matching relation (assets via hasManyThrough models, everything
+ * else via direct hasMany on category_id). Filtering has to use
+ * the same CASE-dispatched correlated subquery so the gt/lt
+ * bounds match what the user sees.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey !== 'item_count') {
+ return null;
+ }
+
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $countExpr = "(CASE categories.category_type
+ WHEN 'asset' THEN (SELECT COUNT(*) FROM models INNER JOIN assets ON assets.model_id = models.id WHERE models.category_id = categories.id AND assets.deleted_at IS NULL)
+ WHEN 'accessory' THEN (SELECT COUNT(*) FROM accessories WHERE accessories.category_id = categories.id AND accessories.deleted_at IS NULL)
+ WHEN 'consumable' THEN (SELECT COUNT(*) FROM consumables WHERE consumables.category_id = categories.id AND consumables.deleted_at IS NULL)
+ WHEN 'component' THEN (SELECT COUNT(*) FROM components WHERE components.category_id = categories.id AND components.deleted_at IS NULL)
+ WHEN 'license' THEN (SELECT COUNT(*) FROM licenses WHERE licenses.category_id = categories.id AND licenses.deleted_at IS NULL)
+ ELSE 0
+ END)";
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($countExpr, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->whereRaw("{$countExpr} > ?", [$gt]);
+ }
+ if ($lt !== null) {
+ $nested->whereRaw("{$countExpr} < ?", [$lt]);
+ }
+ });
+
+ return $query;
+ }
+
protected $searchableCounts = [
'accessories_count',
'consumables_count',
diff --git a/app/Models/Company.php b/app/Models/Company.php
index 316790be9a..86661349f0 100644
--- a/app/Models/Company.php
+++ b/app/Models/Company.php
@@ -140,6 +140,41 @@ final class Company extends SnipeModel
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'parent',
+ 'type' => 'fk',
+ 'column' => 'parent_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.parent'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* The attributes that are mass assignable.
*
diff --git a/app/Models/Component.php b/app/Models/Component.php
index 632b798ae1..fb631e8734 100644
--- a/app/Models/Component.php
+++ b/app/Models/Component.php
@@ -158,7 +158,7 @@ class Component extends SnipeModel implements Importable
'category' => ['name'],
'company' => ['name'],
'location' => ['name'],
- // Search by the parent's "typical supplier" template — see the
+ // Search by the parent's "typical supplier" template. See the
// Accessory model for the rationale.
'defaultSupplier' => ['name'],
'manufacturer' => ['name'],
@@ -169,6 +169,211 @@ class Component extends SnipeModel implements Importable
'orders' => ['order_number'],
];
+ /**
+ * Advanced-search filterable fields. Same as
+ * Accessory::filterableFields, EXCEPT:
+ * remaining uses SUM(components_assets.assigned_qty) rather than
+ * COUNT(pivot) because each checkout row carries a quantity, so
+ * the "checked out" number is a sum of assigned_qty.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => 'category_id',
+ 'endpoint' => 'categories/component',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => 'manufacturer_id',
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'default_supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'location',
+ 'type' => 'fk',
+ 'column' => 'location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('general.location'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'requestable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.requestable'),
+ ],
+ [
+ 'field' => 'qty',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.total'),
+ ],
+ [
+ 'field' => 'min_amt',
+ 'type' => 'numeric',
+ 'label' => trans('general.min_amt'),
+ ],
+ [
+ 'field' => 'remaining',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.remaining'),
+ ],
+ [
+ 'field' => 'purchase_cost',
+ 'type' => 'numeric',
+ 'label' => trans('general.last_unit_cost'),
+ ],
+ [
+ 'field' => 'purchase_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.last_purchase_date'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable Trait. purchase_date / purchase_cost
+ * route through correlated subqueries on OrderItem (via the
+ * HasOrders polymorphic pivot). remaining uses
+ * SUM(components_assets.assigned_qty) to match the
+ * numCheckedOut uses on this model. Default list queries never
+ * pay the subquery cost. Only runs when a matching filter key
+ * is on the request.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey === 'purchase_date') {
+ if (!preg_match('/^(\d{4}-\d{2}-\d{2})?\.\.(\d{4}-\d{2}-\d{2})?$/', trim($filterValue), $m)) {
+ return null;
+ }
+ $start = $m[1] !== '' ? $m[1] : null;
+ $end = $m[2] !== '' ? $m[2] : null;
+ if ($start === null && $end === null) {
+ return null;
+ }
+
+ $lastDateSub = \App\Models\OrderItem::query()
+ ->join('orders', 'orders.id', '=', 'order_items.order_id')
+ ->whereColumn('order_items.item_id', 'components.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('orders.purchase_date');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastDateSub, $start, $end) {
+ if ($start !== null && $end !== null) {
+ $nested->whereBetween($lastDateSub, [$start, $end]);
+ } elseif ($start !== null) {
+ $nested->where($lastDateSub, '>=', $start);
+ } elseif ($end !== null) {
+ $nested->where($lastDateSub, '<=', $end);
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'remaining') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ // Component checkout is SUM(assigned_qty), not COUNT, so
+ // each pivot row can represent multiple units checked out
+ // to one asset. COALESCE to 0 for components with no
+ // pivot rows (SUM returns NULL).
+ $checkoutSumSub = \Illuminate\Support\Facades\DB::table('components_assets')
+ ->whereColumn('components_assets.component_id', 'components.id')
+ ->selectRaw('COALESCE(SUM(components_assets.assigned_qty), 0)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($checkoutSumSub, $gt, $lt) {
+ [$sumSql, $sumBindings] = [$checkoutSumSub->toSql(), $checkoutSumSub->getBindings()];
+ if ($gt !== null) {
+ $nested->whereRaw(
+ "(components.qty - ({$sumSql})) > ?",
+ array_merge($sumBindings, [$gt])
+ );
+ }
+ if ($lt !== null) {
+ $nested->whereRaw(
+ "(components.qty - ({$sumSql})) < ?",
+ array_merge($sumBindings, [$lt])
+ );
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'purchase_cost') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $lastCostSub = \App\Models\OrderItem::query()
+ ->whereColumn('order_items.item_id', 'components.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('order_items.price');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastCostSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($lastCostSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($lastCostSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
+ return null;
+ }
+
public static function booted()
{
static::saving(function ($model) {
diff --git a/app/Models/Consumable.php b/app/Models/Consumable.php
index a53530b5ca..416774825f 100644
--- a/app/Models/Consumable.php
+++ b/app/Models/Consumable.php
@@ -164,7 +164,7 @@ class Consumable extends SnipeModel implements Importable
'company' => ['name'],
'location' => ['name'],
'manufacturer' => ['name'],
- // Search by the parent's "typical supplier" template — see the
+ // Search by the parent's "typical supplier" template. See the
// Accessory model for the rationale.
'defaultSupplier' => ['name'],
'adminuser' => ['first_name', 'last_name', 'display_name'],
@@ -174,6 +174,210 @@ class Consumable extends SnipeModel implements Importable
'orders' => ['order_number'],
];
+ /**
+ * Advanced-search filterable fields. The purchase_date, remaining, and
+ * purchase_cost fields are derived from the Orders / Users
+ * pivot and routed through applyCustomFilter below rather than
+ * a direct column on consumables.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => 'category_id',
+ 'endpoint' => 'categories/consumable',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => 'manufacturer_id',
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'default_supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'location',
+ 'type' => 'fk',
+ 'column' => 'location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('general.location'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'requestable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/hardware/general.requestable'),
+ ],
+ [
+ 'field' => 'qty',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.total'),
+ ],
+ [
+ 'field' => 'min_amt',
+ 'type' => 'numeric',
+ 'label' => trans('general.min_amt'),
+ ],
+ [
+ 'field' => 'remaining',
+ 'type' => 'numeric',
+ 'label' => trans('admin/accessories/general.remaining'),
+ ],
+ [
+ 'field' => 'purchase_cost',
+ 'type' => 'numeric',
+ 'label' => trans('general.last_unit_cost'),
+ ],
+ [
+ 'field' => 'purchase_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.last_purchase_date'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. Same shape as
+ * Accessory::applyCustomFilter. purchase_date / purchase_cost
+ * route through correlated subqueries on OrderItem (via the
+ * HasOrders polymorphic pivot). remaining routes through a
+ * subquery on the consumables_users pivot. Default list queries
+ * never pay the subquery cost. Only runs when a matching filter
+ * key is on the request.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey === 'purchase_date') {
+ if (!preg_match('/^(\d{4}-\d{2}-\d{2})?\.\.(\d{4}-\d{2}-\d{2})?$/', trim($filterValue), $m)) {
+ return null;
+ }
+ $start = $m[1] !== '' ? $m[1] : null;
+ $end = $m[2] !== '' ? $m[2] : null;
+ if ($start === null && $end === null) {
+ return null;
+ }
+
+ $lastDateSub = \App\Models\OrderItem::query()
+ ->join('orders', 'orders.id', '=', 'order_items.order_id')
+ ->whereColumn('order_items.item_id', 'consumables.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('orders.purchase_date');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastDateSub, $start, $end) {
+ if ($start !== null && $end !== null) {
+ $nested->whereBetween($lastDateSub, [$start, $end]);
+ } elseif ($start !== null) {
+ $nested->where($lastDateSub, '>=', $start);
+ } elseif ($end !== null) {
+ $nested->where($lastDateSub, '<=', $end);
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'remaining') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ // numCheckedOut on Consumable walks consumables_users
+ // (one pivot row per handout). Filter mirrors that exact
+ // shape so advanced-search semantics match the displayed
+ // "remaining" column.
+ $checkoutCountSub = \Illuminate\Support\Facades\DB::table('consumables_users')
+ ->whereColumn('consumables_users.consumable_id', 'consumables.id')
+ ->selectRaw('COUNT(*)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($checkoutCountSub, $gt, $lt) {
+ [$countSql, $countBindings] = [$checkoutCountSub->toSql(), $checkoutCountSub->getBindings()];
+ if ($gt !== null) {
+ $nested->whereRaw(
+ "(consumables.qty - ({$countSql})) > ?",
+ array_merge($countBindings, [$gt])
+ );
+ }
+ if ($lt !== null) {
+ $nested->whereRaw(
+ "(consumables.qty - ({$countSql})) < ?",
+ array_merge($countBindings, [$lt])
+ );
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'purchase_cost') {
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $lastCostSub = \App\Models\OrderItem::query()
+ ->whereColumn('order_items.item_id', 'consumables.id')
+ ->where('order_items.item_type', static::class)
+ ->orderByDesc('order_items.id')
+ ->limit(1)
+ ->select('order_items.price');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($lastCostSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($lastCostSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($lastCostSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
+ return null;
+ }
+
/**
* On hard-delete, wipe the image file and Files-tab attachments.
* Soft-delete leaves everything alone so a restore comes back with
diff --git a/app/Models/Department.php b/app/Models/Department.php
index 883ab3a823..6c1d42a1fb 100644
--- a/app/Models/Department.php
+++ b/app/Models/Department.php
@@ -102,6 +102,55 @@ class Department extends SnipeModel
'manager' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('general.company'),
+ ],
+ [
+ 'field' => 'location',
+ 'type' => 'fk',
+ 'column' => 'location_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('general.location'),
+ ],
+ [
+ 'field' => 'manager',
+ 'type' => 'fk',
+ 'column' => 'manager_id',
+ 'endpoint' => 'users',
+ 'label' => trans('admin/departments/table.manager'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* On hard-delete, wipe the image file and Files-tab attachments.
* Soft-delete leaves everything alone so a restore comes back with
diff --git a/app/Models/Depreciation.php b/app/Models/Depreciation.php
index ad8ab8a61f..410cdf8010 100755
--- a/app/Models/Depreciation.php
+++ b/app/Models/Depreciation.php
@@ -70,6 +70,50 @@ class Depreciation extends SnipeModel
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields. depreciation_type (amount or
+ * percent) is only populated for diminishing-balance depreciations,
+ * so rows left on straight-line will not match either option.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'depreciation_type',
+ 'type' => 'enum',
+ 'options' => [
+ ['value' => 'amount', 'label' => trans('general.depreciation_options.amount')],
+ ['value' => 'percent', 'label' => trans('general.depreciation_options.percent')],
+ ],
+ 'label' => trans('general.depreciation_type'),
+ ],
+ [
+ 'field' => 'months',
+ 'type' => 'numeric',
+ 'label' => trans('admin/depreciations/general.number_of_months'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
public function isDeletable()
{
return Gate::allows('delete', $this)
diff --git a/app/Models/Group.php b/app/Models/Group.php
index faf6c3a658..deb45f5a43 100755
--- a/app/Models/Group.php
+++ b/app/Models/Group.php
@@ -65,6 +65,35 @@ class Group extends SnipeModel
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields. Groups has no model-level FKs
+ * beyond created_by, so the filter set is narrow.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* Detach all users_groups pivot rows when a group is deleted.
*/
diff --git a/app/Models/License.php b/app/Models/License.php
index 6c794c56a5..bee51ea1ac 100755
--- a/app/Models/License.php
+++ b/app/Models/License.php
@@ -147,6 +147,152 @@ class License extends Depreciable implements Importable
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * Direct columns on licenses carry purchase_cost / purchase_date
+ * (unlike Accessory where they moved to the Orders table), so no
+ * applyCustomFilter branches for those. free_seats_count is a
+ * derived withCount on freeSeats() so it routes through
+ * applyCustomFilter.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'category',
+ 'type' => 'fk',
+ 'column' => 'category_id',
+ 'endpoint' => 'categories/license',
+ 'label' => trans('general.category'),
+ ],
+ [
+ 'field' => 'manufacturer',
+ 'type' => 'fk',
+ 'column' => 'manufacturer_id',
+ 'endpoint' => 'manufacturers',
+ 'label' => trans('general.manufacturer'),
+ ],
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'reassignable',
+ 'type' => 'boolean',
+ 'label' => trans('admin/licenses/form.reassignable'),
+ ],
+ [
+ 'field' => 'maintained',
+ 'type' => 'boolean',
+ 'label' => trans('admin/licenses/form.maintained'),
+ ],
+ [
+ 'field' => 'seats',
+ 'type' => 'numeric',
+ 'label' => trans('admin/licenses/form.seats'),
+ ],
+ [
+ 'field' => 'min_amt',
+ 'type' => 'numeric',
+ 'label' => trans('general.min_amt'),
+ ],
+ [
+ 'field' => 'free_seats_count',
+ 'type' => 'numeric',
+ 'label' => trans('admin/licenses/general.remaining_seats'),
+ ],
+ [
+ 'field' => 'purchase_cost',
+ 'type' => 'numeric',
+ 'label' => trans('general.purchase_cost'),
+ ],
+ [
+ 'field' => 'purchase_date',
+ 'type' => 'date-range',
+ 'label' => trans('general.purchase_date'),
+ ],
+ [
+ 'field' => 'expiration_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/licenses/form.expiration'),
+ ],
+ [
+ 'field' => 'termination_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/licenses/form.termination_date'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. Routes free_seats_count filter
+ * through a correlated subquery on license_seats that mirrors
+ * the freeSeats() relation (seats with no assigned_to and no
+ * asset_id, not soft-deleted). Default list queries never pay
+ * the subquery cost.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey !== 'free_seats_count') {
+ return null;
+ }
+
+ $bounds = $this->parseGtLtBounds($filterValue);
+ if ($bounds === null) {
+ return null;
+ }
+ [$gt, $lt] = $bounds;
+
+ $freeSeatCountSub = \Illuminate\Support\Facades\DB::table('license_seats')
+ ->whereColumn('license_seats.license_id', 'licenses.id')
+ ->whereNull('license_seats.assigned_to')
+ ->whereNull('license_seats.asset_id')
+ ->whereNull('license_seats.deleted_at')
+ ->selectRaw('COUNT(*)');
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($freeSeatCountSub, $gt, $lt) {
+ if ($gt !== null) {
+ $nested->where($freeSeatCountSub, '>', $gt);
+ }
+ if ($lt !== null) {
+ $nested->where($freeSeatCountSub, '<', $lt);
+ }
+ });
+
+ return $query;
+ }
+
protected $appends = ['free_seat_count'];
/**
diff --git a/app/Models/Location.php b/app/Models/Location.php
index a70ae34d66..b5d9955599 100755
--- a/app/Models/Location.php
+++ b/app/Models/Location.php
@@ -125,6 +125,55 @@ class Location extends SnipeModel implements Importable
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'company',
+ 'type' => 'fk',
+ 'column' => 'company_id',
+ 'endpoint' => 'companies',
+ 'label' => trans('admin/companies/table.title'),
+ ],
+ [
+ 'field' => 'parent',
+ 'type' => 'fk',
+ 'column' => 'parent_id',
+ 'endpoint' => 'locations',
+ 'label' => trans('admin/locations/table.parent'),
+ ],
+ [
+ 'field' => 'manager',
+ 'type' => 'fk',
+ 'column' => 'manager_id',
+ 'endpoint' => 'users',
+ 'label' => trans('admin/users/table.manager'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* On hard-delete, wipe the image file and Files-tab attachments.
* Soft-delete leaves everything alone so a restore comes back with
diff --git a/app/Models/Maintenance.php b/app/Models/Maintenance.php
index 6f0b84499b..5d20f438e4 100644
--- a/app/Models/Maintenance.php
+++ b/app/Models/Maintenance.php
@@ -153,6 +153,185 @@ class Maintenance extends SnipeModel implements CompanyableChild
return ['asset'];
}
+ /**
+ * Advanced-search filterable fields. The asset_tag entry's field
+ * key matches the bs-table column.field so the modal widget-swap
+ * replaces the auto-generated text input with the select2
+ * checkboxes picker.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'asset_tag',
+ 'type' => 'fk',
+ 'column' => 'item_id',
+ 'endpoint' => 'hardware',
+ 'label' => trans('general.assets'),
+ ],
+ [
+ // Field name matches the bs-table column.field in the
+ // maintenances presenter so the modal's widget-swap
+ // finds the auto-generated carrier input and replaces
+ // the plain-text picker with a select2 checkboxes
+ // against the maintenance-types selectlist.
+ 'field' => 'maintenance_type_details',
+ 'type' => 'fk',
+ 'column' => 'maintenance_type_id',
+ 'endpoint' => 'maintenance-types',
+ 'label' => trans('admin/maintenances/form.asset_maintenance_type'),
+ ],
+ [
+ // status_label is a derived display column that reads
+ // from the related asset's status_id. applyCustomFilter
+ // walks that relation via whereHas so the picker still
+ // writes a familiar statuslabels id CSV.
+ 'field' => 'status_label',
+ 'type' => 'fk',
+ 'column' => null,
+ 'endpoint' => 'statuslabels',
+ 'label' => trans('admin/hardware/table.status'),
+ ],
+ [
+ 'field' => 'supplier',
+ 'type' => 'fk',
+ 'column' => 'supplier_id',
+ 'endpoint' => 'suppliers',
+ 'label' => trans('general.supplier'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'completed_by',
+ 'type' => 'fk',
+ 'column' => 'completed_by',
+ 'endpoint' => 'users',
+ 'label' => trans('admin/maintenances/form.completed_by'),
+ ],
+ [
+ 'field' => 'responsible_party',
+ 'type' => 'fk',
+ 'column' => 'responsible_party_id',
+ 'endpoint' => 'users',
+ 'label' => trans('admin/maintenances/form.responsible_party'),
+ ],
+ [
+ 'field' => 'is_warranty',
+ 'type' => 'boolean',
+ 'label' => trans('admin/maintenances/form.is_warranty'),
+ ],
+ [
+ 'field' => 'cost',
+ 'type' => 'numeric',
+ 'label' => trans('admin/maintenances/form.cost'),
+ ],
+ [
+ 'field' => 'asset_maintenance_time',
+ 'type' => 'numeric',
+ 'label' => trans('admin/maintenances/form.asset_maintenance_time'),
+ ],
+ [
+ 'field' => 'start_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/maintenances/form.start_date'),
+ ],
+ [
+ 'field' => 'expected_completion_date',
+ 'type' => 'date-range',
+ 'label' => trans('admin/maintenances/form.completion_date'),
+ ],
+ [
+ 'field' => 'completed_at',
+ 'type' => 'date-range',
+ 'label' => trans('admin/maintenances/form.completed_at'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. asset_tag picks against the
+ * hardware selectlist, so route the chosen ids to item_id AND
+ * pin item_type = Asset so the whereIn does not collide with a
+ * future non-Asset maintenance that happens to share one of
+ * those numeric ids. status_label walks the related asset's
+ * status_id since the maintenances table has no status column.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey === 'asset_tag') {
+ $parsed = $this->parseIdsAndNullSentinel($filterValue);
+ if ($parsed === null) {
+ return null;
+ }
+ [$ids, $includeNull] = $parsed;
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($ids, $includeNull) {
+ $nested->where('maintenances.item_type', Asset::class);
+ if (!empty($ids)) {
+ $nested->whereIn('maintenances.item_id', $ids);
+ }
+ if ($includeNull) {
+ if (!empty($ids)) {
+ $nested->orWhereNull('maintenances.item_id');
+ } else {
+ $nested->whereNull('maintenances.item_id');
+ }
+ }
+ });
+
+ return $query;
+ }
+
+ if ($filterKey === 'status_label') {
+ $parsed = $this->parseIdsAndNullSentinel($filterValue);
+ if ($parsed === null) {
+ return null;
+ }
+ [$ids, $includeNull] = $parsed;
+ if (empty($ids) && !$includeNull) {
+ return null;
+ }
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($ids, $includeNull) {
+ $nested->whereHas('asset', function ($assetQuery) use ($ids, $includeNull) {
+ if (!empty($ids) && $includeNull) {
+ $assetQuery->where(function ($q) use ($ids) {
+ $q->whereIn('assets.status_id', $ids)
+ ->orWhereNull('assets.status_id');
+ });
+ } elseif (!empty($ids)) {
+ $assetQuery->whereIn('assets.status_id', $ids);
+ } else {
+ $assetQuery->whereNull('assets.status_id');
+ }
+ });
+ });
+
+ return $query;
+ }
+
+ return null;
+ }
+
/**
* getImprovementOptions
*
diff --git a/app/Models/MaintenanceType.php b/app/Models/MaintenanceType.php
index a20e26ff77..cf8ac01ea2 100644
--- a/app/Models/MaintenanceType.php
+++ b/app/Models/MaintenanceType.php
@@ -2,6 +2,7 @@
namespace App\Models;
+use App\Models\Traits\Searchable;
use App\Presenters\MaintenanceTypePresenter;
use App\Presenters\Presentable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,6 +17,7 @@ class MaintenanceType extends SnipeModel
{
use HasFactory;
use Presentable;
+ use Searchable;
use SoftDeletes;
use ValidatingTrait;
@@ -31,6 +33,40 @@ class MaintenanceType extends SnipeModel
protected $fillable = ['name', 'tag_color'];
+ protected $searchableAttributes = ['name', 'tag_color'];
+
+ protected $searchableRelations = [
+ 'adminuser' => ['first_name', 'last_name', 'display_name'],
+ ];
+
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
public function isDeletable(): bool
{
return Gate::allows('delete', $this)
diff --git a/app/Models/Manufacturer.php b/app/Models/Manufacturer.php
index 696dca2f69..52200b355d 100755
--- a/app/Models/Manufacturer.php
+++ b/app/Models/Manufacturer.php
@@ -90,6 +90,34 @@ class Manufacturer extends SnipeModel implements Importable
'adminuser' => ['first_name', 'last_name', 'display_name'],
];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* On hard-delete, wipe the image file. Soft-delete leaves it alone so a
* subsequent restore comes back with its image intact.
diff --git a/app/Models/Statuslabel.php b/app/Models/Statuslabel.php
index 3a44a6f1da..e8c99475bf 100755
--- a/app/Models/Statuslabel.php
+++ b/app/Models/Statuslabel.php
@@ -122,6 +122,99 @@ class Statuslabel extends SnipeModel
*/
protected $searchableRelations = [];
+ /**
+ * Advanced-search filterable fields.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'type',
+ 'type' => 'enum',
+ 'options' => [
+ ['value' => 'deployable', 'label' => trans('admin/statuslabels/table.deployable')],
+ ['value' => 'pending', 'label' => trans('admin/statuslabels/table.pending')],
+ ['value' => 'undeployable', 'label' => trans('admin/statuslabels/table.undeployable')],
+ ['value' => 'archived', 'label' => trans('admin/statuslabels/table.archived')],
+ ],
+ 'label' => trans('admin/statuslabels/table.status_type'),
+ ],
+ [
+ 'field' => 'show_in_nav',
+ 'type' => 'boolean',
+ 'label' => trans('admin/statuslabels/table.show_in_nav'),
+ ],
+ [
+ 'field' => 'default_label',
+ 'type' => 'boolean',
+ 'label' => trans('admin/statuslabels/table.default_label'),
+ ],
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
+ /**
+ * Override hook from Searchable. The `type` filter is a four-way
+ * enum (deployable / pending / undeployable / archived) that
+ * decomposes into a WHERE on the stored (deployable, pending,
+ * archived) tuple. Multi-select is supported by OR-combining the
+ * per-value triples inside a single scope so a sibling AND
+ * continues to compose cleanly.
+ */
+ protected function applyCustomFilter(\Illuminate\Database\Eloquent\Builder $query, string $filterKey, string $filterValue, string $boolean = 'and'): ?\Illuminate\Database\Eloquent\Builder
+ {
+ if ($filterKey !== 'type') {
+ return null;
+ }
+
+ $tokens = array_values(array_filter(array_map('trim', explode(',', $filterValue)), 'strlen'));
+ if ($tokens === []) {
+ return null;
+ }
+
+ $tuples = [
+ 'deployable' => [1, 0, 0],
+ 'pending' => [0, 1, 0],
+ 'undeployable' => [0, 0, 0],
+ 'archived' => [0, 0, 1],
+ ];
+ $matched = array_values(array_intersect_key($tuples, array_flip($tokens)));
+ if ($matched === []) {
+ return null;
+ }
+
+ $outerBoolean = $boolean === 'or' ? 'orWhere' : 'where';
+ $query->{$outerBoolean}(function ($nested) use ($matched) {
+ foreach ($matched as $triple) {
+ $nested->orWhere(function ($row) use ($triple) {
+ $row->where('deployable', $triple[0])
+ ->where('pending', $triple[1])
+ ->where('archived', $triple[2]);
+ });
+ }
+ });
+
+ return $query;
+ }
+
public function isDeletable()
{
return Gate::allows('delete', $this)
diff --git a/app/Models/Supplier.php b/app/Models/Supplier.php
index 7c2dec44fd..a079ac599b 100755
--- a/app/Models/Supplier.php
+++ b/app/Models/Supplier.php
@@ -77,6 +77,35 @@ class Supplier extends SnipeModel implements Importable
*/
protected $searchableRelations = [];
+ /**
+ * Advanced-search filterable fields. Suppliers have no company_id or
+ * other model-level FKs beyond created_by.
+ *
+ * @return array<int, array<string, mixed>>
+ */
+ public static function filterableFields(): array
+ {
+ return [
+ [
+ 'field' => 'created_by',
+ 'type' => 'fk',
+ 'column' => 'created_by',
+ 'endpoint' => 'users',
+ 'label' => trans('general.created_by'),
+ ],
+ [
+ 'field' => 'created_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.created_at'),
+ ],
+ [
+ 'field' => 'updated_at',
+ 'type' => 'date-range',
+ 'label' => trans('general.updated_at'),
+ ],
+ ];
+ }
+
/**
* The attributes that are mass assignable.
*