Files
trackbugs/app/Http/Controllers/DashboardController.php
2026-03-19 19:40:49 +02:00

70 lines
2.1 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Event;
use App\Models\Issue;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class DashboardController extends Controller
{
public function __invoke(Request $request): View
{
$user = $request->user();
$projectIds = $user->projects()->pluck('projects.id');
$unresolvedCount = Issue::whereIn('project_id', $projectIds)
->where('status', 'unresolved')
->count();
$events24h = Event::whereIn('project_id', $projectIds)
->where('created_at', '>=', Carbon::now()->subDay())
->count();
$mostActiveProjects = $user->projects()
->withCount(['issues' => fn ($q) => $q->where('status', 'unresolved')])
->withCount(['events' => fn ($q) => $q->where('events.created_at', '>=', Carbon::now()->subDay())])
->orderByDesc('events_count')
->limit(5)
->get();
$days = (int) $request->query('days', 14);
$eventsOverTime = $this->getEventsOverTime($projectIds, $days);
return view('dashboard', [
'unresolvedCount' => $unresolvedCount,
'events24h' => $events24h,
'mostActiveProjects' => $mostActiveProjects,
'eventsOverTime' => $eventsOverTime,
'days' => $days,
]);
}
private function getEventsOverTime($projectIds, int $days): array
{
$since = Carbon::now()->subDays($days)->startOfDay();
$rows = Event::whereIn('project_id', $projectIds)
->where('created_at', '>=', $since)
->select(DB::raw('DATE(created_at) as date'), DB::raw('COUNT(*) as count'))
->groupBy('date')
->orderBy('date')
->pluck('count', 'date')
->toArray();
$result = [];
for ($i = $days - 1; $i >= 0; $i--) {
$date = Carbon::now()->subDays($i)->format('Y-m-d');
$result[] = [
'date' => $date,
'count' => $rows[$date] ?? 0,
];
}
return $result;
}
}