summaries(ExpenseModel::query()->where('customer_job_id', $jobId)); } public function forUserInMonth(int $userId, string $month): array { if (preg_match('/^\d{4}-(0[1-9]|1[0-2])$/', $month) !== 1) { return []; } $start = Carbon::createFromFormat('!Y-m', $month); return $this->summaries(ExpenseModel::query() ->where('user_id', $userId) ->whereBetween('spent_on', [$start->toDateString(), $start->copy()->endOfMonth()->toDateString()])); } public function find(int $id): ?ExpenseSummary { return $this->summaries(ExpenseModel::query()->whereKey($id))[0] ?? null; } /** * @param Builder $query * @return list */ private function summaries(Builder $query): array { /** @var Collection $models */ $models = $query->orderByDesc('spent_on')->orderByDesc('id')->get(); if ($models->isEmpty()) { return []; } $jobs = $this->jobs->findMany($models->pluck('customer_job_id')->unique()->values()->all()); $names = $this->users->namesByIds($models->pluck('user_id')->merge($models->pluck('recorded_by'))->unique()->values()->all()); return $models ->map(fn (ExpenseModel $model): ExpenseSummary => new ExpenseSummary( $model->id, $jobs[$model->customer_job_id] ?? new ExpenseJob($model->customer_job_id, '', '', true), $model->user_id, $names[$model->user_id] ?? '', $model->recorded_by, $names[$model->recorded_by] ?? '', $model->category, $model->paid_by, $model->spent_on->toDateString(), $model->description, $model->cost_cents, $model->kilometers === null ? null : (int) round((float) $model->kilometers * 10), $model->destination, $model->purpose, $model->is_billable, $model->markup_basis_points, $model->billed_amount_cents, )) ->values() ->all(); } }