From 0d76c40980b762eac24478488488ef157d46a3ad Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Wed, 15 Oct 2025 13:42:07 +0100 Subject: [PATCH] feat: Import Users module from old CRM - Copy complete Users module from CRM_Project - Fix syntax error in UserController.php (trailing whitespace) - Add admin users management functionality - Include user profiles, roles, and permissions - Add API endpoints for user management --- .../Users/Controllers/UserController.php | 919 ++++++++++++++++++ crm/Modules/Users/Models/UserModel.php | 266 +++++ crm/Modules/Users/Module.php | 39 + crm/Modules/Users/Routes/api.php | 34 + crm/Modules/Users/Routes/web.php | 81 ++ crm/Modules/Users/Views/admin-roles.php | 436 +++++++++ crm/Modules/Users/Views/admin-users.php | 393 ++++++++ crm/Modules/Users/Views/dashboard.php | 293 ++++++ crm/Modules/Users/Views/user-edit.php | 364 +++++++ crm/Modules/Users/Views/user-permissions.php | 70 ++ crm/Modules/Users/Views/user-profile.php | 342 +++++++ crm/Modules/Users/Views/user-settings.php | 81 ++ crm/Modules/Users/Views/user-view.php | 317 ++++++ .../Users/Widgets/UserActivityWidget.php | 199 ++++ crm/Modules/Users/menu.php | 35 + crm/Modules/Users/widgets.php | 30 + crm/check_analytics_slug.php | 11 - crm/test_analytics_slug.php | 41 - 18 files changed, 3899 insertions(+), 52 deletions(-) create mode 100644 crm/Modules/Users/Controllers/UserController.php create mode 100644 crm/Modules/Users/Models/UserModel.php create mode 100644 crm/Modules/Users/Module.php create mode 100644 crm/Modules/Users/Routes/api.php create mode 100644 crm/Modules/Users/Routes/web.php create mode 100644 crm/Modules/Users/Views/admin-roles.php create mode 100644 crm/Modules/Users/Views/admin-users.php create mode 100644 crm/Modules/Users/Views/dashboard.php create mode 100644 crm/Modules/Users/Views/user-edit.php create mode 100644 crm/Modules/Users/Views/user-permissions.php create mode 100644 crm/Modules/Users/Views/user-profile.php create mode 100644 crm/Modules/Users/Views/user-settings.php create mode 100644 crm/Modules/Users/Views/user-view.php create mode 100644 crm/Modules/Users/Widgets/UserActivityWidget.php create mode 100644 crm/Modules/Users/menu.php create mode 100644 crm/Modules/Users/widgets.php delete mode 100644 crm/check_analytics_slug.php delete mode 100644 crm/test_analytics_slug.php diff --git a/crm/Modules/Users/Controllers/UserController.php b/crm/Modules/Users/Controllers/UserController.php new file mode 100644 index 0000000..881042a --- /dev/null +++ b/crm/Modules/Users/Controllers/UserController.php @@ -0,0 +1,919 @@ +userModel = new UserModel(); + } + + public function showProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Obter ID do utilizador autenticado + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + $userData = $this->userModel->find($userId); + + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Sanitizar dados do utilizador + $user = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? 'N/A'), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? 'N/A'), + 'job_title' => Sanitize::string($userData['job_title'] ?? 'N/A'), + 'company_name' => Sanitize::string($userData['company_name'] ?? 'N/A'), + 'city' => Sanitize::string($userData['city'] ?? 'N/A'), + 'country' => Sanitize::string($userData['country'] ?? 'N/A'), + 'avatar' => \App\Core\View::asset('images/users/avatar-1.jpg'), + 'profile_bg' => \App\Core\View::asset('images/profile-bg.jpg'), + 'followers_count' => $this->getFollowersCount($userId), + 'following_count' => $this->getFollowingCount($userId), + 'email' => Sanitize::email($userData['email'] ?? 'N/A'), + 'website' => Sanitize::url($userData['website'] ?? '#'), + 'phone' => Sanitize::string($userData['phone'] ?? 'N/A'), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? 'N/A'), + 'description' => Sanitize::string($userData['description'] ?? 'N/A'), + 'joining_date' => Sanitize::string($userData['joining_date'] ?? 'N/A') + ]; + + // Parse e sanitizar campos JSON + $skills = []; + $experience = []; + $education = []; + $socialLinks = []; + + if (!empty($userData['skills'])) { + $skills = json_decode($userData['skills'], true) ?: []; + $skills = array_map('Sanitize::string', $skills); + } + if (!empty($userData['experience'])) { + $experience = json_decode($userData['experience'], true) ?: []; + // Sanitizar arrays de experiência + $experience = array_map(function($exp) { + return [ + 'title' => Sanitize::string($exp['title'] ?? ''), + 'company' => Sanitize::string($exp['company'] ?? ''), + 'description' => Sanitize::string($exp['description'] ?? ''), + 'period' => Sanitize::string($exp['period'] ?? '') + ]; + }, $experience); + } + if (!empty($userData['education'])) { + $education = json_decode($userData['education'], true) ?: []; + // Sanitizar arrays de educação + $education = array_map(function($edu) { + return [ + 'degree' => Sanitize::string($edu['degree'] ?? ''), + 'institution' => Sanitize::string($edu['institution'] ?? ''), + 'year' => Sanitize::string($edu['year'] ?? '') + ]; + }, $education); + } + if (!empty($userData['social_links'])) { + $socialLinks = json_decode($userData['social_links'], true) ?: []; + // Sanitizar links sociais + $socialLinks = array_map('Sanitize::url', $socialLinks); + } + + $userProfile = [ + 'bio' => Sanitize::string($userData['bio'] ?? 'No bio available.'), + 'location' => Sanitize::string($userData['location'] ?? 'N/A'), + 'skills' => $skills, + 'experience' => $experience, + 'education' => $education, + 'social_links' => $socialLinks, + 'profile_completion' => $this->calculateProfileCompletion($userData) + ]; + + // Render the main layout with the profile page content + View::render('layouts/main.php', [ + 'title' => 'User Profile', + 'page_content' => function() use ($user, $userProfile) { + View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Profile']); + View::render('@pages/profile', [ + 'user' => $user, + 'profile' => $userProfile + ]); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_show_profile', 'userId' => $userId ?? 0]); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Show the profile edit form. + */ + public function showEditProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + $userData = $this->userModel->find($userId); + + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Parse e sanitizar campos JSON + $skills = []; + $experience = []; + $education = []; + $socialLinks = []; + + if (!empty($userData['skills'])) { + $skills = json_decode($userData['skills'], true) ?: []; + $skills = array_map('Sanitize::string', $skills); + } + if (!empty($userData['experience'])) { + $experience = json_decode($userData['experience'], true) ?: []; + $experience = array_map(function($exp) { + return [ + 'title' => Sanitize::string($exp['title'] ?? ''), + 'company' => Sanitize::string($exp['company'] ?? ''), + 'description' => Sanitize::string($exp['description'] ?? ''), + 'period' => Sanitize::string($exp['period'] ?? '') + ]; + }, $experience); + } + if (!empty($userData['education'])) { + $education = json_decode($userData['education'], true) ?: []; + $education = array_map(function($edu) { + return [ + 'degree' => Sanitize::string($edu['degree'] ?? ''), + 'institution' => Sanitize::string($edu['institution'] ?? ''), + 'year' => Sanitize::string($edu['year'] ?? '') + ]; + }, $education); + } + if (!empty($userData['social_links'])) { + $socialLinks = json_decode($userData['social_links'], true) ?: []; + $socialLinks = array_map('Sanitize::url', $socialLinks); + } + + $user = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'phone' => Sanitize::string($userData['phone'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? ''), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? ''), + 'website' => Sanitize::url($userData['website'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'description' => Sanitize::string($userData['description'] ?? ''), + 'avatar' => Sanitize::string($userData['avatar'] ?? '/assets/images/users/avatar-1.jpg') + ]; + + $profile = [ + 'bio' => Sanitize::string($userData['bio'] ?? ''), + 'location' => Sanitize::string($userData['location'] ?? ''), + 'skills' => $skills, + 'experience' => $experience, + 'education' => $education, + 'social_links' => $socialLinks + ]; + + View::render('layouts/main.php', [ + 'title' => 'Edit Profile', + 'page_content' => function() use ($user, $profile) { + View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Edit Profile']); + View::render('@pages/profile-edit', [ + 'user' => $user, + 'profile' => $profile + ]); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_show_edit_profile', 'userId' => $userId ?? 0]); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Handle profile update form submission. + */ + public function updateProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + // ✅ NOVO: Validação automática usando ValidatorFactory + $validation = $this->validatePostAutoOrFail('user.update'); + + // Se chegou aqui, a validação passou - dados já sanitizados + $userData = $validation['data']; + + // Sanitizar e validar dados do perfil + $skills = array_filter(explode(',', InputSanitizer::get('skills', 'POST') ?? ''), 'trim'); + $skills = array_map('Sanitize::string', $skills); + + $profileData = [ + 'bio' => Sanitize::string(InputSanitizer::get('bio', 'POST') ?? ''), + 'location' => Sanitize::string(InputSanitizer::get('location', 'POST') ?? ''), + 'skills' => json_encode($skills), + 'social_links' => json_encode([ + 'linkedin' => Sanitize::url(InputSanitizer::get('linkedin', 'POST') ?? ''), + 'github' => Sanitize::url(InputSanitizer::get('github', 'POST') ?? ''), + 'twitter' => Sanitize::url(InputSanitizer::get('twitter', 'POST') ?? '') + ]) + ]; + + // Update user and profile + $success = $this->userModel->update($userId, $userData, $profileData); + + if ($success) { + $this->successResponse([], 'Profile updated successfully'); + } else { + $this->errorResponse('Failed to update profile'); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_update_profile', 'userId' => $userId ?? 0]); + $this->errorResponse('Internal server error', 500); + } + } + + /** + * Admin users management page. + */ + public function adminUsers(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Verificar se é admin + if (!Auth::isAdmin()) { + http_response_code(403); + echo 'Acesso negado'; + return; + } + + View::render('layouts/main.php', [ + 'title' => 'Gestão de Utilizadores', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Utilizadores' + ]); + View::render('@users/admin-users'); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_admin_users']); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Admin roles management page. + */ + public function adminRoles(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Verificar se é admin + if (!Auth::isAdmin()) { + http_response_code(403); + echo 'Acesso negado'; + return; + } + + View::render('layouts/main.php', [ + 'title' => 'Gestão de Perfis', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Perfis' + ]); + View::render('@users/admin-roles.php'); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_admin_roles']); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + // API Methods for Admin Users Management + + /** + * API: Get all users with pagination and search + */ + public function apiGetUsers(): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $search = Sanitize::string($_GET['search'] ?? ''); + $sort = Sanitize::string($_GET['sort'] ?? 'name'); + $page = max(1, (int)($_GET['page'] ?? 1)); + $perPage = max(1, min(100, (int)($_GET['per_page'] ?? 10))); + + $users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage); + $totalUsers = $this->userModel->getTotalForAdmin($search); + $totalPages = ceil($totalUsers / $perPage); + + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'users' => $users, + 'current_page' => $page, + 'per_page' => $perPage, + 'total_pages' => $totalPages, + 'total' => $totalUsers + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_users']); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Get single user by ID + */ + public function apiGetUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $user = $this->userModel->findForAdmin($id); + + if (!$user) { + http_response_code(404); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Utilizador não encontrado']); + exit; + } + + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'user' => $user + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Create new user + */ + public function apiCreateUser(): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $input = json_decode(file_get_contents('php://input'), true); + + $userData = [ + 'first_name' => Sanitize::string($input['first_name'] ?? ''), + 'last_name' => Sanitize::string($input['last_name'] ?? ''), + 'email' => Sanitize::email($input['email'] ?? ''), + 'password' => $input['password'] ?? '', + 'role' => Sanitize::string($input['role'] ?? 'user'), + 'is_active' => (int)($input['is_active'] ?? 1) + ]; + + // Basic validation + if (empty($userData['first_name']) || empty($userData['email']) || empty($userData['password'])) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Campos obrigatórios em falta']); + exit; + } + + if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Email inválido']); + exit; + } + + $userId = $this->userModel->createForAdmin($userData); + + if ($userId) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador criado com sucesso', + 'user_id' => $userId + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao criar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_create_user']); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Update user + */ + public function apiUpdateUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $input = json_decode(file_get_contents('php://input'), true); + + $userData = [ + 'first_name' => Sanitize::string($input['first_name'] ?? ''), + 'last_name' => Sanitize::string($input['last_name'] ?? ''), + 'email' => Sanitize::email($input['email'] ?? ''), + 'role' => Sanitize::string($input['role'] ?? 'user'), + 'is_active' => (int)($input['is_active'] ?? 1) + ]; + + // Only include password if provided + if (!empty($input['password'])) { + $userData['password'] = $input['password']; + } + + // Basic validation + if (empty($userData['first_name']) || empty($userData['email'])) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Campos obrigatórios em falta']); + exit; + } + + if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Email inválido']); + exit; + } + + $success = $this->userModel->updateForAdmin($id, $userData); + + if ($success) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador atualizado com sucesso' + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao atualizar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_update_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Delete user + */ + public function apiDeleteUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + // Don't allow deleting yourself + if ($id === Auth::id()) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Não pode eliminar a sua própria conta']); + exit; + } + + $success = $this->userModel->deleteForAdmin($id); + + if ($success) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador eliminado com sucesso' + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao eliminar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_delete_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * Get followers count for a user + */ + private function getFollowersCount(int $userId): int + { + // For now, return 0 as we don't have a followers system implemented + // This can be implemented when the social features are added + return 0; + } + + /** + * Get following count for a user + */ + private function getFollowingCount(int $userId): int + { + // For now, return 0 as we don't have a following system implemented + // This can be implemented when the social features are added + return 0; + } + + /** + * Calculate profile completion percentage + */ + private function calculateProfileCompletion(array $userData): int + { + $totalFields = 10; + $completedFields = 0; + + // Check required fields + if (!empty($userData['first_name'])) $completedFields++; + if (!empty($userData['last_name'])) $completedFields++; + if (!empty($userData['email'])) $completedFields++; + if (!empty($userData['bio'])) $completedFields++; + if (!empty($userData['job_title'])) $completedFields++; + if (!empty($userData['city'])) $completedFields++; + if (!empty($userData['country'])) $completedFields++; + if (!empty($userData['phone'])) $completedFields++; + if (!empty($userData['skills'])) $completedFields++; + if (!empty($userData['avatar'])) $completedFields++; + + return (int) round(($completedFields / $totalFields) * 100); + } + + // --- INDIVIDUAL USER MANAGEMENT METHODS (Missing functionality) --- + + /** + * Show specific user details (admin function) + */ + public function showUser(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Utilizador: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-view', + 'page_content' => function() use ($user) { + View::render('@users/user-view.php', ['user' => $user]); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show specific user profile (admin function) + */ + public function showUserProfile(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? '') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Perfil: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-profile', + 'page_content' => function() use ($user) { + View::render('@users/user-profile.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_profile', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show edit user form (admin function) + */ + public function showEditUser(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Editar: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-edit', + 'page_content' => function() use ($user) { + View::render('@users/user-edit.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_edit_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show user settings (admin function) + */ + public function showUserSettings(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active'), + 'preferences' => json_decode($userData['preferences'] ?? '{}', true) + ]; + + View::render('layouts/main.php', [ + 'title' => 'Definições: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-settings', + 'page_content' => function() use ($user) { + View::render('@users/user-settings.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_settings', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show user permissions (admin function) + */ + public function showUserPermissions(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'role' => Sanitize::string($userData['role'] ?? 'user'), + 'permissions' => json_decode($userData['permissions'] ?? '[]', true) + ]; + + View::render('layouts/main.php', [ + 'title' => 'Permissões: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-permissions', + 'page_content' => function() use ($user) { + View::render('@users/user-permissions.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_permissions', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Update specific user (admin function) + */ + public function updateUser(int $id): void + { + try { + $this->requireAuth(); + + if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + http_response_code(405); + echo 'Método não permitido'; + return; + } + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Update user with sanitized data + $updateData = [ + 'first_name' => Sanitize::string($_POST['first_name'] ?? ''), + 'last_name' => Sanitize::string($_POST['last_name'] ?? ''), + 'email' => Sanitize::email($_POST['email'] ?? ''), + 'job_title' => Sanitize::string($_POST['job_title'] ?? ''), + 'company_name' => Sanitize::string($_POST['company_name'] ?? ''), + 'status' => Sanitize::string($_POST['status'] ?? 'active') + ]; + + $success = $this->userModel->update($id, $updateData); + + if ($success) { + header('Location: /users/' . $id . '?updated=1', true, 302); + } else { + http_response_code(500); + echo 'Erro ao actualizar utilizador'; + } + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'update_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } +} \ No newline at end of file diff --git a/crm/Modules/Users/Models/UserModel.php b/crm/Modules/Users/Models/UserModel.php new file mode 100644 index 0000000..7d31b9f --- /dev/null +++ b/crm/Modules/Users/Models/UserModel.php @@ -0,0 +1,266 @@ +db = DatabaseManager::getInstance(); + // Use default database + } + + /** + * Find a user by their ID, joining with the profile data. + * + * @param int $id The user's ID. + * @return array|false The user data as an associative array, or false if not found. + */ + public function find(int $id) + { + try { + // Validar ID + if ($id <= 0) { + return false; + } + + // Use default database + + $sql = " + SELECT + u.id, + u.username, + u.first_name, + u.last_name, + u.email, + u.phone, + u.city, + u.country, + u.zipcode, + u.website, + u.description, + u.avatar, + u.job_title, + u.company_name, + u.joining_date, + u.role, + u.is_active, + up.bio, + up.location, + up.skills, + up.experience, + up.education, + up.social_links + FROM + users u + LEFT JOIN + user_profiles up ON u.id = up.user_id + WHERE + u.id = :id + "; + + $result = $this->db->fetch($sql, [':id' => $id]); + $this->db->useDefaultDatabase(); + + return $result; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Update user and profile data. + * + * @param int $id The user's ID. + * @param array $userData The user data to update. + * @param array $profileData The profile data to update. + * @return bool True if update was successful, false otherwise. + */ + public function update(int $id, array $userData, array $profileData): bool + { + try { + // Validar ID + if ($id <= 0) { + return false; + } + + // Sanitizar dados do utilizador + $sanitizedUserData = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'phone' => Sanitize::string($userData['phone'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? ''), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? ''), + 'website' => Sanitize::url($userData['website'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'description' => Sanitize::string($userData['description'] ?? ''), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + // Sanitizar dados do perfil + $sanitizedProfileData = [ + 'bio' => Sanitize::string($profileData['bio'] ?? ''), + 'location' => Sanitize::string($profileData['location'] ?? ''), + 'skills' => Sanitize::string($profileData['skills'] ?? ''), + 'social_links' => Sanitize::string($profileData['social_links'] ?? ''), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + // Use default database + + // Update user data + $userSuccess = $this->db->update('users', $sanitizedUserData, ['id' => $id]); + + // Update profile data + $profileSuccess = $this->db->update('user_profiles', $sanitizedProfileData, ['user_id' => $id]); + + $this->db->useDefaultDatabase(); + + return $userSuccess && $profileSuccess; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Find a user by email. + * + * @param string $email + * @return array|false + */ + public function findByEmail(string $email) + { + try { + // Use default database + $sql = "SELECT * FROM users WHERE email = :email LIMIT 1"; + $result = $this->db->fetch($sql, [':email' => $email]); + $this->db->useDefaultDatabase(); + return $result; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Create a new user. + * + * @param array $data + * @return int|false User ID or false on failure + */ + public function create(array $data) + { + try { + // Use default database + $userData = [ + 'username' => Sanitize::string($data['username'] ?? ''), + 'first_name' => Sanitize::string($data['first_name'] ?? ''), + 'last_name' => Sanitize::string($data['last_name'] ?? ''), + 'email' => Sanitize::email($data['email'] ?? ''), + 'password' => $data['password'] ?? '', + 'role' => Sanitize::string($data['role'] ?? 'user'), + 'is_active' => $data['is_active'] ?? 1, + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + $userId = $this->db->insert('users', $userData); + $this->db->useDefaultDatabase(); + return $userId; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Get all users with optional filters + */ + public function getAll(array $filters = [], int $limit = 50, int $offset = 0): array + { + try { + $sql = "SELECT + u.id, + u.username, + u.first_name, + u.last_name, + u.email, + u.phone, + u.city, + u.country, + u.zipcode, + u.website, + u.description, + u.avatar, + u.job_title, + u.company_name, + u.joining_date, + u.role, + u.is_active, + u.created_at, + u.updated_at + FROM + users u + WHERE + u.id > 0"; + + $params = []; + + if (!empty($filters['search'])) { + $sql .= " AND (u.username LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)"; + $searchTerm = '%' . $filters['search'] . '%'; + $params[] = $searchTerm; + $params[] = $searchTerm; + $params[] = $searchTerm; + $params[] = $searchTerm; + } + + if (!empty($filters['role'])) { + $sql .= " AND u.role = ?"; + $params[] = $filters['role']; + } + + if (isset($filters['is_active'])) { + $sql .= " AND u.is_active = ?"; + $params[] = $filters['is_active']; + } + + $sql .= " ORDER BY u.created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset; + + return $this->db->fetchAll($sql, $params) ?: []; + } catch (\Exception $e) { + return []; + } + } + + /** + * Delete a user by ID + */ + public function delete(int $id): bool + { + try { + if ($id <= 0) { + return false; + } + + // Soft delete - mark as inactive instead of deleting + $sql = "UPDATE users SET is_active = 0, updated_at = NOW() WHERE id = ?"; + $result = $this->db->query($sql, [$id]); + + return $result > 0; + } catch (\Exception $e) { + return false; + } + } +} diff --git a/crm/Modules/Users/Module.php b/crm/Modules/Users/Module.php new file mode 100644 index 0000000..dda697e --- /dev/null +++ b/crm/Modules/Users/Module.php @@ -0,0 +1,39 @@ +get( + '/api/admin/users', + [UserController::class, 'apiGetUsers'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->get( + '/api/admin/users/{int:id}', + [UserController::class, 'apiGetUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->post( + '/api/admin/users', + [UserController::class, 'apiCreateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->put( + '/api/admin/users/{int:id}', + [UserController::class, 'apiUpdateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->delete( + '/api/admin/users/{int:id}', + [UserController::class, 'apiDeleteUser'], + [AuthMiddleware::class, 'requireAuth'] +); \ No newline at end of file diff --git a/crm/Modules/Users/Routes/web.php b/crm/Modules/Users/Routes/web.php new file mode 100644 index 0000000..a8404c2 --- /dev/null +++ b/crm/Modules/Users/Routes/web.php @@ -0,0 +1,81 @@ +get( + '/apps/users/profile', + [UserController::class, 'showProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Profile editing routes +$router->get( + '/apps/users/profile/edit', + [UserController::class, 'showEditProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->post( + '/apps/users/profile/update', + [UserController::class, 'updateProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Admin routes +$router->get( + '/admin/users', + [UserController::class, 'adminUsers'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->get( + '/admin/roles', + [UserController::class, 'adminRoles'], + [AuthMiddleware::class, 'requireAuth'] +); + +// --- INDIVIDUAL USER MANAGEMENT ROUTES (Missing functionality) --- +// View specific user profile (admin function) +$router->get( + '/users/{int:id}', + [UserController::class, 'showUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// View specific user profile page +$router->get( + '/users/{int:id}/profile', + [UserController::class, 'showUserProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Edit specific user (admin function) +$router->get( + '/users/{int:id}/edit', + [UserController::class, 'showEditUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// User settings page +$router->get( + '/users/{int:id}/settings', + [UserController::class, 'showUserSettings'], + [AuthMiddleware::class, 'requireAuth'] +); + +// User permissions management +$router->get( + '/users/{int:id}/permissions', + [UserController::class, 'showUserPermissions'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Update specific user (admin function) +$router->post( + '/users/{int:id}/update', + [UserController::class, 'updateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Adicionaremos mais rotas aqui, como POST para atualizar o perfil diff --git a/crm/Modules/Users/Views/admin-roles.php b/crm/Modules/Users/Views/admin-roles.php new file mode 100644 index 0000000..1d36bba --- /dev/null +++ b/crm/Modules/Users/Views/admin-roles.php @@ -0,0 +1,436 @@ + + +
+
+
+
+
+
+

Gestão de Perfis de Utilizador

+
+
+ +
+
+
+
+
+
+ +
+
+
+ Ordenar por: + +
+
+
+ +
+ + + + + + + + + + + + + + + + + + + +
+
+ +
+
Nome do PerfilDescriçãoPermissõesUtilizadoresEstadoAções
+
+
+
+
+
+ + + + + \ No newline at end of file diff --git a/crm/Modules/Users/Views/admin-users.php b/crm/Modules/Users/Views/admin-users.php new file mode 100644 index 0000000..b3c4809 --- /dev/null +++ b/crm/Modules/Users/Views/admin-users.php @@ -0,0 +1,393 @@ + + +
+
+
+

Gestão de Utilizadores

+
+ +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+ + + + +
+
+
+
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+ Ordenar por: + +
+
+
+
+ +
+ +
+
+ Carregando... +
+
+ + +
+
+ + + + + + + + + + + + + + + +
+
+ +
+
NomeEmailFunçãoEstadoData CriaçãoAções
+ + +
+ + +
Nenhum resultado encontrado
+

Não encontrámos utilizadores que correspondam aos critérios de pesquisa.

+
+
+ + +
+
+ +
    + +
+ +
+
+
+
+
+
+ + +
+
+
+
Estatísticas
+
+
+
+
+
+

0

+

Total

+
+
+
+
+

0

+

Ativos

+
+
+
+
+

0

+

Inativos

+
+
+
+
+

0

+

Admins

+
+
+
+
+
+ + +
+
+
Atividade Recente
+
+
+
+ +
+
Nenhuma atividade recente
+
+
+
+
+
+
+ + + + + + diff --git a/crm/Modules/Users/Views/dashboard.php b/crm/Modules/Users/Views/dashboard.php new file mode 100644 index 0000000..9cc9789 --- /dev/null +++ b/crm/Modules/Users/Views/dashboard.php @@ -0,0 +1,293 @@ + + +
+
+
+

Dashboard de Utilizadores

+ +
+
+
+ +
+ +
+
+
+
+
+

Total de Utilizadores

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Utilizadores Ativos

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Novos Este Mês

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Administradores

+

+
+
+
+ + + +
+
+
+
+
+
+
+ +
+ +
+
+
+

Utilizadores Recentes

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
UtilizadorEmailFunçãoEstadoData de RegistoAções
+
+
+
+ + + +
+
+
+
+

+
+
+
+ + + + + + + + + +
+ +

Nenhum utilizador encontrado

+ Gerir Utilizadores +
+
+
+
+
+ + +
+
+
+

Atividade Recente

+
+
+
+ + +
+ +
+ +

+ +
+
+ + +
+ +

Nenhuma atividade recente

+
+ +
+
+
+
+
+ +
+ +
+
+
+

Registo de Utilizadores

+
+
+ +
+
+
+ + +
+
+
+

Distribuição por Função

+
+
+ +
+
+
+
+ + diff --git a/crm/Modules/Users/Views/user-edit.php b/crm/Modules/Users/Views/user-edit.php new file mode 100644 index 0000000..46bbf85 --- /dev/null +++ b/crm/Modules/Users/Views/user-edit.php @@ -0,0 +1,364 @@ +
+
+
+

Editar Utilizador

+ +
+
+
+ +
+
+
+
+

Informações do Utilizador

+
+
+
+ + +
+
+
+ + +
+ Por favor, insira o nome. +
+
+
+
+
+ + +
+ Por favor, insira o apelido. +
+
+
+
+ +
+
+
+ + +
+ Por favor, insira um username. +
+
+
+
+
+ + +
+ Por favor, insira um email válido. +
+
+
+
+ +
+
+
+ + +
+
+
+
+ + +
+
+
+ +
+
+
+ + +
+ Por favor, selecione um status. +
+
+
+
+
+ + +
+
+
+ +
+ + +
+ +
+ + +
+ +
+ +
Alterar Password
+
+
+
+ + + Deixe em branco para manter a password atual +
+
+
+
+ + +
+ As passwords não coincidem. +
+
+
+
+ +
+ + +
+
+
+
+
+ +
+ +
+
+

Pré-visualização

+
+
+
+
+ + + +
+

+

+ + + +
+
+
+ + +
+
+

Informações da Conta

+
+
+
+
+ +
+
+
Membro desde
+

+
+
+ +
+
+ +
+
+
Último acesso
+

+
+
+ +
+
+ +
+
+
Última atualização
+

+
+
+
+
+ + +
+
+

Ações Rápidas

+
+
+
+ + Gerir Permissões + + + Configurações + + + + + + +
+
+
+
+
+ + \ No newline at end of file diff --git a/crm/Modules/Users/Views/user-permissions.php b/crm/Modules/Users/Views/user-permissions.php new file mode 100644 index 0000000..7e60511 --- /dev/null +++ b/crm/Modules/Users/Views/user-permissions.php @@ -0,0 +1,70 @@ +
+
+
+

Permissões do Utilizador

+ +
+
+
+ +
+
+
+
+

Gerir Permissões

+
+
+
+ +
+ +
+ +
+
+ > + +
+
+ +
+
+
+ + +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/crm/Modules/Users/Views/user-profile.php b/crm/Modules/Users/Views/user-profile.php new file mode 100644 index 0000000..da07fc6 --- /dev/null +++ b/crm/Modules/Users/Views/user-profile.php @@ -0,0 +1,342 @@ +
+
+
+

Perfil Completo

+ +
+
+
+ +
+ +
+
+
+
+
+ + + +
+

+

+ + + +
+ +
+ + +
Informações de Contacto
+
+
+ +
+
+
Email
+

+
+
+ + +
+
+ +
+
+
Telefone
+

+
+
+ + + +
+
+ +
+
+
Localização
+

+
+
+ + + +
Informações da Conta
+
+
+ +
+
+
Membro desde
+

+
+
+ +
+
+ +
+
+
Último acesso
+

+
+
+ +
+
+ +
+
+
Tipo de Conta
+

+
+
+
+
+ + + +
+
+

Biografia

+
+
+

+
+
+ +
+ + +
+ +
+
+
+
+
+
+

Sessões

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Atividades

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Projetos

+

+
+
+
+ + + +
+
+
+
+
+
+
+ + +
+
+

Informações Detalhadas

+
+
+
+
+
Informações Pessoais
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Nome Completo:
Username:
Email:
Telefone:
Data de Nascimento:
Localização:
+
+
+
Informações da Conta
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Status: + + + +
Tipo de Conta:
Criado em:
Última Atualização:
Último Login:
ID do Utilizador:#
+
+
+
+
+ + + +
+
+

Projetos Recentes

+
+
+
+ + + + + + + + + + + + + + + + + + + +
ProjetoStatusProgressoData de Criação
+
+
+
+ + + +
+
+
+
+

+
+
+
+ + + + +
+
+
+ % +
+
+
+
+ + + +
+
+

Atividade Recente

+
+
+
+ + +
+ +
+ +

+ +
+
+ + +
+ +

Nenhuma atividade recente

+
+ +
+
+
+
+
\ No newline at end of file diff --git a/crm/Modules/Users/Views/user-settings.php b/crm/Modules/Users/Views/user-settings.php new file mode 100644 index 0000000..41bedf8 --- /dev/null +++ b/crm/Modules/Users/Views/user-settings.php @@ -0,0 +1,81 @@ +
+
+
+

Definições do Utilizador

+ +
+
+
+ +
+
+
+
+

Configurações Gerais

+
+
+
+ +
+ + +
+
+ + +
+
+ +
+ > + +
+
+
+ + +
+
+
+
+
+
+ + \ No newline at end of file diff --git a/crm/Modules/Users/Views/user-view.php b/crm/Modules/Users/Views/user-view.php new file mode 100644 index 0000000..4f309fd --- /dev/null +++ b/crm/Modules/Users/Views/user-view.php @@ -0,0 +1,317 @@ +
+
+
+

Perfil do Utilizador

+ +
+
+
+ +
+ +
+
+
+
+
+ + + +
+

+

+ + + +
+ +
+ +
+
+ +
+
+
Email
+

+
+
+ +
+
+ +
+
+
Membro desde
+

+
+
+ +
+
+ +
+
+
Último acesso
+

+
+
+ +
+
+ +
+
+
Localização
+

+
+
+
+
+ + +
+
+

Ações Rápidas

+
+
+ +
+
+
+ + +
+ +
+
+
+
+
+
+

Sessões

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Atividades

+

+
+
+
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+

Projetos

+

+
+
+
+ + + +
+
+
+
+
+
+
+ + +
+
+

Informações Detalhadas

+
+
+
+
+
Informações Pessoais
+ + + + + + + + + + + + + + + + + + + + + +
Nome Completo:
Username:
Email:
Telefone:
Data de Nascimento:
+
+
+
Informações da Conta
+ + + + + + + + + + + + + + + + + + + + + +
Status: + + + +
Tipo de Conta:
Criado em:
Última Atualização:
Último Login:
+
+
+
+
+ + +
+
+

Atividade Recente

+
+
+
+ + +
+ +
+ +

+ +
+
+ + +
+ +

Nenhuma atividade recente

+
+ +
+
+
+
+
+ + \ No newline at end of file diff --git a/crm/Modules/Users/Widgets/UserActivityWidget.php b/crm/Modules/Users/Widgets/UserActivityWidget.php new file mode 100644 index 0000000..83bffae --- /dev/null +++ b/crm/Modules/Users/Widgets/UserActivityWidget.php @@ -0,0 +1,199 @@ +db = DatabaseManager::getInstance(); + } + + /** + * Render the user activity widget + * + * @param array $config Widget configuration + * @return string Widget HTML + */ + public static function render(array $config = []): string + { + try { + $widget = new self(); + return $widget->renderContent($config); + } catch (\Exception $e) { + ErrorReporter::report($e); + return '
Erro ao carregar atividade de utilizadores
'; + } + } + + /** + * Render widget content + */ + private function renderContent(array $config): string + { + $stats = $this->getStats(); + + ob_start(); + ?> +
+
+
+
+ + + +
+
+

Online Agora

+
+
utilizadores
+
+
+
+
+
+
+
+ + + +
+
+

Logins Hoje

+
+
+
+
+
+
+
+
+
+ + + +
+
+

Novos Utilizadores

+
+
esta semana
+
+
+
+
+
+ +
+
+ Último login: + +
+
+ db->fetch(" + SELECT + -- Users online (active in last 15 minutes) + (SELECT COUNT(*) FROM users + WHERE last_login > DATE_SUB(NOW(), INTERVAL 15 MINUTE) + AND deleted_at IS NULL) as users_online, + + -- Logins today + (SELECT COUNT(*) FROM users + WHERE DATE(last_login) = CURDATE() + AND deleted_at IS NULL) as logins_today, + + -- New users this week + (SELECT COUNT(*) FROM users + WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) + AND deleted_at IS NULL) as new_users, + + -- Last login time + (SELECT MAX(last_login) FROM users WHERE deleted_at IS NULL) as last_login_time + "); + + if (!$result) { + // Try basic user count if main query fails + try { + $basicResult = $this->db->fetch("SELECT COUNT(*) as count FROM users WHERE deleted_at IS NULL"); + $totalUsers = (int)($basicResult['count'] ?? 0); + + return [ + 'users_online' => max(1, (int)($totalUsers * 0.3)), + 'logins_today' => max(1, (int)($totalUsers * 2)), + 'new_users' => max(0, (int)($totalUsers * 0.1)), + 'last_login' => $totalUsers > 0 ? 'há 15m' : 'Nunca' + ]; + } catch (\Exception $e) { + // Final fallback if users table doesn't exist + return [ + 'users_online' => 0, + 'logins_today' => 0, + 'new_users' => 0, + 'last_login' => 'Nunca' + ]; + } + } + + $usersOnline = (int)($result['users_online'] ?? 0); + $loginsToday = (int)($result['logins_today'] ?? 0); + $newUsers = (int)($result['new_users'] ?? 0); + $lastLoginTime = $result['last_login_time'] ?? null; + + // Format last login time + $lastLogin = 'Nunca'; + if ($lastLoginTime) { + $lastLoginTimestamp = strtotime($lastLoginTime); + $timeDiff = time() - $lastLoginTimestamp; + if ($timeDiff < 60) { + $lastLogin = 'agora'; + } elseif ($timeDiff < 3600) { + $lastLogin = 'há ' . round($timeDiff / 60) . 'm'; + } elseif ($timeDiff < 86400) { + $lastLogin = 'há ' . round($timeDiff / 3600) . 'h'; + } else { + $lastLogin = 'há ' . round($timeDiff / 86400) . 'd'; + } + } + + return [ + 'users_online' => $usersOnline, + 'logins_today' => $loginsToday, + 'new_users' => $newUsers, + 'last_login' => $lastLogin + ]; + + } catch (\Exception $e) { + ErrorReporter::report($e); + // Return sample data on error + return [ + 'users_online' => 15, + 'logins_today' => 67, + 'new_users' => 8, + 'last_login' => 'há 5m' + ]; + } + } +} \ No newline at end of file diff --git a/crm/Modules/Users/menu.php b/crm/Modules/Users/menu.php new file mode 100644 index 0000000..be8a10b --- /dev/null +++ b/crm/Modules/Users/menu.php @@ -0,0 +1,35 @@ + 7, + 'label' => 'Gestão de Utilizadores', + 'icon' => 'ri-user-settings-line', + 'url' => '/admin/users', + 'order' => 7, + 'parent_id' => null, + 'dev' => 0, +]); + +// Submenus do Users +MenuManager::registerMenus('Users', [ + [ + 'id' => 71, + 'label' => 'Utilizadores', + 'icon' => 'ri-user-line', + 'url' => '/admin/users', + 'order' => 1, + 'parent_id' => 7, + 'dev' => 0, + ], + [ + 'id' => 72, + 'label' => 'Perfis', + 'icon' => 'ri-shield-user-line', + 'url' => '/admin/roles', + 'order' => 2, + 'parent_id' => 7, + 'dev' => 0, + ], +]); diff --git a/crm/Modules/Users/widgets.php b/crm/Modules/Users/widgets.php new file mode 100644 index 0000000..7d2c5d2 --- /dev/null +++ b/crm/Modules/Users/widgets.php @@ -0,0 +1,30 @@ +registerWidget( + 'users-activity', + 'Users', + 'Atividade de Utilizadores', + 'App\\Modules\\Users\\Widgets\\UserActivityWidget', + [ + 'description' => 'Atividade recente dos utilizadores', + 'size' => 'small', + 'category' => 'users' + ] + ); +} \ No newline at end of file diff --git a/crm/check_analytics_slug.php b/crm/check_analytics_slug.php deleted file mode 100644 index 8aa3bcc..0000000 --- a/crm/check_analytics_slug.php +++ /dev/null @@ -1,11 +0,0 @@ -fetchAll('SELECT id, cuid, analytics_slug, name FROM redirects WHERE status >= 0 LIMIT 5'); - -echo "🔍 Verificando analytics_slug na base de dados...\n\n"; - -foreach ($redirects as $r) { - echo "ID: {$r['id']}, CUID: {$r['cuid']}, Analytics Slug: " . ($r['analytics_slug'] ?? 'NULL') . ", Name: {$r['name']}\n"; -} diff --git a/crm/test_analytics_slug.php b/crm/test_analytics_slug.php deleted file mode 100644 index 8eda102..0000000 --- a/crm/test_analytics_slug.php +++ /dev/null @@ -1,41 +0,0 @@ -getAll(); - - echo "🔍 Testando analytics_slug...\n\n"; - echo "📊 Total de redirects: " . count($redirects) . "\n\n"; - - if (!empty($redirects)) { - $first = $redirects[0]; - echo "📋 Primeiro redirect:\n"; - echo "ID: {$first['id']}\n"; - echo "Nome: {$first['name']}\n"; - echo "CUID: {$first['cuid']}\n"; - echo "Analytics Slug: " . ($first['analytics_slug'] ?? 'NULL') . "\n"; - - // Verificar se todos têm analytics_slug - $withoutSlug = 0; - foreach ($redirects as $redirect) { - if (empty($redirect['analytics_slug'])) { - $withoutSlug++; - echo "❌ Redirect ID {$redirect['id']} sem analytics_slug\n"; - } - } - - echo "\n📈 Redirects sem analytics_slug: {$withoutSlug}\n"; - - if ($withoutSlug > 0) { - echo "⚠️ PROBLEMA: Alguns redirects não têm analytics_slug!\n"; - } else { - echo "✅ Todos os redirects têm analytics_slug!\n"; - } - } - -} catch (Exception $e) { - echo "❌ Erro: " . $e->getMessage() . "\n"; -}