diff --git a/plataforma-tutorias/app/Http/Controllers/AuthController.php b/plataforma-tutorias/app/Http/Controllers/AuthController.php index c3a965f..a651604 100644 --- a/plataforma-tutorias/app/Http/Controllers/AuthController.php +++ b/plataforma-tutorias/app/Http/Controllers/AuthController.php @@ -70,7 +70,6 @@ class AuthController extends Controller "name" => $user->name, "email" => $user->email, "role_id" => $user->role_id, - "password" => $user->password, "created_at" => $user->created_at, ], ]); @@ -104,20 +103,28 @@ class AuthController extends Controller public function me() { $user = auth()->user(); - $videosWatched = Video::select('id') - ->with('views') - ->whereHas('views', function ($q) use ($user) { - $q->where('user_id', $user->id); - })->count(); - $videosCount = Video::select('id')->where('is_active', true)->count(); + $userId = $user->id; + $role = $user->role_id; + + if ($role !== 1) { + $stats = Video::selectRaw(' + COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count, + COUNT(CASE WHEN is_active = 1 AND EXISTS ( + SELECT 1 FROM video_views + WHERE video_views.video_id = videos.id + AND video_views.user_id = ? + ) THEN 1 END) as watched_count + ', [$userId]) + ->first(); + } return response()->json([ 'message' => 'Utilizador obtido com sucesso', 'data' => [ 'id' => $user->id, 'role_id' => $user->role_id, - 'videosWatched' => $videosWatched, - 'videosCount' => $videosCount, + 'videosWatched' => $stats->watched_count ?? 0, + 'videosCount' => $stats->active_count ?? 0, ], 'errors' => null, ], 200); diff --git a/plataforma-tutorias/app/Http/Controllers/DashboardController.php b/plataforma-tutorias/app/Http/Controllers/DashboardController.php index 4612915..1e60dbf 100644 --- a/plataforma-tutorias/app/Http/Controllers/DashboardController.php +++ b/plataforma-tutorias/app/Http/Controllers/DashboardController.php @@ -23,7 +23,6 @@ class DashboardController extends Controller $userId = $user->id; $role = $user->role_id; - $videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order') ->where('is_active', true) ->whereDoesntHave('views', function ($q) use ($user) { @@ -42,13 +41,19 @@ class DashboardController extends Controller ]; }); - $videosCount = Video::select('id')->where('is_active', true)->count(); - - $videosWatched = Video::select('id') - ->where('is_active', true) - ->whereHas('views', function ($query) use ($user) { - $query->where('user_id', $user->id); - })->count(); + if ($role === 1) { + $stats = Video::selectRaw('COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count')->first(); + } else { + $stats = Video::selectRaw(' + COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count, + COUNT(CASE WHEN is_active = 1 AND EXISTS ( + SELECT 1 FROM video_views + WHERE video_views.video_id = videos.id + AND video_views.user_id = ? + ) THEN 1 END) as watched_count + ', [$userId]) + ->first(); + } $workshops = Workshop::select(['id', 'title', 'image', 'date', 'time_start', 'time_end', 'status']) ->with(['users:id']) @@ -70,21 +75,27 @@ class DashboardController extends Controller ]; }); - $workshopsInscribed = Workshop::select('id') - ->where('status', 'pending') - ->whereHas('users', function ($query) use ($user) { - $query->where('user_id', $user->id); - })->count(); - - $workshopsCount = Workshop::select('id')->where('status', 'pending')->count(); + if ($role === 1) { + $workshopsCount = Workshop::selectRaw('COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count')->first(); + } else { + $workshopsCount = Workshop::selectRaw(' + COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count, + COUNT(CASE WHEN status = \'pending\' AND EXISTS ( + SELECT 1 FROM user_workshop + WHERE user_workshop.workshop_id = workshops.id + AND user_workshop.user_id = ? + ) THEN 1 END) as workshops_inscribed + ', [$userId]) + ->first(); + } return response()->json([ 'videos' => $videos, - 'videosWatched' => $videosWatched, - 'videosCount' => $videosCount, + 'videosWatched' => $stats->watched_count ?? 0, + 'videosCount' => $stats->active_count ?? 0, 'workshops' => $workshops, - 'workshopsCount' => $workshopsCount, - 'workshopsInscribed' => $workshopsInscribed, + 'workshopsCount' => $workshopsCount->workshops_count ?? 0, + 'workshopsInscribed' => $workshopsCount->workshops_inscribed ?? 0, 'userId' => $userId, 'role' => $role, ], 200); diff --git a/plataforma-tutorias/app/Http/Controllers/VideosController.php b/plataforma-tutorias/app/Http/Controllers/VideosController.php index cf2cffa..cec0487 100644 --- a/plataforma-tutorias/app/Http/Controllers/VideosController.php +++ b/plataforma-tutorias/app/Http/Controllers/VideosController.php @@ -40,15 +40,13 @@ class VideosController extends Controller $search = trim((string) $request->query('search', '')); $categoryId = $request->query('category'); $watched = $request->query('watched'); + $status = $request->query('status'); $perPage = $request->query('per_page', 9); $query = Video::select(['id', 'title', 'thumbnail', 'is_active']) - ->with([ - 'categories:id,name', - 'views' => function ($q) use ($user) { - $q->select('id', 'video_id', 'user_id') - ->where('user_id', $user->id); - } + ->with('categories:id,name') + ->withCount([ + 'views as watched' => fn($q) => $q->where('user_id', $userId) ]) ->when($search !== '', function ($q) use ($search) { @@ -64,45 +62,48 @@ class VideosController extends Controller }); }) - ->when($user->role_id !== 1, function ($q) { - $q->where('is_active', true); + ->when($role !== 1, fn($q) => $q->where('is_active', true)) + + ->when( + $role === 1 && $status === 'active', + fn($q) => + $q->where('is_active', true) + ) + + ->when( + $role === 1 && $status === 'inactive', + fn($q) => + $q->where('is_active', false) + ) + + ->when($watched !== null, function ($q) use ($watched, $userId) { + (int) $watched === 1 + ? $q->whereHas('views', fn($v) => $v->where('user_id', $userId)) + : $q->whereDoesntHave('views', fn($v) => $v->where('user_id', $userId)); }) - ->when($watched !== null, function ($q) use ($watched, $user) { - - if ((int) $watched === 1) { - $q->whereHas('views', function ($v) use ($user) { - $v->where('user_id', $user->id); - }); - } - - if ((int) $watched === 0) { - $q->whereDoesntHave('views', function ($v) use ($user) { - $v->where('user_id', $user->id); - }); - } + // left join para trazer os vídeos vistos pelo utilizador + ->leftJoin('video_views as vv', function ($join) use ($userId) { + $join->on('vv.video_id', '=', 'videos.id') + ->where('vv.user_id', '=', $userId); }) - ->orderByRaw(' - CASE WHEN EXISTS ( - SELECT 1 FROM video_views - WHERE video_views.video_id = videos.id - AND video_views.user_id = ? - ) THEN 1 ELSE 0 END ASC, - videos.order ASC - ', [$user->id]) + ->orderByRaw('CASE WHEN vv.id IS NOT NULL THEN 1 ELSE 0 END ASC') + ->orderBy('videos.order', 'ASC') + ->select(['videos.id', 'videos.title', 'videos.thumbnail', 'videos.is_active']) + ->paginate($perPage); - $videosActive = Video::select('id') - ->where('is_active', true) - ->count(); - - $videosWatched = Video::select('id') - ->where('is_active', true) - ->whereHas('views', function ($q) use ($user) { - $q->where('user_id', $user->id); - }) - ->count(); + // 1 única query para obter o número de vídeos ativos e vistos + $stats = Video::selectRaw(' + COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count, + COUNT(CASE WHEN is_active = 1 AND EXISTS ( + SELECT 1 FROM video_views + WHERE video_views.video_id = videos.id + AND video_views.user_id = ? + ) THEN 1 END) as watched_count + ', [$userId]) + ->first(); $query->getCollection()->transform(function ($video) { return [ @@ -115,11 +116,17 @@ class VideosController extends Controller ]; }); - $categories = Category::select('id', 'name') - ->where('is_active', true) - ->whereHas('videos') - ->orderBy('name', 'asc') - ->get(); + // Guarda as categorias em cache durante 1 minuto para evitar consultas repetidas + $categories = cache()->remember( + 'active_categories_with_videos', + 60, + fn() => + Category::select('id', 'name') + ->where('is_active', true) + ->whereHas('videos') + ->orderBy('name') + ->get() + ); return response()->json([ 'message' => 'Vídeos obtidos com sucesso', @@ -133,55 +140,11 @@ class VideosController extends Controller 'userId' => $userId, 'role' => $role, 'categories' => $categories, - 'videosActive' => $videosActive, - 'videosWatched' => $videosWatched, + 'videosActive' => $stats->active_count, + 'videosWatched' => $stats->watched_count ?? 0, ]); } - public function nextVideos() - { - $user = auth()->user(); - - if (!$user) { - return response()->json([ - 'message' => 'Não autenticado', - ], 401); - } - - $videos = Video::select(['id', 'title', 'thumbnail', 'is_active', 'order']) - ->with(['categories:id,name']) - - // 👇 regra base: vídeos não vistos - ->whereDoesntHave('views', function ($q) use ($user) { - $q->where('user_id', $user->id); - }) - - // 👇 users normais não veem inativos - ->when($user->role_id !== 1, function ($q) { - $q->where('is_active', true); - }) - - ->orderBy('order', 'asc') - ->limit(3) - ->get() - ->map(function ($video) { - return [ - 'id' => $video->id, - 'title' => $video->title, - 'thumbnail' => $video->thumbnail, - 'is_active' => $video->is_active, - 'categories' => $video->categories, - 'watched' => false, // aqui já sabes que não foram vistos - ]; - }); - - return response()->json([ - 'message' => 'Dashboard videos', - 'data' => $videos, - ]); - } - - public function search(Request $request) { $user = auth()->user(); @@ -222,30 +185,6 @@ class VideosController extends Controller ]); } - public function videosLength() - { - $user = auth()->user(); - $userID = $user->id; - - if ($user->role_id !== 1) { - $videos = Video::select('id')->with('views')->where('is_active', true)->count(); - $videosWatched = Video::with('views')->where('is_active', true)->whereHas('views', function ($query) use ($userID) { - $query->where('user_id', $userID); - })->count(); - } else { - $videos = Video::select('id')->with('views')->where('is_active', true)->count(); - } - - return response()->json([ - 'message' => 'Vídeos ativos obtidos com sucesso', - 'data' => [ - 'videos' => $videos, - 'videosWatched' => $videosWatched ?? 0, - ], - 'errors' => null, - ], 200); - } - public function getVideo($id) { $user = auth()->user(); @@ -286,7 +225,6 @@ class VideosController extends Controller $video = Video::with('categories')->find($id); - if ($video) { $video->url = Storage::url($video->url); $video->thumbnail = Storage::url($video->thumbnail); diff --git a/plataforma-tutorias/app/Http/Controllers/WorkshopsController.php b/plataforma-tutorias/app/Http/Controllers/WorkshopsController.php index f03f658..458017e 100644 --- a/plataforma-tutorias/app/Http/Controllers/WorkshopsController.php +++ b/plataforma-tutorias/app/Http/Controllers/WorkshopsController.php @@ -115,69 +115,6 @@ class WorkshopsController extends Controller ]); } - public function workshopsLength() - { - $user = auth()->user(); - $userID = $user->id; - - if ($user->role_id !== 1) { - $workshops = Workshop::select('id')->where('status', 'pending')->count(); - $workshopsInscribed = Workshop::with('users')->where('status', 'pending')->whereHas('users', function ($query) use ($userID) { - $query->where('user_id', $userID); - })->count(); - } else { - $workshops = Workshop::select('id')->where('status', 'pending')->count(); - } - - return response()->json([ - 'message' => 'Vídeos ativos obtidos com sucesso', - 'data' => [ - 'workshops' => $workshops, - 'workshopsInscribed' => $workshopsInscribed ?? 0, - ], - 'errors' => null, - ], 200); - } - - public function nextWorkshops() - { - $user = auth()->user(); - - if (!$user) { - return response()->json([ - 'message' => 'Não autenticado', - ], 401); - } - - $role = $user->role_id; - - $workshops = Workshop::select(['id', 'title', 'image', 'date', 'time_start', 'time_end', 'status']) - ->with(['users:id']) - ->where('status', 'pending') - ->orderBy('date', 'asc') - ->orderBy('time_start', 'asc') - ->limit(3) - ->get() - ->map(function ($workshop) { - return [ - 'id' => $workshop->id, - 'title' => $workshop->title, - 'image' => $workshop->image, - 'date' => $workshop->date, - 'time_start' => $workshop->time_start, - 'time_end' => $workshop->time_end, - 'status' => $workshop->status, - 'users' => $workshop->users->pluck('id'), - ]; - }); - - return response()->json([ - 'message' => 'Dashboard workshops', - 'data' => $workshops, - 'role' => $role, - ]); - } - public function getWorkshop($id) { $workshop = Workshop::with('users')->find($id); diff --git a/plataforma-tutorias/config/cors.php b/plataforma-tutorias/config/cors.php index d76dfca..d4591cd 100644 --- a/plataforma-tutorias/config/cors.php +++ b/plataforma-tutorias/config/cors.php @@ -34,6 +34,6 @@ return [ 'max_age' => 0, - 'supports_credentials' => false, + 'supports_credentials' => true, ]; diff --git a/plataforma-tutorias/config/jwt.php b/plataforma-tutorias/config/jwt.php index 3d9eda3..5ce9856 100644 --- a/plataforma-tutorias/config/jwt.php +++ b/plataforma-tutorias/config/jwt.php @@ -101,7 +101,7 @@ return [ | */ - 'ttl' => env('JWT_TTL', 1440), + 'ttl' => env('JWT_TTL', 15), /* |-------------------------------------------------------------------------- diff --git a/plataforma-tutorias/database/migrations/2026_06_02_113520_create_refresh_tokens.php b/plataforma-tutorias/database/migrations/2026_06_02_113520_create_refresh_tokens.php new file mode 100644 index 0000000..04bda36 --- /dev/null +++ b/plataforma-tutorias/database/migrations/2026_06_02_113520_create_refresh_tokens.php @@ -0,0 +1,31 @@ +id(); + $table->foreignId('user_id')->constrained('users'); + $table->string('token_hash'); + $table->dateTime('revoked_at')->nullable(); + $table->dateTime('expires_at'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('refresh_tokens'); + } +}; diff --git a/plataforma-tutorias/routes/api.php b/plataforma-tutorias/routes/api.php index 125e539..1e1f05b 100644 --- a/plataforma-tutorias/routes/api.php +++ b/plataforma-tutorias/routes/api.php @@ -24,10 +24,10 @@ use App\Http\Controllers\DashboardController; Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); -Route::post('/refresh', [AuthController::class, 'refresh']); Route::post('/contact', [ContactController::class, 'send']); //proteção da rota no ficheiro index da página de contactos Route::middleware([JwtMiddleware::class])->group(function () { + Route::post('/refresh', [AuthController::class, 'refresh']); /* Rota protegida por middleware JwtMiddleware - Só os utilizadores autenticados podem aceder a esta rota */ Route::patch('/profile/{id}', [UserController::class, 'update']); Route::get('/profile', [UserController::class, 'profile']);