join('billing_invoices', 'billing_invoices.id', '=', 'billing_lines.billing_invoice_id') ->join('billing_exports', 'billing_exports.id', '=', 'billing_invoices.billing_export_id') ->where('billing_exports.status', ExportStatus::Created->value) // Materials created before billing months existed have none: their month is the month they were created in, as in the export repository. ->whereRaw('COALESCE(billing_exports.period, SUBSTR(billing_exports.created_at, 1, 7)) BETWEEN ? AND ?', [$fromMonth, $toMonth]) ->groupBy('billing_lines.customer_job_id') ->select('billing_lines.customer_job_id') ->selectRaw(self::sumOf(LineKind::Hours, 'net_cents').' as hours_cents') ->selectRaw(self::sumOf(LineKind::FixedPrice, 'net_cents').' as fixed_cents') ->selectRaw(self::sumOf(LineKind::MonthlyFee, 'net_cents').' as monthly_cents') ->selectRaw(self::sumOf(LineKind::Expense, 'net_cents').' as expense_cents') ->selectRaw(self::sumOf(LineKind::Hours, 'quantity_quarters').' as billed_quarters') ->get(); $result = []; foreach ($rows as $row) { $jobId = (int) $row->customer_job_id; $result[$jobId] = new BilledJobRevenue( $jobId, (int) $row->hours_cents, (int) $row->fixed_cents, (int) $row->monthly_cents, (int) $row->expense_cents, (int) $row->billed_quarters, ); } return $result; } private static function sumOf(LineKind $kind, string $column): string { return "SUM(CASE WHEN billing_lines.kind = '{$kind->value}' THEN COALESCE(billing_lines.{$column}, 0) ELSE 0 END)"; } }