fix: videos/workshops query optmization
This commit is contained in:
@@ -70,7 +70,6 @@ class AuthController extends Controller
|
|||||||
"name" => $user->name,
|
"name" => $user->name,
|
||||||
"email" => $user->email,
|
"email" => $user->email,
|
||||||
"role_id" => $user->role_id,
|
"role_id" => $user->role_id,
|
||||||
"password" => $user->password,
|
|
||||||
"created_at" => $user->created_at,
|
"created_at" => $user->created_at,
|
||||||
],
|
],
|
||||||
]);
|
]);
|
||||||
@@ -104,20 +103,28 @@ class AuthController extends Controller
|
|||||||
public function me()
|
public function me()
|
||||||
{
|
{
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
$videosWatched = Video::select('id')
|
$userId = $user->id;
|
||||||
->with('views')
|
$role = $user->role_id;
|
||||||
->whereHas('views', function ($q) use ($user) {
|
|
||||||
$q->where('user_id', $user->id);
|
if ($role !== 1) {
|
||||||
})->count();
|
$stats = Video::selectRaw('
|
||||||
$videosCount = Video::select('id')->where('is_active', true)->count();
|
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([
|
return response()->json([
|
||||||
'message' => 'Utilizador obtido com sucesso',
|
'message' => 'Utilizador obtido com sucesso',
|
||||||
'data' => [
|
'data' => [
|
||||||
'id' => $user->id,
|
'id' => $user->id,
|
||||||
'role_id' => $user->role_id,
|
'role_id' => $user->role_id,
|
||||||
'videosWatched' => $videosWatched,
|
'videosWatched' => $stats->watched_count ?? 0,
|
||||||
'videosCount' => $videosCount,
|
'videosCount' => $stats->active_count ?? 0,
|
||||||
],
|
],
|
||||||
'errors' => null,
|
'errors' => null,
|
||||||
], 200);
|
], 200);
|
||||||
|
|||||||
@@ -23,7 +23,6 @@ class DashboardController extends Controller
|
|||||||
$userId = $user->id;
|
$userId = $user->id;
|
||||||
$role = $user->role_id;
|
$role = $user->role_id;
|
||||||
|
|
||||||
|
|
||||||
$videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')
|
$videos = Video::select('id', 'title', 'thumbnail', 'is_active', 'order')
|
||||||
->where('is_active', true)
|
->where('is_active', true)
|
||||||
->whereDoesntHave('views', function ($q) use ($user) {
|
->whereDoesntHave('views', function ($q) use ($user) {
|
||||||
@@ -42,13 +41,19 @@ class DashboardController extends Controller
|
|||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
$videosCount = Video::select('id')->where('is_active', true)->count();
|
if ($role === 1) {
|
||||||
|
$stats = Video::selectRaw('COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count')->first();
|
||||||
$videosWatched = Video::select('id')
|
} else {
|
||||||
->where('is_active', true)
|
$stats = Video::selectRaw('
|
||||||
->whereHas('views', function ($query) use ($user) {
|
COUNT(CASE WHEN is_active = 1 THEN 1 END) as active_count,
|
||||||
$query->where('user_id', $user->id);
|
COUNT(CASE WHEN is_active = 1 AND EXISTS (
|
||||||
})->count();
|
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'])
|
$workshops = Workshop::select(['id', 'title', 'image', 'date', 'time_start', 'time_end', 'status'])
|
||||||
->with(['users:id'])
|
->with(['users:id'])
|
||||||
@@ -70,21 +75,27 @@ class DashboardController extends Controller
|
|||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
$workshopsInscribed = Workshop::select('id')
|
if ($role === 1) {
|
||||||
->where('status', 'pending')
|
$workshopsCount = Workshop::selectRaw('COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count')->first();
|
||||||
->whereHas('users', function ($query) use ($user) {
|
} else {
|
||||||
$query->where('user_id', $user->id);
|
$workshopsCount = Workshop::selectRaw('
|
||||||
})->count();
|
COUNT(CASE WHEN status = \'pending\' THEN 1 END) as workshops_count,
|
||||||
|
COUNT(CASE WHEN status = \'pending\' AND EXISTS (
|
||||||
$workshopsCount = Workshop::select('id')->where('status', 'pending')->count();
|
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([
|
return response()->json([
|
||||||
'videos' => $videos,
|
'videos' => $videos,
|
||||||
'videosWatched' => $videosWatched,
|
'videosWatched' => $stats->watched_count ?? 0,
|
||||||
'videosCount' => $videosCount,
|
'videosCount' => $stats->active_count ?? 0,
|
||||||
'workshops' => $workshops,
|
'workshops' => $workshops,
|
||||||
'workshopsCount' => $workshopsCount,
|
'workshopsCount' => $workshopsCount->workshops_count ?? 0,
|
||||||
'workshopsInscribed' => $workshopsInscribed,
|
'workshopsInscribed' => $workshopsCount->workshops_inscribed ?? 0,
|
||||||
'userId' => $userId,
|
'userId' => $userId,
|
||||||
'role' => $role,
|
'role' => $role,
|
||||||
], 200);
|
], 200);
|
||||||
|
|||||||
@@ -40,15 +40,13 @@ class VideosController extends Controller
|
|||||||
$search = trim((string) $request->query('search', ''));
|
$search = trim((string) $request->query('search', ''));
|
||||||
$categoryId = $request->query('category');
|
$categoryId = $request->query('category');
|
||||||
$watched = $request->query('watched');
|
$watched = $request->query('watched');
|
||||||
|
$status = $request->query('status');
|
||||||
$perPage = $request->query('per_page', 9);
|
$perPage = $request->query('per_page', 9);
|
||||||
|
|
||||||
$query = Video::select(['id', 'title', 'thumbnail', 'is_active'])
|
$query = Video::select(['id', 'title', 'thumbnail', 'is_active'])
|
||||||
->with([
|
->with('categories:id,name')
|
||||||
'categories:id,name',
|
->withCount([
|
||||||
'views' => function ($q) use ($user) {
|
'views as watched' => fn($q) => $q->where('user_id', $userId)
|
||||||
$q->select('id', 'video_id', 'user_id')
|
|
||||||
->where('user_id', $user->id);
|
|
||||||
}
|
|
||||||
])
|
])
|
||||||
|
|
||||||
->when($search !== '', function ($q) use ($search) {
|
->when($search !== '', function ($q) use ($search) {
|
||||||
@@ -64,45 +62,48 @@ class VideosController extends Controller
|
|||||||
});
|
});
|
||||||
})
|
})
|
||||||
|
|
||||||
->when($user->role_id !== 1, function ($q) {
|
->when($role !== 1, fn($q) => $q->where('is_active', true))
|
||||||
$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) {
|
// left join para trazer os vídeos vistos pelo utilizador
|
||||||
|
->leftJoin('video_views as vv', function ($join) use ($userId) {
|
||||||
if ((int) $watched === 1) {
|
$join->on('vv.video_id', '=', 'videos.id')
|
||||||
$q->whereHas('views', function ($v) use ($user) {
|
->where('vv.user_id', '=', $userId);
|
||||||
$v->where('user_id', $user->id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if ((int) $watched === 0) {
|
|
||||||
$q->whereDoesntHave('views', function ($v) use ($user) {
|
|
||||||
$v->where('user_id', $user->id);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
|
|
||||||
->orderByRaw('
|
->orderByRaw('CASE WHEN vv.id IS NOT NULL THEN 1 ELSE 0 END ASC')
|
||||||
CASE WHEN EXISTS (
|
->orderBy('videos.order', 'ASC')
|
||||||
|
->select(['videos.id', 'videos.title', 'videos.thumbnail', 'videos.is_active'])
|
||||||
|
|
||||||
|
->paginate($perPage);
|
||||||
|
|
||||||
|
// 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
|
SELECT 1 FROM video_views
|
||||||
WHERE video_views.video_id = videos.id
|
WHERE video_views.video_id = videos.id
|
||||||
AND video_views.user_id = ?
|
AND video_views.user_id = ?
|
||||||
) THEN 1 ELSE 0 END ASC,
|
) THEN 1 END) as watched_count
|
||||||
videos.order ASC
|
', [$userId])
|
||||||
', [$user->id])
|
->first();
|
||||||
->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();
|
|
||||||
|
|
||||||
$query->getCollection()->transform(function ($video) {
|
$query->getCollection()->transform(function ($video) {
|
||||||
return [
|
return [
|
||||||
@@ -115,11 +116,17 @@ class VideosController extends Controller
|
|||||||
];
|
];
|
||||||
});
|
});
|
||||||
|
|
||||||
$categories = Category::select('id', 'name')
|
// 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)
|
->where('is_active', true)
|
||||||
->whereHas('videos')
|
->whereHas('videos')
|
||||||
->orderBy('name', 'asc')
|
->orderBy('name')
|
||||||
->get();
|
->get()
|
||||||
|
);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
'message' => 'Vídeos obtidos com sucesso',
|
'message' => 'Vídeos obtidos com sucesso',
|
||||||
@@ -133,55 +140,11 @@ class VideosController extends Controller
|
|||||||
'userId' => $userId,
|
'userId' => $userId,
|
||||||
'role' => $role,
|
'role' => $role,
|
||||||
'categories' => $categories,
|
'categories' => $categories,
|
||||||
'videosActive' => $videosActive,
|
'videosActive' => $stats->active_count,
|
||||||
'videosWatched' => $videosWatched,
|
'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)
|
public function search(Request $request)
|
||||||
{
|
{
|
||||||
$user = auth()->user();
|
$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)
|
public function getVideo($id)
|
||||||
{
|
{
|
||||||
$user = auth()->user();
|
$user = auth()->user();
|
||||||
@@ -286,7 +225,6 @@ class VideosController extends Controller
|
|||||||
|
|
||||||
$video = Video::with('categories')->find($id);
|
$video = Video::with('categories')->find($id);
|
||||||
|
|
||||||
|
|
||||||
if ($video) {
|
if ($video) {
|
||||||
$video->url = Storage::url($video->url);
|
$video->url = Storage::url($video->url);
|
||||||
$video->thumbnail = Storage::url($video->thumbnail);
|
$video->thumbnail = Storage::url($video->thumbnail);
|
||||||
|
|||||||
@@ -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)
|
public function getWorkshop($id)
|
||||||
{
|
{
|
||||||
$workshop = Workshop::with('users')->find($id);
|
$workshop = Workshop::with('users')->find($id);
|
||||||
|
|||||||
@@ -34,6 +34,6 @@ return [
|
|||||||
|
|
||||||
'max_age' => 0,
|
'max_age' => 0,
|
||||||
|
|
||||||
'supports_credentials' => false,
|
'supports_credentials' => true,
|
||||||
|
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -101,7 +101,7 @@ return [
|
|||||||
|
|
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
'ttl' => env('JWT_TTL', 1440),
|
'ttl' => env('JWT_TTL', 15),
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|--------------------------------------------------------------------------
|
|--------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('refresh_tokens', function (Blueprint $table) {
|
||||||
|
$table->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');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -24,10 +24,10 @@ use App\Http\Controllers\DashboardController;
|
|||||||
|
|
||||||
Route::post('/register', [AuthController::class, 'register']);
|
Route::post('/register', [AuthController::class, 'register']);
|
||||||
Route::post('/login', [AuthController::class, 'login']);
|
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::post('/contact', [ContactController::class, 'send']); //proteção da rota no ficheiro index da página de contactos
|
||||||
|
|
||||||
Route::middleware([JwtMiddleware::class])->group(function () {
|
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 */
|
/* Rota protegida por middleware JwtMiddleware - Só os utilizadores autenticados podem aceder a esta rota */
|
||||||
Route::patch('/profile/{id}', [UserController::class, 'update']);
|
Route::patch('/profile/{id}', [UserController::class, 'update']);
|
||||||
Route::get('/profile', [UserController::class, 'profile']);
|
Route::get('/profile', [UserController::class, 'profile']);
|
||||||
|
|||||||
Reference in New Issue
Block a user