A free open source IT asset/license management system
Added low stock controller
snipe9c61c4c629de
diff --git a/app/Http/Controllers/Api/LowStockController.php b/app/Http/Controllers/Api/LowStockController.phpnew file mode 100644index 0000000000..15ae97b34f--- /dev/null+++ b/app/Http/Controllers/Api/LowStockController.php@@ -0,0 +1,81 @@+<?php++namespace App\Http\Controllers\Api;++use App\Helpers\Helper;+use App\Http\Controllers\Controller;+use App\Http\Transformers\LowStockTransformer;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;++/**+ * Unified low-stock endpoint for the dashboard widget. Delegates the+ * actual "which rows count as low" logic to Helper::checkLowInventory()+ * so this API and the top-nav alert bell (livewire:alert-menu) share a+ * single source of truth. The helper factors in current checkouts and+ * the site-wide alert_threshold buffer, and it covers five source+ * models (Consumable / Accessory / Component / AssetModel / License) —+ * routing through it here avoids ever duplicating that logic on the+ * widget side and drifting from what the alert bell shows.+ *+ * Search / sort / paginate happen after the helper returns, on a+ * bounded set (only rows the helper flagged as alertable, which is+ * small by definition), so PHP-side ordering is cheap here.+ */+class LowStockController extends Controller+{+ /**+ * Sort keys that bs-table can toggle from a column header. Anything+ * else falls back to remaining_asc (most urgent first).+ */+ private const SORTABLE_COLUMNS = ['name', 'type', 'qty', 'min_amt', 'remaining', 'percent'];++ public function index(Request $request): JsonResponse|array+ {+ // Base access gate. Anyone who can view any of the source types+ // can see the widget; per-row permissions (adjust_quantity)+ // still gate the action buttons inside the transformer.+ $viewer = auth()->user();+ $canView = false;+ foreach (LowStockTransformer::sourceModels() as $modelClass) {+ if ($viewer?->can('view', $modelClass)) {+ $canView = true;+ break;+ }+ }+ if (! $canView) {+ abort(403);+ }++ $rows = Helper::checkLowInventory();++ $search = trim((string) $request->input('search', ''));+ if ($search !== '') {+ $rows = array_values(array_filter($rows, fn ($r) => str_contains(strtolower($r['name']), strtolower($search))));+ }++ $sort = in_array($request->input('sort'), self::SORTABLE_COLUMNS, true) ? $request->input('sort') : 'remaining';+ $order = $request->input('order') === 'desc' ? 'desc' : 'asc';++ usort($rows, function ($a, $b) use ($sort) {+ return match ($sort) {+ 'name' => strcasecmp((string) $a['name'], (string) $b['name']),+ 'type' => strcmp((string) $a['type'], (string) $b['type']),+ 'qty' => (int) ($a['qty'] ?? 0) <=> (int) ($b['qty'] ?? 0),+ 'min_amt' => (int) $a['min_amt'] <=> (int) $b['min_amt'],+ 'percent' => (int) $a['percent'] <=> (int) $b['percent'],+ default => (int) $a['remaining'] <=> (int) $b['remaining'],+ };+ });+ if ($order === 'desc') {+ $rows = array_reverse($rows);+ }++ $total = count($rows);+ $offset = max(0, (int) app('api_offset_value'));+ $limit = max(1, (int) app('api_limit_value'));+ $page = array_slice($rows, $offset, $limit);++ return (new LowStockTransformer)->transformLowStockItems($page, $total);+ }+}diff --git a/app/Http/Transformers/LowStockTransformer.php b/app/Http/Transformers/LowStockTransformer.phpnew file mode 100644index 0000000000..6b4a126ea9--- /dev/null+++ b/app/Http/Transformers/LowStockTransformer.php@@ -0,0 +1,124 @@+<?php++namespace App\Http\Transformers;++use App\Models\Accessory;+use App\Models\AssetModel;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\License;+use Illuminate\Support\Facades\Gate;++/**+ * Normalizes low-stock rows for the dashboard widget's bs-table and any+ * other surface (email digests, exports) that wants the same shape.+ *+ * Consumes the array-of-arrays output of Helper::checkLowInventory() —+ * the same query that powers the top-nav alert bell — so the two+ * surfaces can't drift out of sync. Each input row already carries a+ * plural type discriminator ("consumables", "accessories", ...);+ * we singularize it to match polymorphicItemFormatter's expectation on+ * the frontend.+ *+ * Fields output per row:+ * - id: composite "consumable-5" so bs-table has a unique row key+ * across the five source tables (numeric ids collide)+ * - item: { id, name, type, deleted_at } for polymorphicItemFormatter+ * - qty / min_amt / remaining / percent: raw numbers+ * - available_actions.adjust_quantity: per-type policy check;+ * AssetModels and Licenses always get false (no adjust-quantity+ * flow exists on those models today)+ */+class LowStockTransformer+{+ /**+ * Map the helper's plural type discriminators to the singular form+ * polymorphicItemFormatter expects. Anything not in this map falls+ * through as-is and will render without an icon.+ */+ private const TYPE_SINGULAR = [+ 'consumables' => 'consumable',+ 'accessories' => 'accessory',+ 'components' => 'component',+ 'models' => 'model',+ 'licenses' => 'license',+ ];++ /**+ * The models that expose an adjust-quantity flow via the shared+ * blade/modals/adjust-quantity modal. AssetModels and Licenses use+ * different provisioning flows and don't participate.+ */+ private const ADJUST_QUANTITY_MODELS = [+ 'consumable' => Consumable::class,+ 'accessory' => Accessory::class,+ 'component' => Component::class,+ ];++ /**+ * @param array<int, array<string, mixed>> $rows as returned by Helper::checkLowInventory()+ */+ public function transformLowStockItems(array $rows, int $total): array+ {+ $out = [];+ foreach ($rows as $row) {+ $out[] = $this->transformLowStockItem($row);+ }++ return (new DatatablesTransformer)->transformDatatables($out, $total);+ }++ /**+ * @param array<string, mixed> $row+ * @return array<string, mixed>+ */+ public function transformLowStockItem(array $row): array+ {+ $type = self::TYPE_SINGULAR[$row['type']] ?? $row['type'];+ $modelClass = self::ADJUST_QUANTITY_MODELS[$type] ?? null;++ return [+ 'id' => $type.'-'.$row['id'],+ 'item' => [+ 'id' => (int) $row['id'],+ 'name' => e($row['name']),+ 'type' => $type,+ 'deleted_at' => null,+ ],+ 'qty' => (int) ($row['qty'] ?? 0),+ 'min_amt' => (int) $row['min_amt'],+ 'remaining' => (int) $row['remaining'],+ 'percent' => (int) $row['percent'],+ 'available_actions' => [+ 'adjust_quantity' => $modelClass !== null && Gate::allows('update', $modelClass),+ ],+ ];+ }++ /**+ * Type-check for models that support in-place quantity adjustment.+ * Referenced from AssetModel + License classes when the transformer+ * needs to gate icon rendering; kept as a separate const so it's+ * easy to extend if another source model joins the flow.+ *+ * @return array<string, class-string>+ */+ public static function adjustQuantityModels(): array+ {+ return self::ADJUST_QUANTITY_MODELS;+ }++ /**+ * @return array<int, class-string>+ */+ public static function sourceModels(): array+ {+ return [+ Consumable::class,+ Accessory::class,+ Component::class,+ AssetModel::class,+ License::class,+ ];+ }+}