withCount('invoices')->orderByDesc('id')->get(); if ($models->isEmpty()) { return []; } $ids = $models->pluck('id')->all(); $jobCounts = BillingInvoiceJobModel::query() ->join('billing_invoices', 'billing_invoices.id', '=', 'billing_invoice_jobs.billing_invoice_id') ->whereIn('billing_invoices.billing_export_id', $ids) ->groupBy('billing_invoices.billing_export_id') ->selectRaw('billing_invoices.billing_export_id as export_id, count(*) as job_count') ->pluck('job_count', 'export_id'); $netSums = BillingLineModel::query() ->join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id') ->whereIn('billing_invoices.billing_export_id', $ids) ->groupBy('billing_invoices.billing_export_id') ->selectRaw('billing_invoices.billing_export_id as export_id, sum(billing_lines.net_cents) as net_cents') ->pluck('net_cents', 'export_id'); $names = $this->users->namesByIds($models->pluck('created_by')->merge($models->pluck('finalized_by'))->filter()->unique()->values()->all()); return $models->map(fn (BillingExportModel $model): ExportSummary => new ExportSummary( $model->id, $model->number, $model->status, DateTimeImmutable::createFromInterface($model->created_at), $names[$model->created_by] ?? '', $model->finalized_at === null ? null : DateTimeImmutable::createFromInterface($model->finalized_at), $model->finalized_by === null ? null : ($names[$model->finalized_by] ?? ''), (int) $model->getAttribute('invoices_count'), (int) ($jobCounts[$model->id] ?? 0), $model->status === ExportStatus::Created ? (int) ($netSums[$model->id] ?? 0) : null, ))->values()->all(); } }