when(! $includeInactive, fn (Builder $query) => $query->where('is_active', true)) ->withCount('items') ->orderBy('sort_order') ->get() ->map(fn (StockItemGroupModel $model): StockGroupSummary => new StockGroupSummary($model->id, $model->name, $model->is_active, (int) $model->getAttribute('items_count'))) ->values() ->all(); } public function items(?string $search = null, ?int $groupId = null, bool $onlyReorder = false, bool $includeInactive = false): array { $search = trim((string) $search); return $this->itemQuery() ->when($groupId !== null, fn (Builder $query) => $query->where('stock_items.stock_item_group_id', $groupId)) ->when(! $includeInactive, fn (Builder $query) => $query->where('stock_items.is_active', true)) ->get() ->filter(fn (StockItemModel $model): bool => $search === '' || StockSearch::matches($search, $model->name, $model->code)) ->map(fn (StockItemModel $model): StockItemSummary => $this->toSummary($model)) ->filter(fn (StockItemSummary $item): bool => ! $onlyReorder || $item->needsReorder()) ->values() ->all(); } public function findItem(int $id): ?StockItemSummary { $model = $this->itemQuery()->where('stock_items.id', $id)->first(); return $model === null ? null : $this->toSummary($model); } public function itemsByIds(array $ids): array { if ($ids === []) { return []; } return $this->itemQuery() ->whereIn('stock_items.id', $ids) ->get() ->mapWithKeys(fn (StockItemModel $model): array => [$model->id => $this->toSummary($model)]) ->all(); } public function movementsOf(int $itemId, int $limit = 200): array { $models = StockMovementModel::query() ->with('reversal:id,reverses_movement_id') ->where('stock_item_id', $itemId) ->orderByDesc('id') ->limit($limit) ->get(); $balance = (int) StockMovementModel::query()->where('stock_item_id', $itemId)->sum('quantity_milli'); return $this->summaries($models, $balance); } public function findMovement(int $id): ?StockMovementSummary { $model = StockMovementModel::query()->with('reversal:id,reverses_movement_id')->find($id); if ($model === null) { return null; } $balance = (int) StockMovementModel::query() ->where('stock_item_id', $model->stock_item_id) ->where('id', '<=', $model->id) ->sum('quantity_milli'); return $this->summaries(collect([$model]), $balance)[0]; } public function imagePathOf(int $itemId, bool $thumbnail): ?string { $model = StockItemModel::query()->find($itemId, ['id', 'image_path', 'thumbnail_path']); return $thumbnail ? $model?->thumbnail_path : $model?->image_path; } /** * @return Builder */ private function itemQuery(): Builder { return StockItemModel::query() ->join('stock_item_groups', 'stock_item_groups.id', '=', 'stock_items.stock_item_group_id') ->select('stock_items.*') ->addSelect('stock_item_groups.name as group_name') ->selectSub( StockMovementModel::query()->selectRaw('COALESCE(SUM(quantity_milli), 0)')->whereColumn('stock_movements.stock_item_id', 'stock_items.id'), 'balance_milli', ) ->orderBy('stock_item_groups.sort_order') ->orderBy('stock_items.name'); } private function toSummary(StockItemModel $model): StockItemSummary { $balance = (int) $model->getAttribute('balance_milli'); return new StockItemSummary( id: $model->id, groupId: $model->stock_item_group_id, groupName: (string) $model->getAttribute('group_name'), name: $model->name, unit: $model->unit, code: $model->code, supplier: $model->supplier, reorderLevelMilli: $model->reorder_level_milli, balanceMilli: $balance, averageCostHundredths: $model->average_cost_hundredths, valueCents: StockValuation::valueCents($balance, $model->average_cost_hundredths), hasImage: $model->thumbnail_path !== null, isActive: $model->is_active, ); } /** * @param Collection $models Newest first. * @param int $balance The balance after the newest of them. * @return list */ private function summaries(Collection $models, int $balance): array { $names = $this->users->namesByIds($models->pluck('user_id')->unique()->values()->all()); $summaries = []; foreach ($models as $model) { $summaries[] = new StockMovementSummary( id: $model->id, itemId: $model->stock_item_id, kind: $model->kind, quantityMilli: $model->quantity_milli, balanceAfterMilli: $balance, valueCents: $model->value_cents, occurredOn: $model->occurred_on->format('Y-m-d'), recordedAt: Carbon::instance($model->recorded_at)->setTimezone((string) config('app.business_timezone'))->format('Y-m-d H:i'), userId: $model->user_id, userName: $names[$model->user_id] ?? '', taskId: $model->task_id, jobId: $model->customer_job_id, machineId: $model->machine_id, orderLineId: $model->quick_sale_order_line_id, maintenanceRecordId: $model->maintenance_record_id, inventoryCountId: $model->inventory_count_id, reason: $model->reason, supplier: $model->supplier, documentNumber: $model->document_number, reversesMovementId: $model->reverses_movement_id, reversedByMovementId: $model->reversal?->id, ); $balance -= $model->quantity_milli; } return $summaries; } }