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(); } public function billedMonthsOf(int $jobId): array { return BillingLineModel::query() ->join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id') ->join('billing_exports', 'billing_exports.id', '=', 'billing_invoices.billing_export_id') ->where('billing_lines.customer_job_id', $jobId) ->where('billing_lines.kind', LineKind::MonthlyFee) ->whereNotNull('billing_lines.period') ->where('billing_exports.status', ExportStatus::Created) ->orderBy('billing_lines.period') ->get([ 'billing_lines.period', 'billing_lines.net_cents', 'billing_exports.id as export_id', 'billing_exports.number as export_number', 'billing_exports.finalized_at', ]) ->map(fn (BillingLineModel $line): BilledMonth => new BilledMonth( (string) $line->getAttribute('period'), (int) $line->getAttribute('export_id'), (int) $line->getAttribute('export_number'), $line->getAttribute('finalized_at') === null ? null : new DateTimeImmutable((string) $line->getAttribute('finalized_at'), new DateTimeZone('UTC')), $line->net_cents, )) ->values() ->all(); } }