where('worked_on', '>=', $from) ->where('worked_on', '<', self::dayAfter($to)) ->groupBy('user_id', 'customer_job_id', 'work_type_id') ->orderBy('user_id') ->select('user_id', 'customer_job_id', 'work_type_id') ->selectRaw('SUM(hours) * 4 as quarters') ->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN hours ELSE 0 END) * 4 as unapproved_quarters') ->selectRaw('SUM(CASE WHEN billing_export_id IS NULL THEN 0 ELSE hours END) * 4 as billed_quarters') ->get() ->map(fn (object $row): ReportedHours => new ReportedHours( (int) $row->user_id, (int) $row->customer_job_id, (int) $row->work_type_id, (int) round((float) $row->quarters), (int) round((float) $row->unapproved_quarters), (int) round((float) $row->billed_quarters), )) ->all(); } public function unbilledUntil(string $day): array { return DB::table('time_entries') ->whereNull('billing_export_id') ->where('worked_on', '<', self::dayAfter($day)) ->groupBy('customer_job_id', 'work_type_id') ->orderBy('customer_job_id') ->select('customer_job_id', 'work_type_id') ->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN 0 ELSE hours END) * 4 as approved_quarters') ->selectRaw('SUM(CASE WHEN approved_at IS NULL THEN hours ELSE 0 END) * 4 as unapproved_quarters') ->selectRaw('MIN(worked_on) as oldest_day') ->get() ->map(fn (object $row): UnbilledHours => new UnbilledHours( (int) $row->customer_job_id, (int) $row->work_type_id, (int) round((float) $row->approved_quarters), (int) round((float) $row->unapproved_quarters), substr((string) $row->oldest_day, 0, 10), )) ->all(); } /** * Days may be stored with a time, so a period ends before the next day. */ private static function dayAfter(string $day): string { return (new DateTimeImmutable($day))->modify('+1 day')->format('Y-m-d'); } }