From 0283e966a95c827cec07d4969fcb03bf3d917090 Mon Sep 17 00:00:00 2001 From: 1sonhador <1sonhador@gmail.com> Date: Wed, 22 Oct 2025 18:09:55 +0100 Subject: [PATCH] MoneyFlix: Add remaining assets and source maps - Add source maps and license files for compiled assets - Add debug and test files for development - Complete Git repository with all necessary files for MoneyFlix project --- crm/Core/Auth.php | 6 + crm/Core/AuthMiddleware.php | 7 +- crm/Core/BaseController.php | 28 +- .../AddRawRequestToRedirectStats.php | 5 + .../Migrations/CreateUserActivitiesTable.php | 14 +- crm/Core/Router.php | 5 +- .../Controllers/AdvertisingApiController.php | 50 +- .../Controllers/BrandApiController.php | 20 +- crm/Modules/Advertising/Routes/api.php | 3 + crm/Modules/Advertising/Routes/web.php | 3 + crm/Modules/Controllers/PagesController.php | 2 +- .../Controllers/PublicCampaignsController.php | 3 +- .../Controllers/ErrorMonitoringController.php | 33 + .../ErrorMonitoring/Models/ErrorLog.php | 78 -- crm/Modules/ErrorMonitoring/Routes/web.php | 1 + crm/Modules/ErrorMonitoring/Views/errors.php | 5 +- crm/Modules/Routes/web.php | 2 +- .../Users/Controllers/UserController.php | 445 ++++++++-- .../Users/Models/UserActivityModel.php | 111 --- crm/Modules/Users/Models/UserModel.php | 204 +++-- crm/Modules/Users/Routes/api.php | 30 +- crm/Modules/Users/Routes/web.php | 14 + crm/Modules/Users/Views/admin-roles.php | 54 +- crm/Modules/Users/Views/admin-users.php | 580 +++++++++++++- .../Users/Widgets/UserActivityWidget.php | 108 ++- crm/Modules/Views/profile/settings.php | 6 +- .../Views/public-campaign-analytics.php | 10 +- .../Api/RedirectsApiController.php | 307 ------- .../Controllers/PublicRedirectsController.php | 370 --------- .../Controllers/RedirectsApiController.php | 757 ------------------ .../Controllers/RedirectsController.php | 562 ------------- .../ExtendRedirectsForAnalytics.php | 163 ---- .../IntegrateRedirectsWithSiteGroups.php | 223 ------ crm/Redirects/Models/RedirectFilterModel.php | 120 --- crm/Redirects/Models/RedirectModel.php | 346 -------- crm/Redirects/Models/RedirectStatsModel.php | 210 ----- crm/Redirects/Module.php | 78 -- crm/Redirects/Routes/api.php | 41 - crm/Redirects/Routes/public.php | 12 - crm/Redirects/Routes/web.php | 17 - .../Services/RedirectAutoCreatorService.php | 245 ------ .../Services/RedirectCreativeService.php | 217 ----- crm/Redirects/Services/RedirectProcessor.php | 16 - .../Views/components/filter-template.php | 35 - crm/Redirects/Views/dashboard.php | 289 ------- crm/Redirects/Views/redirects/create.php | 412 ---------- crm/Redirects/Views/redirects/edit.php | 138 ---- crm/Redirects/Views/redirects/index.php | 366 --------- crm/Redirects/Views/redirects/view.php | 356 -------- crm/Redirects/Views/settings.php | 308 ------- crm/Redirects/Views/stats/index.php | 441 ---------- crm/Redirects/config.php | 92 --- crm/Redirects/menu.php | 62 -- crm/Routes/web.php | 36 +- crm/Views/assets/lang/pt.json | 42 +- .../components/faqs/general-questions.php | 25 +- crm/Views/components/faqs/header.php | 8 +- crm/Views/components/faqs/manage-account.php | 22 +- .../components/faqs/privacy-security.php | 18 +- crm/Views/layouts/auth.php | 2 +- crm/Views/layouts/customizer.php | 7 +- crm/Views/layouts/topbar.php | 6 +- crm/debug_routes.php | 28 + crm/index.php | 45 ++ crm/test_roles_api.php | 29 + crm/test_roles_direct.php | 12 + crm/test_route_match.php | 21 + deploy-moneyflix-php.sh | 39 +- nodejs-redirector/ecosystem.config.cjs | 2 +- nodejs-redirector/env.example | 2 +- nodejs-redirector/index.mjs | 126 ++- public/assets/css/app.min.css.map | 1 + public/assets/css/public.min.css.map | 2 +- .../assets/js/alpine/forms/edit-redirect.js | 2 +- .../assets/js/alpine/tables/redirects-list.js | 2 +- public/assets/js/app.573fed979e3987a21d55.js | 3 - ...> app.8e9399a666b59b9816a2.js.LICENSE.txt} | 0 ...js.map => app.8e9399a666b59b9816a2.js.map} | 2 +- .../assets/js/public.4ae5942bfac40866ea14.js | 3 - .../js/public.4ae5942bfac40866ea14.js.map | 1 - ...ublic.6a37efa8030a7ee0bab7.js.LICENSE.txt} | 4 +- .../js/public.6a37efa8030a7ee0bab7.js.map | 1 + .../assets/js/vendor.9519303acbdcceec1cd1.js | 3 - .../js/vendor.9519303acbdcceec1cd1.js.map | 1 - ...endor.d567be5785f67ef5f74b.js.LICENSE.txt} | 4 +- .../js/vendor.d567be5785f67ef5f74b.js.map | 1 + src/js/alpine/forms/edit-redirect.js | 8 +- src/js/alpine/tables/redirects-list.js | 7 +- src/js/main.js | 28 +- src/js/pages/admin-users.js | 44 +- src/js/pages/error-monitoring-errors.js | 74 ++ test_redirects_final.php | 12 + 92 files changed, 1878 insertions(+), 6805 deletions(-) delete mode 100644 crm/Modules/Users/Models/UserActivityModel.php delete mode 100644 crm/Redirects/Controllers/Api/RedirectsApiController.php delete mode 100644 crm/Redirects/Controllers/PublicRedirectsController.php delete mode 100644 crm/Redirects/Controllers/RedirectsApiController.php delete mode 100644 crm/Redirects/Controllers/RedirectsController.php delete mode 100644 crm/Redirects/Database/Migrations/ExtendRedirectsForAnalytics.php delete mode 100644 crm/Redirects/Database/Migrations/IntegrateRedirectsWithSiteGroups.php delete mode 100644 crm/Redirects/Models/RedirectFilterModel.php delete mode 100644 crm/Redirects/Models/RedirectModel.php delete mode 100644 crm/Redirects/Models/RedirectStatsModel.php delete mode 100644 crm/Redirects/Module.php delete mode 100644 crm/Redirects/Routes/api.php delete mode 100644 crm/Redirects/Routes/public.php delete mode 100644 crm/Redirects/Routes/web.php delete mode 100644 crm/Redirects/Services/RedirectAutoCreatorService.php delete mode 100644 crm/Redirects/Services/RedirectCreativeService.php delete mode 100644 crm/Redirects/Services/RedirectProcessor.php delete mode 100644 crm/Redirects/Views/components/filter-template.php delete mode 100644 crm/Redirects/Views/dashboard.php delete mode 100644 crm/Redirects/Views/redirects/create.php delete mode 100644 crm/Redirects/Views/redirects/edit.php delete mode 100644 crm/Redirects/Views/redirects/index.php delete mode 100644 crm/Redirects/Views/redirects/view.php delete mode 100644 crm/Redirects/Views/settings.php delete mode 100644 crm/Redirects/Views/stats/index.php delete mode 100644 crm/Redirects/config.php delete mode 100644 crm/Redirects/menu.php create mode 100644 crm/debug_routes.php create mode 100644 crm/index.php create mode 100644 crm/test_roles_api.php create mode 100644 crm/test_roles_direct.php create mode 100644 crm/test_route_match.php create mode 100644 public/assets/css/app.min.css.map delete mode 100644 public/assets/js/app.573fed979e3987a21d55.js rename public/assets/js/{app.573fed979e3987a21d55.js.LICENSE.txt => app.8e9399a666b59b9816a2.js.LICENSE.txt} (100%) rename public/assets/js/{app.573fed979e3987a21d55.js.map => app.8e9399a666b59b9816a2.js.map} (61%) delete mode 100644 public/assets/js/public.4ae5942bfac40866ea14.js delete mode 100644 public/assets/js/public.4ae5942bfac40866ea14.js.map rename public/assets/js/{public.4ae5942bfac40866ea14.js.LICENSE.txt => public.6a37efa8030a7ee0bab7.js.LICENSE.txt} (95%) create mode 100644 public/assets/js/public.6a37efa8030a7ee0bab7.js.map delete mode 100644 public/assets/js/vendor.9519303acbdcceec1cd1.js delete mode 100644 public/assets/js/vendor.9519303acbdcceec1cd1.js.map rename public/assets/js/{vendor.9519303acbdcceec1cd1.js.LICENSE.txt => vendor.d567be5785f67ef5f74b.js.LICENSE.txt} (90%) create mode 100644 public/assets/js/vendor.d567be5785f67ef5f74b.js.map create mode 100644 test_redirects_final.php diff --git a/crm/Core/Auth.php b/crm/Core/Auth.php index 94cb7d2..433b5c1 100644 --- a/crm/Core/Auth.php +++ b/crm/Core/Auth.php @@ -230,9 +230,15 @@ class Auth /** * Check if user has admin role + * Se autenticado via API key, considera sempre como admin */ public static function isAdmin(): bool { + // Se autenticado via API key, tem acesso total + if (!empty($_SERVER['API_KEY_AUTH'])) { + return true; + } + if (!self::check()) { return false; } diff --git a/crm/Core/AuthMiddleware.php b/crm/Core/AuthMiddleware.php index fc32c28..d95faf4 100644 --- a/crm/Core/AuthMiddleware.php +++ b/crm/Core/AuthMiddleware.php @@ -12,13 +12,14 @@ class AuthMiddleware public static function requireAuth(): void { if (!Auth::check()) { - header('Location: /login'); + header('Location: /auth/login'); exit(); } } /** * API or Auth: allow if logged in OR if Authorization Bearer matches env key + * Se autenticado via Bearer, define flag para bypass de checks de role */ public static function apiOrAuth(): void { @@ -30,8 +31,10 @@ class AuthMiddleware if (stripos($authHeader, 'Bearer ') === 0) { $token = trim(substr($authHeader, 7)); } - $expected = $_ENV['REDIRECTS_API_KEY'] ?? getenv('REDIRECTS_API_KEY') ?? ''; + $expected = $_ENV['REDIRECTS_API_KEY'] ?? ''; if ($expected && $token && hash_equals($expected, $token)) { + // Define flag indicando autenticação via API key (acesso total) + $_SERVER['API_KEY_AUTH'] = true; return; } http_response_code(401); diff --git a/crm/Core/BaseController.php b/crm/Core/BaseController.php index 67100d9..5b394e5 100644 --- a/crm/Core/BaseController.php +++ b/crm/Core/BaseController.php @@ -134,7 +134,8 @@ abstract class BaseController '/public/', '/api/ecommerce/products', '/api/ecommerce/filter-options', - '/api/error-monitoring/' + '/api/error-monitoring/', + '/error-monitoring/' ]; foreach ($publicPatterns as $pattern) { @@ -172,6 +173,31 @@ abstract class BaseController } } + /** + * Check if request is authenticated via session OR API key + */ + protected function apiOrAuthRequired(): void + { + // Check session authentication first + if (Auth::check()) { + return; + } + + // Check Bearer token + $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; + if (stripos($authHeader, 'Bearer ') === 0) { + $token = trim(substr($authHeader, 7)); + $expectedKey = $_ENV['REDIRECTS_API_KEY'] ?? ''; + + if ($expectedKey && hash_equals($expectedKey, $token)) { + return; + } + } + + // Neither session nor API key is valid + $this->errorResponse('Unauthorized - Authentication required', 401); + } + /** * Obter dados sanitizados do request */ diff --git a/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php index 0021379..39f1bcc 100644 --- a/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php +++ b/crm/Core/Database/Migrations/AddRawRequestToRedirectStats.php @@ -32,3 +32,8 @@ class AddRawRequestToRedirectStats extends Migration + + + + + diff --git a/crm/Core/Database/Migrations/CreateUserActivitiesTable.php b/crm/Core/Database/Migrations/CreateUserActivitiesTable.php index 69b7b5b..c8e630c 100644 --- a/crm/Core/Database/Migrations/CreateUserActivitiesTable.php +++ b/crm/Core/Database/Migrations/CreateUserActivitiesTable.php @@ -8,18 +8,18 @@ class CreateUserActivitiesTable extends Migration public function up(): void { $this->createTable('user_activities', function($table) { - $table->id(); - $table->unsignedBigInteger('user_id'); + $table->bigInteger('id')->autoIncrement()->notNull(); + $table->bigInteger('user_id'); $table->string('action', 100); $table->string('description', 255); - $table->json('metadata')->nullable(); + $table->text('metadata')->nullable(); $table->string('ip_address', 45)->nullable(); $table->string('user_agent', 500)->nullable(); - $table->timestamp('created_at')->useCurrent(); + $table->timestamp('created_at')->default('CURRENT_TIMESTAMP')->notNull(); - $table->index(['user_id', 'created_at']); - $table->index(['action', 'created_at']); - $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); + $table->primaryKey('id'); + $table->index('user_id'); + $table->index('action'); }); } diff --git a/crm/Core/Router.php b/crm/Core/Router.php index 42aea90..46ab941 100644 --- a/crm/Core/Router.php +++ b/crm/Core/Router.php @@ -201,9 +201,8 @@ class Router if (!empty($middleware)) { // This is a simplified middleware handler for the purpose of the example - $authMiddleware = new AuthMiddleware(); - if (isset($middleware[0]) && method_exists($authMiddleware, $middleware[1])) { - call_user_func([$authMiddleware, $middleware[1]]); + if (isset($middleware[0]) && method_exists($middleware[0], $middleware[1])) { + call_user_func([$middleware[0], $middleware[1]]); } } diff --git a/crm/Modules/Advertising/Controllers/AdvertisingApiController.php b/crm/Modules/Advertising/Controllers/AdvertisingApiController.php index b90e052..ceddd54 100644 --- a/crm/Modules/Advertising/Controllers/AdvertisingApiController.php +++ b/crm/Modules/Advertising/Controllers/AdvertisingApiController.php @@ -43,7 +43,7 @@ class AdvertisingApiController extends BaseController 'search' => InputSanitizer::get('search', 'GET', '') ]; - $campaignModel = $this->resolveModuleService('model.CampaignModel'); + $campaignModel = new \App\Modules\Advertising\Models\CampaignModel(); $campaigns = $campaignModel->getAll($filters); echo json_encode([ @@ -68,7 +68,7 @@ class AdvertisingApiController extends BaseController // Se chegou aqui, a validação passou - dados já sanitizados $input = $validation['data']; - $campaignModel = $this->resolveModuleService('model.CampaignModel'); + $campaignModel = new \App\Modules\Advertising\Models\CampaignModel(); $success = $campaignModel->create($input); if ($success) { @@ -100,7 +100,7 @@ class AdvertisingApiController extends BaseController return; } - $campaignModel = $this->resolveModuleService('model.CampaignModel'); + $campaignModel = new \App\Modules\Advertising\Models\CampaignModel(); $campaign = $campaignModel->getById($id); if (!$campaign) { @@ -181,7 +181,8 @@ class AdvertisingApiController extends BaseController { header('Content-Type: application/json'); - $success = $this->resolveModuleService('model.CampaignModel')->delete($id); + $campaignModel = new \App\Modules\Advertising\Models\CampaignModel(); + $success = $campaignModel->delete($id); if ($success) { echo json_encode(['success' => true, 'message' => 'Campanha eliminada com sucesso']); @@ -208,34 +209,34 @@ class AdvertisingApiController extends BaseController $referer = $_SERVER['HTTP_REFERER'] ?? ''; // Verificar se IP está bloqueado - if ($this->resolveModuleService('model.TrackingModel')->isIpBlocked($ipAddress)) { + if (new \App\Modules\Advertising\Models\TrackingModel()->isIpBlocked($ipAddress)) { http_response_code(403); echo json_encode(['success' => false, 'message' => 'IP blocked']); return; } // Analisar fonte de tráfego - $trafficAnalysis = $this->resolveModuleService('model.TrackingModel')->analyzeTrafficSource($userAgent, $referer); + $trafficAnalysis = new \App\Modules\Advertising\Models\TrackingModel()->analyzeTrafficSource($userAgent, $referer); $sessionId = session_id() ?: (string) new \Visus\Cuid2\Cuid2(); // Verificar se é app bloqueada (Facebook, Instagram, etc.) - if ($this->resolveModuleService('model.TrackingModel')->isAppBlocked($userAgent, $referer)) { - $this->resolveModuleService('model.TrackingModel')->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'App blocked'); + if (new \App\Modules\Advertising\Models\TrackingModel()->isAppBlocked($userAgent, $referer)) { + new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'App blocked'); http_response_code(403); echo json_encode(['success' => false, 'message' => 'App blocked']); return; } // Verificar se é bot traffic - if ($this->resolveModuleService('model.TrackingModel')->isBotTraffic($userAgent)) { - $this->resolveModuleService('model.TrackingModel')->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'Bot traffic'); + if (new \App\Modules\Advertising\Models\TrackingModel()->isBotTraffic($userAgent)) { + new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer, 'Bot traffic'); http_response_code(403); echo json_encode(['success' => false, 'message' => 'Bot traffic detected']); return; } // Registar análise de tráfego válido - $this->resolveModuleService('model.TrackingModel')->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer); + new \App\Modules\Advertising\Models\TrackingModel()->recordTrafficAnalysis($trafficAnalysis, $sessionId, $ipAddress, $userAgent, $referer); $trackingData = array_merge($input, [ 'ip_address' => $ipAddress, @@ -248,7 +249,7 @@ class AdvertisingApiController extends BaseController 'platform' => $trafficAnalysis['platform'] ]); - $success = $this->resolveModuleService('model.TrackingModel')->recordView( + $success = new \App\Modules\Advertising\Models\TrackingModel()->recordView( (int) $input['tracker_id'], (int) $input['creative_id'], $trackingData @@ -277,8 +278,8 @@ class AdvertisingApiController extends BaseController $ipAddress = $_SERVER['REMOTE_ADDR'] ?? ''; // Verificar fraude - if ($this->resolveModuleService('model.TrackingModel')->detectFraud($ipAddress)) { - $this->resolveModuleService('model.TrackingModel')->recordFraudDetection($ipAddress, 'click_spam', 'Too many clicks in short time'); + if (new \App\Modules\Advertising\Models\TrackingModel()->detectFraud($ipAddress)) { + new \App\Modules\Advertising\Models\TrackingModel()->recordFraudDetection($ipAddress, 'click_spam', 'Too many clicks in short time'); http_response_code(403); echo json_encode(['success' => false, 'message' => 'Fraud detected']); return; @@ -292,7 +293,7 @@ class AdvertisingApiController extends BaseController 'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2() ]); - $success = $this->resolveModuleService('model.TrackingModel')->recordClick( + $success = new \App\Modules\Advertising\Models\TrackingModel()->recordClick( (int) $input['tracker_id'], (int) $input['creative_id'], $trackingData @@ -328,7 +329,7 @@ class AdvertisingApiController extends BaseController 'session_id' => session_id() ?: (string) new \Visus\Cuid2\Cuid2() ]); - $success = $this->resolveModuleService('model.TrackingModel')->recordRegister( + $success = new \App\Modules\Advertising\Models\TrackingModel()->recordRegister( (int) $input['tracker_id'], (int) $input['creative_id'], $trackingData @@ -349,8 +350,8 @@ class AdvertisingApiController extends BaseController $startDate = InputSanitizer::get('start_date', 'GET', ''); $endDate = InputSanitizer::get('end_date', 'GET', ''); - $stats = $this->resolveModuleService('model.CampaignModel')->getCampaignStats($campaignId, $startDate, $endDate); - $eventStats = $this->resolveModuleService('model.TrackingModel')->getEventStats($campaignId, $startDate, $endDate); + $stats = (new \App\Modules\Advertising\Models\CampaignModel())->getCampaignStats($campaignId, $startDate, $endDate); + $eventStats = new \App\Modules\Advertising\Models\TrackingModel()->getEventStats($campaignId, $startDate, $endDate); echo json_encode([ 'success' => true, @@ -368,7 +369,7 @@ class AdvertisingApiController extends BaseController $startDate = InputSanitizer::get('start_date', 'GET', ''); $endDate = InputSanitizer::get('end_date', 'GET', ''); - $geoStats = $this->resolveModuleService('model.TrackingModel')->getGeoStats($campaignId, $startDate, $endDate); + $geoStats = new \App\Modules\Advertising\Models\TrackingModel()->getGeoStats($campaignId, $startDate, $endDate); echo json_encode([ 'success' => true, @@ -383,7 +384,7 @@ class AdvertisingApiController extends BaseController $startDate = InputSanitizer::get('start_date', 'GET', ''); $endDate = InputSanitizer::get('end_date', 'GET', ''); - $deviceStats = $this->resolveModuleService('model.TrackingModel')->getDeviceStats($campaignId, $startDate, $endDate); + $deviceStats = new \App\Modules\Advertising\Models\TrackingModel()->getDeviceStats($campaignId, $startDate, $endDate); echo json_encode([ 'success' => true, @@ -398,7 +399,7 @@ class AdvertisingApiController extends BaseController $startDate = InputSanitizer::get('start_date', 'GET', ''); $endDate = InputSanitizer::get('end_date', 'GET', ''); - $stats = $this->resolveModuleService('model.TrackingModel')->getTrafficStats($startDate, $endDate); + $stats = new \App\Modules\Advertising\Models\TrackingModel()->getTrafficStats($startDate, $endDate); echo json_encode([ 'success' => true, @@ -410,7 +411,7 @@ class AdvertisingApiController extends BaseController { header('Content-Type: application/json'); - $stats = $this->resolveModuleService('model.TrackingModel')->getBlockedAppsStats(); + $stats = new \App\Modules\Advertising\Models\TrackingModel()->getBlockedAppsStats(); echo json_encode([ 'success' => true, @@ -443,8 +444,9 @@ class AdvertisingApiController extends BaseController $noEndDateCampaigns = (int)($stats['no_end_date'] ?? 0); // Estatísticas de eventos de hoje - $impressionsToday = $this->resolveModuleService('model.TrackingModel')->getTodayViewsCount(); - $clicksToday = $this->resolveModuleService('model.TrackingModel')->getTodayClicksCount(); + $trackingModel = new \App\Modules\Advertising\Models\TrackingModel(); + $impressionsToday = $trackingModel->getTodayViewsCount(); + $clicksToday = $trackingModel->getTodayClicksCount(); echo json_encode([ 'success' => true, diff --git a/crm/Modules/Advertising/Controllers/BrandApiController.php b/crm/Modules/Advertising/Controllers/BrandApiController.php index 95c2bcf..91ecb84 100644 --- a/crm/Modules/Advertising/Controllers/BrandApiController.php +++ b/crm/Modules/Advertising/Controllers/BrandApiController.php @@ -19,7 +19,7 @@ class BrandApiController extends BaseController try { header('Content-Type: application/json'); - $brandModel = $this->resolveModuleService('model.BrandModel'); + $brandModel = new \App\Modules\Advertising\Models\BrandModel(); $brands = $brandModel->getActiveBrands(); echo json_encode([ @@ -38,7 +38,7 @@ class BrandApiController extends BaseController try { header('Content-Type: application/json'); - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $landingTypes = $landingTypeModel->getAll(); echo json_encode([ @@ -58,7 +58,7 @@ class BrandApiController extends BaseController header('Content-Type: application/json'); $brandIdInt = (int) Sanitize::string($brandId); - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $landingTypes = $landingTypeModel->getByBrandId($brandIdInt); if (empty($landingTypes)) { @@ -90,7 +90,7 @@ class BrandApiController extends BaseController return; } - $brandModel = $this->resolveModuleService('model.BrandModel'); + $brandModel = new \App\Modules\Advertising\Models\BrandModel(); $id = $brandModel->create($input); echo json_encode([ @@ -124,7 +124,7 @@ class BrandApiController extends BaseController return; } - $brandModel = $this->resolveModuleService('model.BrandModel'); + $brandModel = new \App\Modules\Advertising\Models\BrandModel(); $success = $brandModel->update($id, $input); if ($success) { @@ -151,7 +151,7 @@ class BrandApiController extends BaseController return; } - $brandModel = $this->resolveModuleService('model.BrandModel'); + $brandModel = new \App\Modules\Advertising\Models\BrandModel(); $success = $brandModel->destroy($id); if ($success) { @@ -194,7 +194,7 @@ class BrandApiController extends BaseController return; } - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $id = $landingTypeModel->create($input); // Registrar no histórico @@ -234,7 +234,7 @@ class BrandApiController extends BaseController } // Obter dados antigos para histórico - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $oldData = $landingTypeModel->getById($id); // Validar template @@ -286,7 +286,7 @@ class BrandApiController extends BaseController } // Obter dados para histórico - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $oldData = $landingTypeModel->getById($id); $success = $landingTypeModel->destroy($id); @@ -333,7 +333,7 @@ class BrandApiController extends BaseController return; } - $landingTypeModel = $this->resolveModuleService('model.LandingTypeModel'); + $landingTypeModel = new \App\Modules\Advertising\Models\LandingTypeModel(); $landingType = $landingTypeModel->getById($landingTypeId); if (!$landingType) { diff --git a/crm/Modules/Advertising/Routes/api.php b/crm/Modules/Advertising/Routes/api.php index 284956a..b904282 100644 --- a/crm/Modules/Advertising/Routes/api.php +++ b/crm/Modules/Advertising/Routes/api.php @@ -1,4 +1,5 @@ get('/api/advertising/creative-filters/types', [CreativeFiltersApiController::class, 'getFilterTypes']); $router->get('/api/advertising/creative-filters/operators', [CreativeFiltersApiController::class, 'getFilterOperators']); diff --git a/crm/Modules/Advertising/Routes/web.php b/crm/Modules/Advertising/Routes/web.php index 097ceff..119d3e9 100644 --- a/crm/Modules/Advertising/Routes/web.php +++ b/crm/Modules/Advertising/Routes/web.php @@ -1,9 +1,12 @@ get('/advertising', [AdvertisingController::class, 'dashboard']); $router->get('/advertising/dashboard', [AdvertisingController::class, 'dashboard']); diff --git a/crm/Modules/Controllers/PagesController.php b/crm/Modules/Controllers/PagesController.php index e398766..9dcbcfb 100644 --- a/crm/Modules/Controllers/PagesController.php +++ b/crm/Modules/Controllers/PagesController.php @@ -351,7 +351,7 @@ class PagesController 'pagetitle' => 'Pages', 'title' => 'Profile Settings' ]); - View::render('@pages/profile/settings'); + View::render('@pages/profile-settings'); } ]); } diff --git a/crm/Modules/Controllers/PublicCampaignsController.php b/crm/Modules/Controllers/PublicCampaignsController.php index f6ab8fe..ab2ec39 100644 --- a/crm/Modules/Controllers/PublicCampaignsController.php +++ b/crm/Modules/Controllers/PublicCampaignsController.php @@ -54,7 +54,7 @@ class PublicCampaignsController extends BaseController 'page_name' => 'public-campaign-analytics', 'branding' => $branding, 'slug' => $slug, - 'page_content' => function() use ($branding, $slug, $stats, $filterOptions, $startDate, $endDate) { + 'page_content' => function() use ($branding, $slug, $redirect, $stats, $filterOptions, $startDate, $endDate) { View::render('layouts/page-title.php', [ 'pagetitle' => 'Campaign Analytics', 'title' => 'Campaign Performance' @@ -62,6 +62,7 @@ class PublicCampaignsController extends BaseController View::render('pages/public-campaign-analytics', [ 'branding' => $branding, 'slug' => $slug, + 'redirect' => $redirect, 'stats' => $stats, 'filterOptions' => $filterOptions, 'startDate' => $startDate, diff --git a/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php b/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php index c62eb84..d628889 100644 --- a/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php +++ b/crm/Modules/ErrorMonitoring/Controllers/ErrorMonitoringController.php @@ -846,4 +846,37 @@ class ErrorMonitoringController extends BaseController $this->errorResponse('Erro ao resolver: ' . $e->getMessage()); } } + + /** + * API: Limpar todos os erros + */ + public function apiClearAllErrors(): void + { + $this->requireAuth(); + + try { + $db = DatabaseManager::getInstance(); + + // Contar erros antes de apagar + $countResult = $db->fetch("SELECT COUNT(*) as total FROM error_logs"); + $totalErrors = $countResult['total'] ?? 0; + + if ($totalErrors === 0) { + $this->successResponse(['deleted_count' => 0], 'Nenhum erro encontrado para apagar'); + return; + } + + // Apagar todos os erros + $result = $db->query("DELETE FROM error_logs"); + + if ($result) { + $this->successResponse(['deleted_count' => $totalErrors], "Todos os {$totalErrors} erros foram apagados com sucesso"); + } else { + $this->errorResponse('Falha ao apagar erros'); + } + + } catch (Exception $e) { + $this->errorResponse('Erro ao apagar erros: ' . $e->getMessage()); + } + } } \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Models/ErrorLog.php b/crm/Modules/ErrorMonitoring/Models/ErrorLog.php index e1df43d..3e432c6 100644 --- a/crm/Modules/ErrorMonitoring/Models/ErrorLog.php +++ b/crm/Modules/ErrorMonitoring/Models/ErrorLog.php @@ -239,82 +239,4 @@ class ErrorLog return $stats; } - /** - * Inserir dados de teste - */ - public function insertTestData(): void - { - $testErrors = [ - [ - 'unique_id' => 'TEST-001', - 'project_name' => 'CRM Project', - 'environment' => 'development', - 'error_type' => 'Exception', - 'severity' => 'error', - 'message' => 'Division by zero in calculation module', - 'file_path' => '/app/Modules/Crm/Controllers/DealController.php', - 'line_number' => 156, - 'stack_trace' => "Stack trace:\n#0 /app/Modules/Crm/Controllers/DealController.php(156): calculateCommission()\n#1 /public/index.php(45): main()", - 'context_data' => json_encode(['deal_id' => 123, 'user_id' => 456]), - 'user_id' => 'user_456', - 'session_id' => 'sess_789', - 'request_id' => 'req_001', - 'ip_address' => '192.168.1.100', - 'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', - 'url' => 'http://localhost:8888/apps/crm/deals/123', - 'http_method' => 'POST', - 'occurrences' => 3, - 'first_seen' => '2024-01-15 10:30:00', - 'last_seen' => '2024-01-15 14:45:00' - ], - [ - 'unique_id' => 'TEST-002', - 'project_name' => 'CRM Project', - 'environment' => 'development', - 'error_type' => 'Error', - 'severity' => 'warning', - 'message' => 'Database connection timeout', - 'file_path' => '/app/Core/DatabaseManager.php', - 'line_number' => 89, - 'stack_trace' => "Stack trace:\n#0 /app/Core/DatabaseManager.php(89): connect()\n#1 /app/Modules/Auth/Controllers/AuthController.php(23): login()", - 'context_data' => json_encode(['attempt' => 3, 'timeout' => 30]), - 'user_id' => 'user_123', - 'session_id' => 'sess_456', - 'request_id' => 'req_002', - 'ip_address' => '192.168.1.101', - 'user_agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', - 'url' => 'http://localhost:8888/auth/login', - 'http_method' => 'POST', - 'occurrences' => 1, - 'first_seen' => '2024-01-15 11:15:00', - 'last_seen' => '2024-01-15 11:15:00' - ], - [ - 'unique_id' => 'TEST-003', - 'project_name' => 'CRM Project', - 'environment' => 'development', - 'error_type' => 'Exception', - 'severity' => 'critical', - 'message' => 'Memory limit exceeded in report generation', - 'file_path' => '/app/Modules/Analytics/Controllers/ReportController.php', - 'line_number' => 234, - 'stack_trace' => "Stack trace:\n#0 /app/Modules/Analytics/Controllers/ReportController.php(234): generateReport()\n#1 /app/Modules/Analytics/Controllers/ReportController.php(189): processData()", - 'context_data' => json_encode(['report_type' => 'monthly', 'data_size' => '2GB']), - 'user_id' => 'user_789', - 'session_id' => 'sess_012', - 'request_id' => 'req_003', - 'ip_address' => '192.168.1.102', - 'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36', - 'url' => 'http://localhost:8888/apps/analytics/reports/monthly', - 'http_method' => 'GET', - 'occurrences' => 5, - 'first_seen' => '2024-01-14 09:00:00', - 'last_seen' => '2024-01-15 16:30:00' - ] - ]; - - foreach ($testErrors as $error) { - $this->create($error); - } - } } \ No newline at end of file diff --git a/crm/Modules/ErrorMonitoring/Routes/web.php b/crm/Modules/ErrorMonitoring/Routes/web.php index 1a59c2c..1281678 100644 --- a/crm/Modules/ErrorMonitoring/Routes/web.php +++ b/crm/Modules/ErrorMonitoring/Routes/web.php @@ -30,6 +30,7 @@ $router->get('/api/error-monitoring/dashboard', [ErrorMonitoringController::clas $router->get('/api/error-monitoring/errors', [ErrorMonitoringController::class, 'apiErrors']); $router->get('/api/error-monitoring/recent-errors', [ErrorMonitoringController::class, 'apiRecentErrors']); $router->post('/api/error-monitoring/resolve', [ErrorMonitoringController::class, 'apiResolveError']); +$router->post('/api/error-monitoring/clear-all', [ErrorMonitoringController::class, 'apiClearAllErrors']); // JavaScript error capture (POST only) $router->post('/api/error-monitoring/js-error', [ErrorMonitoringController::class, 'apiCaptureJsError']); diff --git a/crm/Modules/ErrorMonitoring/Views/errors.php b/crm/Modules/ErrorMonitoring/Views/errors.php index e06ab04..0ddddbe 100644 --- a/crm/Modules/ErrorMonitoring/Views/errors.php +++ b/crm/Modules/ErrorMonitoring/Views/errors.php @@ -45,7 +45,10 @@ use App\Core\View; Apply Filters + diff --git a/crm/Modules/Routes/web.php b/crm/Modules/Routes/web.php index d31dabc..21a00bf 100644 --- a/crm/Modules/Routes/web.php +++ b/crm/Modules/Routes/web.php @@ -7,7 +7,7 @@ $router = Router::getInstance(); // --- PAGES ROUTES --- $router->get('/apps/pages/starter', [PagesController::class, 'starter']); $router->get('/apps/pages/profile', [PagesController::class, 'profile']); -$router->get('/apps/pages/profile-settings/', [PagesController::class, 'pagesProfileSettingsPage']); +$router->get('/apps/pages/profile-settings', [PagesController::class, 'pagesProfileSettingsPage']); $router->get('/apps/pages/team', [PagesController::class, 'team']); $router->get('/apps/pages/timeline', [PagesController::class, 'timeline']); $router->get('/apps/pages/faqs', [PagesController::class, 'faqs']); diff --git a/crm/Modules/Users/Controllers/UserController.php b/crm/Modules/Users/Controllers/UserController.php index 32ae984..74092ef 100644 --- a/crm/Modules/Users/Controllers/UserController.php +++ b/crm/Modules/Users/Controllers/UserController.php @@ -287,6 +287,7 @@ class UserController extends BaseController } } + /** * Admin users management page. */ @@ -373,16 +374,12 @@ class UserController extends BaseController public function apiGetUsers(): void { try { - // Check if user is logged in and is admin, or if using API key - $isLoggedIn = Auth::check(); - $isAdmin = $isLoggedIn && Auth::isAdmin(); - $hasApiKey = !empty($_SERVER['HTTP_AUTHORIZATION']) && - stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0; - - if (!$isAdmin && !$hasApiKey) { + // Middleware já faz autenticação (apiOrAuth) + // Verificar se é admin + if (!Auth::isAdmin()) { http_response_code(403); header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); exit; } @@ -390,9 +387,13 @@ class UserController extends BaseController $sort = Sanitize::string($_GET['sort'] ?? 'name'); $page = max(1, (int)($_GET['page'] ?? 1)); $perPage = max(1, min(100, (int)($_GET['per_page'] ?? 10))); + $showDeleted = filter_var($_GET['show_deleted'] ?? false, FILTER_VALIDATE_BOOLEAN); + + // Debug log + error_log("API Users - show_deleted: " . ($showDeleted ? 'true' : 'false')); - $users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage); - $totalUsers = $this->userModel->getTotalForAdmin($search); + $users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage, $showDeleted); + $totalUsers = $this->userModel->getTotalForAdmin($search, $showDeleted); $totalPages = ceil($totalUsers / $perPage); header('Content-Type: application/json'); @@ -413,18 +414,66 @@ class UserController extends BaseController exit; } + /** + * API: Reset user password + */ + public function apiResetPassword(int $id): void + { + try { + // Middleware já faz autenticação (apiOrAuth) + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); + exit; + } + + // Don't allow resetting your own password + if ($id === Auth::id()) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Não pode fazer reset da sua própria password']); + exit; + } + + // Generate new random password + $newPassword = bin2hex(random_bytes(8)); // 16 character password + $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT); + + $success = $this->userModel->updatePassword($id, $hashedPassword); + + if ($success) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Password reset com sucesso', + 'new_password' => $newPassword + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao reset password']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_reset_password', 'userId' => $id]); + 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(); - + // Middleware já faz autenticação (apiOrAuth) if (!Auth::isAdmin()) { http_response_code(403); header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); exit; } @@ -457,12 +506,11 @@ class UserController extends BaseController public function apiCreateUser(): void { try { - $this->requireAuth(); - + // Middleware já faz autenticação (apiOrAuth) if (!Auth::isAdmin()) { http_response_code(403); header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); exit; } @@ -521,12 +569,11 @@ class UserController extends BaseController public function apiUpdateUser(int $id): void { try { - $this->requireAuth(); - + // Middleware já faz autenticação (apiOrAuth) if (!Auth::isAdmin()) { http_response_code(403); header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); exit; } @@ -588,12 +635,11 @@ class UserController extends BaseController public function apiDeleteUser(int $id): void { try { - $this->requireAuth(); - + // Middleware já faz autenticação (apiOrAuth) if (!Auth::isAdmin()) { http_response_code(403); header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); + echo json_encode(['success' => false, 'message' => 'Acesso negado']); exit; } @@ -922,39 +968,348 @@ class UserController extends BaseController } /** - * API: Get recent activity + * View individual role */ - public function apiGetRecentActivity(): void + public function viewRole(int $id): void { try { - // Check if user is logged in and is admin, or if using API key - $isLoggedIn = Auth::check(); - $isAdmin = $isLoggedIn && Auth::isAdmin(); - $hasApiKey = !empty($_SERVER['HTTP_AUTHORIZATION']) && - stripos($_SERVER['HTTP_AUTHORIZATION'], 'Bearer ') === 0; + $this->requireAuth(); - if (!$isAdmin && !$hasApiKey) { + if (!Auth::isAdmin()) { http_response_code(403); - header('Content-Type: application/json'); - echo json_encode(['error' => 'Acesso negado']); - exit; + echo 'Acesso negado'; + return; } - // Get real activity data from database - $activityModel = new \App\Modules\Users\Models\UserActivityModel(); - $activities = $activityModel->getAllRecentActivities(50); + $roleModel = new \App\Modules\Users\Models\RoleModel(); + $role = $roleModel->getRoleWithUsers($id); - header('Content-Type: application/json'); - echo json_encode([ - 'success' => true, - 'data' => $activities + if (!$role) { + http_response_code(404); + echo 'Perfil não encontrado'; + return; + } + + View::render('layouts/main.php', [ + 'title' => 'Ver Perfil - ' . $role['name'], + 'page_content' => function() use ($role) { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Ver Perfil: ' . $role['name'] + ]); + View::render('@users/role-view.php', ['role' => $role]); + } ]); } catch (\Exception $e) { - ErrorReporter::report($e, ['context' => 'api_get_recent_activity']); + ErrorReporter::report($e, ['context' => 'view_role', 'role_id' => $id]); http_response_code(500); - header('Content-Type: application/json'); - echo json_encode(['error' => 'Erro interno do servidor']); + echo 'Erro interno do servidor'; } - exit; } -} \ No newline at end of file + + /** + * Edit individual role + */ + public function editRole(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + echo 'Acesso negado'; + return; + } + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + $role = $roleModel->find($id); + + if (!$role) { + http_response_code(404); + echo 'Perfil não encontrado'; + return; + } + + // Parse permissions if JSON + if (!empty($role['permissions'])) { + $role['permissions'] = json_decode($role['permissions'], true) ?: []; + } else { + $role['permissions'] = []; + } + + View::render('layouts/main.php', [ + 'title' => 'Editar Perfil - ' . $role['name'], + 'page_content' => function() use ($role) { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Editar Perfil: ' . $role['name'] + ]); + View::render('@users/role-edit.php', ['role' => $role]); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'edit_role', 'role_id' => $id]); + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + + // ========================================== + // ROLES API METHODS + // ========================================== + + /** + * API: Get all roles + */ + public function apiGetRoles(): void + { + try { + $this->apiOrAuthRequired(); + + // If authenticated via session, check if admin + if (Auth::check() && !Auth::isAdmin()) { + $this->errorResponse('Acesso negado - requer permissões de administrador', 403); + return; + } + // If using Bearer token, allow access (API key has full access) + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + $roles = $roleModel->getAllWithUserCount(); + + // Format roles for frontend + $formattedRoles = array_map(function($role) { + // Parse permissions + $permissions = []; + if (!empty($role['permissions'])) { + $permissions = json_decode($role['permissions'], true) ?: []; + } + + return [ + 'id' => (int)$role['id'], + 'name' => $role['name'], + 'description' => $role['description'] ?? '', + 'permissions' => $permissions, + 'users_count' => (int)($role['users_count'] ?? 0), + 'users' => [], // Empty for listing, will be loaded on detail view + 'status' => $role['is_active'] ? 'active' : 'inactive', + 'type' => $this->getRoleType($role['name']), + 'created_at' => $role['created_at'] ?? null, + 'updated_at' => $role['updated_at'] ?? null + ]; + }, $roles); + + $this->successResponse([ + 'roles' => $formattedRoles + ], 'Roles retrieved successfully'); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_roles']); + $this->errorResponse('Erro ao carregar perfis', 500); + } + } + + /** + * API: Get single role + */ + public function apiGetRole(int $id): void + { + try { + $this->apiOrAuthRequired(); + + // If authenticated via session, check if admin + if (Auth::check() && !Auth::isAdmin()) { + $this->errorResponse('Acesso negado', 403); + return; + } + // If using Bearer token, allow access (API key has full access) + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + $role = $roleModel->getRoleWithUsers($id); + + if (!$role) { + $this->errorResponse('Perfil não encontrado', 404); + return; + } + + $this->successResponse([ + 'role' => $role + ], 'Role retrieved successfully'); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_role', 'role_id' => $id]); + $this->errorResponse('Erro ao carregar perfil', 500); + } + } + + /** + * API: Create role + */ + public function apiCreateRole(): void + { + try { + $this->apiOrAuthRequired(); + + // If authenticated via session, check if admin + if (Auth::check() && !Auth::isAdmin()) { + $this->errorResponse('Acesso negado', 403); + return; + } + // If using Bearer token, allow access (API key has full access) + + $name = Sanitize::string($_POST['name'] ?? ''); + $description = Sanitize::string($_POST['description'] ?? ''); + $permissions = $_POST['permissions'] ?? []; + + if (empty($name)) { + $this->errorResponse('Nome do perfil é obrigatório', 400); + return; + } + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + + if ($roleModel->roleNameExists($name)) { + $this->errorResponse('Já existe um perfil com este nome', 409); + return; + } + + $roleId = $roleModel->createRole([ + 'name' => $name, + 'description' => $description, + 'permissions' => $permissions, + 'is_active' => 1 + ]); + + if ($roleId) { + $this->successResponse([ + 'role_id' => $roleId + ], 'Perfil criado com sucesso'); + } else { + $this->errorResponse('Erro ao criar perfil', 500); + } + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_create_role']); + $this->errorResponse('Erro ao criar perfil', 500); + } + } + + /** + * API: Update role + */ + public function apiUpdateRole(int $id): void + { + try { + $this->apiOrAuthRequired(); + + // If authenticated via session, check if admin + if (Auth::check() && !Auth::isAdmin()) { + $this->errorResponse('Acesso negado', 403); + return; + } + // If using Bearer token, allow access (API key has full access) + + parse_str(file_get_contents('php://input'), $_PUT); + + $name = Sanitize::string($_PUT['name'] ?? ''); + $description = Sanitize::string($_PUT['description'] ?? ''); + $permissions = $_PUT['permissions'] ?? []; + + if (empty($name)) { + $this->errorResponse('Nome do perfil é obrigatório', 400); + return; + } + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + + if ($roleModel->roleNameExists($name, $id)) { + $this->errorResponse('Já existe outro perfil com este nome', 409); + return; + } + + $success = $roleModel->updateRole($id, [ + 'name' => $name, + 'description' => $description, + 'permissions' => $permissions + ]); + + if ($success) { + $this->successResponse([], 'Perfil atualizado com sucesso'); + } else { + $this->errorResponse('Erro ao atualizar perfil', 500); + } + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_update_role', 'role_id' => $id]); + $this->errorResponse('Erro ao atualizar perfil', 500); + } + } + + /** + * API: Delete role + */ + public function apiDeleteRole(int $id): void + { + try { + $this->apiOrAuthRequired(); + + // If authenticated via session, check if admin + if (Auth::check() && !Auth::isAdmin()) { + $this->errorResponse('Acesso negado', 403); + return; + } + // If using Bearer token, allow access (API key has full access) + + $roleModel = new \App\Modules\Users\Models\RoleModel(); + + // Check if role exists + $role = $roleModel->find($id); + if (!$role) { + $this->errorResponse('Perfil não encontrado', 404); + return; + } + + // Prevent deletion of admin role + if ($role['name'] === 'admin' || $role['name'] === 'super_admin') { + $this->errorResponse('Não é possível eliminar o perfil de administrador', 403); + return; + } + + // Check if role has users + $usersWithRole = $this->db->fetch( + "SELECT COUNT(*) as count FROM users WHERE role = ? AND is_active = 1", + [$role['name']] + ); + + if (($usersWithRole['count'] ?? 0) > 0) { + $this->errorResponse('Não é possível eliminar um perfil que está a ser usado por utilizadores', 409); + return; + } + + $success = $roleModel->deleteRole($id); + + if ($success) { + $this->successResponse([], 'Perfil eliminado com sucesso'); + } else { + $this->errorResponse('Erro ao eliminar perfil', 500); + } + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_delete_role', 'role_id' => $id]); + $this->errorResponse('Erro ao eliminar perfil', 500); + } + } + + /** + * Helper: Get role type based on name + */ + private function getRoleType(string $name): string + { + $name = strtolower($name); + if (in_array($name, ['admin', 'administrator', 'super_admin'])) { + return 'admin'; + } elseif (in_array($name, ['editor', 'moderator', 'manager'])) { + return 'editor'; + } + return 'user'; + } +} diff --git a/crm/Modules/Users/Models/UserActivityModel.php b/crm/Modules/Users/Models/UserActivityModel.php deleted file mode 100644 index 2ef3040..0000000 --- a/crm/Modules/Users/Models/UserActivityModel.php +++ /dev/null @@ -1,111 +0,0 @@ -db = DatabaseManager::getInstance(); - } - - /** - * Log user activity - */ - public function logActivity(int $userId, string $action, string $description, array $metadata = []): bool - { - try { - $sql = "INSERT INTO user_activities (user_id, action, description, metadata, ip_address, user_agent) - VALUES (?, ?, ?, ?, ?, ?)"; - - $params = [ - $userId, - $action, - $description, - json_encode($metadata), - $_SERVER['REMOTE_ADDR'] ?? null, - $_SERVER['HTTP_USER_AGENT'] ?? null - ]; - - return $this->db->query($sql, $params) > 0; - } catch (\Exception $e) { - return false; - } - } - - /** - * Get recent activities for a user - */ - public function getRecentActivities(int $userId, int $limit = 10): array - { - try { - $sql = "SELECT id, user_id, action, description, metadata, ip_address, created_at - FROM user_activities - WHERE user_id = ? - ORDER BY created_at DESC - LIMIT ?"; - - return $this->db->fetchAll($sql, [$userId, $limit]) ?: []; - } catch (\Exception $e) { - return []; - } - } - - /** - * Get all recent activities (admin) - */ - public function getAllRecentActivities(int $limit = 50): array - { - try { - $sql = "SELECT ua.id, ua.user_id, ua.action, ua.description, ua.metadata, - ua.ip_address, ua.created_at, u.username, u.email - FROM user_activities ua - LEFT JOIN users u ON ua.user_id = u.id - ORDER BY ua.created_at DESC - LIMIT ?"; - - return $this->db->fetchAll($sql, [$limit]) ?: []; - } catch (\Exception $e) { - return []; - } - } - - /** - * Get activity statistics - */ - public function getActivityStats(int $days = 30): array - { - try { - $sql = "SELECT - COUNT(*) as total_activities, - COUNT(DISTINCT user_id) as active_users, - DATE(created_at) as activity_date - FROM user_activities - WHERE created_at >= DATE_SUB(NOW(), INTERVAL ? DAY) - GROUP BY DATE(created_at) - ORDER BY activity_date DESC"; - - return $this->db->fetchAll($sql, [$days]) ?: []; - } catch (\Exception $e) { - return []; - } - } - - /** - * Clean old activities (older than specified days) - */ - public function cleanOldActivities(int $days = 90): int - { - try { - $sql = "DELETE FROM user_activities - WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)"; - - return $this->db->query($sql, [$days]); - } catch (\Exception $e) { - return 0; - } - } -} diff --git a/crm/Modules/Users/Models/UserModel.php b/crm/Modules/Users/Models/UserModel.php index d7e0e14..0627cb5 100644 --- a/crm/Modules/Users/Models/UserModel.php +++ b/crm/Modules/Users/Models/UserModel.php @@ -213,7 +213,8 @@ class UserModel FROM users u WHERE - u.id > 0"; + u.id > 0 + AND u.is_active != -1"; $params = []; @@ -244,35 +245,15 @@ class UserModel } } - /** - * 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; - } - } - /** * Get all users for admin with pagination and search */ - public function getAllForAdmin(string $search = '', string $sort = 'name', int $page = 1, int $perPage = 10): array + public function getAllForAdmin(string $search = '', string $sort = 'name', int $page = 1, int $perPage = 10, bool $showDeleted = false): array { try { $offset = ($page - 1) * $perPage; - $sql = "SELECT + $sql = "SELECT u.id, u.username, u.first_name, @@ -281,13 +262,22 @@ class UserModel 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, - u.last_login - FROM users u - WHERE u.id > 0"; + u.updated_at + FROM + users u + WHERE + u.id > 0 + AND u.is_active != -1"; $params = []; @@ -301,12 +291,12 @@ class UserModel } // Add sorting - $allowedSorts = ['name', 'email', 'role', 'created_at', 'last_login']; + $allowedSorts = ['name', 'email', 'created_at', 'role', 'is_active']; if (in_array($sort, $allowedSorts)) { if ($sort === 'name') { $sql .= " ORDER BY u.first_name, u.last_name"; } else { - $sql .= " ORDER BY u.{$sort}"; + $sql .= " ORDER BY u." . $sort; } } else { $sql .= " ORDER BY u.created_at DESC"; @@ -323,10 +313,15 @@ class UserModel /** * Get total count of users for admin with search */ - public function getTotalForAdmin(string $search = ''): int + public function getTotalForAdmin(string $search = '', bool $showDeleted = false): int { try { $sql = "SELECT COUNT(*) as total FROM users u WHERE u.id > 0"; + + if (!$showDeleted) { + $sql .= " AND u.is_active != -1"; + } + $params = []; if (!empty($search)) { @@ -346,43 +341,132 @@ class UserModel } /** - * Find user for admin by ID + * Delete a user by ID */ - public function findForAdmin(int $id): ?array + public function delete(int $id): bool { try { if ($id <= 0) { - return null; + return false; } - $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, - u.last_login - FROM users u - WHERE u.id = ?"; - - $result = $this->db->fetch($sql, [$id]); - return $result ?: null; + // 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 null; + return false; + } + } + + /** + * Delete a user by ID for admin (soft delete) + */ + public function deleteForAdmin(int $id): bool + { + try { + if ($id <= 0) { + return false; + } + + // Soft delete - mark as deleted (status = -1) + $sql = "UPDATE users SET is_active = -1, updated_at = NOW() WHERE id = ?"; + $result = $this->db->query($sql, [$id]); + + return $result > 0; + } catch (\Exception $e) { + return false; + } + } + + /** + * Create a user for admin + */ + public function createForAdmin(array $userData): int|false + { + try { + $sql = "INSERT INTO users (username, first_name, last_name, email, password, role, is_active, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())"; + + $hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT); + + $result = $this->db->query($sql, [ + $userData['username'], + $userData['first_name'], + $userData['last_name'], + $userData['email'], + $hashedPassword, + $userData['role'], + $userData['is_active'] + ]); + + return $result ? $this->db->lastInsertId() : false; + } catch (\Exception $e) { + return false; + } + } + + /** + * Update a user for admin + */ + public function updateForAdmin(int $id, array $userData): bool + { + try { + if ($id <= 0) { + return false; + } + + $sql = "UPDATE users SET + username = ?, + first_name = ?, + last_name = ?, + email = ?, + role = ?, + is_active = ?, + updated_at = NOW()"; + + $params = [ + $userData['username'], + $userData['first_name'], + $userData['last_name'], + $userData['email'], + $userData['role'], + $userData['is_active'] + ]; + + // Only update password if provided + if (!empty($userData['password'])) { + $sql .= ", password = ?"; + $params[] = password_hash($userData['password'], PASSWORD_DEFAULT); + } + + $sql .= " WHERE id = ?"; + $params[] = $id; + + $result = $this->db->query($sql, $params); + return $result > 0; + } catch (\Exception $e) { + return false; + } + } + + /** + * Update user password + */ + public function updatePassword(int $id, string $hashedPassword): bool + { + try { + if ($id <= 0 || empty($hashedPassword)) { + return false; + } + + $sql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?"; + $result = $this->db->query($sql, [$hashedPassword, $id]); + + return $result > 0; + } catch (\Exception $e) { + return false; } } } diff --git a/crm/Modules/Users/Routes/api.php b/crm/Modules/Users/Routes/api.php index d825c05..4f59297 100644 --- a/crm/Modules/Users/Routes/api.php +++ b/crm/Modules/Users/Routes/api.php @@ -2,39 +2,49 @@ use App\Modules\Users\Controllers\UserController; use App\Core\AuthMiddleware; +// Middleware para autenticação: aceita sessão ativa OU Bearer token +$authMiddleware = [AuthMiddleware::class, 'apiOrAuth']; + // Admin Users API Routes $router->get( '/api/admin/users', [UserController::class, 'apiGetUsers'], - [AuthMiddleware::class, 'apiOrAuth'] + $authMiddleware ); $router->get( '/api/admin/users/{int:id}', [UserController::class, 'apiGetUser'], - [AuthMiddleware::class, 'apiOrAuth'] + $authMiddleware ); $router->post( '/api/admin/users', [UserController::class, 'apiCreateUser'], - [AuthMiddleware::class, 'apiOrAuth'] + $authMiddleware ); $router->put( '/api/admin/users/{int:id}', [UserController::class, 'apiUpdateUser'], - [AuthMiddleware::class, 'apiOrAuth'] + $authMiddleware ); $router->delete( '/api/admin/users/{int:id}', [UserController::class, 'apiDeleteUser'], - [AuthMiddleware::class, 'apiOrAuth'] + $authMiddleware ); -$router->get( - '/api/admin/users/recent-activity', - [UserController::class, 'apiGetRecentActivity'], - [AuthMiddleware::class, 'apiOrAuth'] -); \ No newline at end of file +$router->post( + '/api/admin/users/{int:id}/reset-password', + [UserController::class, 'apiResetPassword'], + $authMiddleware +); + +// Roles API Routes (authentication handled in controller method) +$router->get('/api/users/roles', [UserController::class, 'apiGetRoles']); +$router->get('/api/users/roles/{int:id}', [UserController::class, 'apiGetRole']); +$router->post('/api/users/roles', [UserController::class, 'apiCreateRole']); +$router->put('/api/users/roles/{int:id}', [UserController::class, 'apiUpdateRole']); +$router->delete('/api/users/roles/{int:id}', [UserController::class, 'apiDeleteRole']); \ No newline at end of file diff --git a/crm/Modules/Users/Routes/web.php b/crm/Modules/Users/Routes/web.php index a8404c2..fbe96a3 100644 --- a/crm/Modules/Users/Routes/web.php +++ b/crm/Modules/Users/Routes/web.php @@ -29,12 +29,26 @@ $router->get( [AuthMiddleware::class, 'requireAuth'] ); + $router->get( '/admin/roles', [UserController::class, 'adminRoles'], [AuthMiddleware::class, 'requireAuth'] ); +// Individual role management +$router->get( + '/admin/roles/{int:id}', + [UserController::class, 'viewRole'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->get( + '/admin/roles/{int:id}/edit', + [UserController::class, 'editRole'], + [AuthMiddleware::class, 'requireAuth'] +); + // --- INDIVIDUAL USER MANAGEMENT ROUTES (Missing functionality) --- // View specific user profile (admin function) $router->get( diff --git a/crm/Modules/Users/Views/admin-roles.php b/crm/Modules/Users/Views/admin-roles.php index 1d36bba..ba55961 100644 --- a/crm/Modules/Users/Views/admin-roles.php +++ b/crm/Modules/Users/Views/admin-roles.php @@ -295,52 +295,18 @@ document.addEventListener('DOMContentLoaded', function() { sort: this.sortBy })); const data = await response.json(); - this.roles = data.roles || []; + + if (data.success) { + this.roles = data.data.roles || []; + } else { + console.error('Erro na API:', data.message); + alert('Erro ao carregar perfis: ' + data.message); + this.roles = []; + } } catch (error) { console.error('Erro ao carregar perfis:', error); - this.roles = [ - { - id: 1, - name: 'Administrador', - key: 'admin', - description: 'Acesso total ao sistema', - permissions: ['users.view', 'users.create', 'users.edit', 'users.delete', 'content.view', 'content.create', 'content.edit', 'content.delete', 'reports.view', 'reports.create', 'system.settings', 'system.admin'], - users_count: 3, - users: [ - { id: 1, name: 'Admin User', avatar: '/assets/images/users/avatar-1.jpg' }, - { id: 2, name: 'Manager User', avatar: '/assets/images/users/avatar-2.jpg' } - ], - status: 'active', - type: 'admin' - }, - { - id: 2, - name: 'Editor', - key: 'editor', - description: 'Pode criar e editar conteúdo', - permissions: ['content.view', 'content.create', 'content.edit'], - users_count: 8, - users: [ - { id: 3, name: 'Editor User', avatar: '/assets/images/users/avatar-3.jpg' }, - { id: 4, name: 'Writer User', avatar: '/assets/images/users/avatar-4.jpg' } - ], - status: 'active', - type: 'editor' - }, - { - id: 3, - name: 'Utilizador', - key: 'user', - description: 'Acesso básico ao sistema', - permissions: ['content.view'], - users_count: 15, - users: [ - { id: 5, name: 'Regular User', avatar: '/assets/images/users/avatar-5.jpg' } - ], - status: 'active', - type: 'user' - } - ]; + alert('Erro ao carregar perfis. Verifique a consola para mais detalhes.'); + this.roles = []; } finally { this.loading = false; } diff --git a/crm/Modules/Users/Views/admin-users.php b/crm/Modules/Users/Views/admin-users.php index b3c4809..4c2a26f 100644 --- a/crm/Modules/Users/Views/admin-users.php +++ b/crm/Modules/Users/Views/admin-users.php @@ -3,14 +3,16 @@ use App\Core\AssetPath; use App\Core\OutputSanitize; ?> -
Inativos
+Eliminados
+
+
+
+ Short link:
+
+
Total Redirects
-Active Redirects
-Inactive Redirects
-Total Clicks
-| Name | -Target URL | -Status | -Created | -Actions | -
|---|---|---|---|---|
|
-
-
-
-
-
-
-
-
-
- = htmlspecialchars($redirect['name']) ?>- = htmlspecialchars($redirect['id']) ?> - |
- - - = htmlspecialchars($redirect['target_url']) ?> - - | -- - Active - - Inactive - - Deleted - - | -- = date('M j, Y', strtotime($redirect['created_at'])) ?> - | -
-
-
-
-
-
-
- |
-
Set up your source and target URLs with optional filters
-Target by country, browser, device, time, and more
-Monitor performance and user behavior in real-time
-A carregar dados do redirect...
-A carregar redirects...
-Crie o seu primeiro redirect para começar
- -| Nome | -URL de Origem | -URL de Destino | -Estado | -Tipo | -Rastreamento | -Criado | -Ações | -
|---|---|---|---|---|---|---|---|
|
-
-
-
-
-
-
-
-
-
-
-
- |
- - - | -- - | -- - | -- - | -- - | -- - | -
-
-
-
-
-
-
- |
-
Name: = htmlspecialchars($redirect['name']) ?>
-Status: - - = $redirect['status'] == 1 ? 'Active' : 'Inactive' ?> - -
-Redirect Type: = htmlspecialchars($redirect['redirect_type']) ?>
-Tracking: - - = $redirect['tracking_enabled'] ? 'Enabled' : 'Disabled' ?> - -
-Created: = date('M j, Y H:i', strtotime($redirect['created_at'])) ?>
-Updated: = date('M j, Y H:i', strtotime($redirect['updated_at'])) ?>
- -Expires: = date('M j, Y H:i', strtotime($redirect['expires_at'])) ?>
- - -Max Clicks: = number_format($redirect['max_clicks']) ?>
- -= htmlspecialchars($redirect['source_url']) ?>
-= htmlspecialchars($redirect['target_url']) ?>
-= $redirect['fallback_url'] ? htmlspecialchars($redirect['fallback_url']) : 'None' ?>
-Partilha este link para permitir acesso público aos analytics deste redirect
- -No filters configured. All visitors will be redirected to the target URL.
- -| Type | -Value | -Operator | -Priority | -Status | -Actions | -
|---|---|---|---|---|---|
| = htmlspecialchars(ucfirst($filter['filter_type'])) ?> | -= htmlspecialchars($filter['filter_value']) ?> | -= htmlspecialchars(ucfirst(str_replace('_', ' ', $filter['filter_operator']))) ?> | -= $filter['priority'] ?> | -- - = $filter['is_active'] ? 'Active' : 'Inactive' ?> - - | -- - - | -
Total Clicks
-Unique Clicks
-Unique IPs
-Avg Response
-No recent activity
- -- = date('M j, Y H:i', strtotime($activity['timestamp'])) ?> - - • = htmlspecialchars($activity['country_code']) ?> - - - • = htmlspecialchars($activity['browser']) ?> - -
-Total de Cliques
-Cliques Únicos
-IPs Únicos
-Tempo Médio de Resposta
-| País | -Cliques | -Percentagem | -
|---|---|---|
| - | - | - - | -
| Nenhum dado disponível | -||
| Dispositivo | -Cliques | -Percentagem | -
|---|---|---|
| - | - | - - | -
| Nenhum dado disponível | -||
If you can not find answer to your question in our FAQ, you can always contact us or email us. We will answer you shortly!
+Encontre aqui respostas sobre como utilizar o MoneyFlix Redirect System - criar redirects, aceder a analytics e gerir as suas campanhas.
/public/analytics/{analytics_slug}. Este link é público e pode ser partilhado com terceiros para visualização de estatísticas.
/r/{cuid}. Por exemplo: redirect.moneyflix.com/r/mf_bonus. Este link redireciona para o URL de destino e regista a estatística do acesso.
/public/analytics/{slug}) são acessíveis a qualquer pessoa com o link, permitindo partilhar estatísticas com clientes ou parceiros sem necessidade de login.