Files
MoneyFlix/crm/Core/DashboardWidgetManager.php
1sonhador 9d43854277 feat: Initial MoneyFlix project setup
- Created separate MoneyFlix project directory
- Copied Node.js redirector from production server
- Added CRM PHP code (Redirects module, Core classes, Config, Routes, Views)
- Created comprehensive documentation (README_MONEYFLIX.md)
- Added sync script to keep CRM code updated (sync-from-crm.sh)
- Configured .gitignore for Node.js and PHP
- Set up proper project structure for multi-client isolation

This separates MoneyFlix from the main CRM to avoid confusion
between different client systems and provides a dedicated
environment for MoneyFlix-specific development and maintenance.
2025-10-03 12:09:41 +01:00

295 lines
9.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Core;
use App\Core\DatabaseManager;
use App\Core\Logger;
use App\Core\ErrorReporter;
/**
* Dashboard Widget Manager
*
* Manages modular dashboard widgets system allowing modules to register
* widgets and users to customize their dashboard layout and content.
*/
class DashboardWidgetManager
{
private ?DatabaseManager $db = null;
private ?Logger $logger = null;
private static ?self $instance = null;
public function __construct()
{
// Lazy loading - não inicializar aqui
}
private function getDb(): DatabaseManager
{
if ($this->db === null) {
$this->db = DatabaseManager::getInstance();
}
return $this->db;
}
private function getLogger(): Logger
{
if ($this->logger === null) {
$this->logger = new Logger();
}
return $this->logger;
}
/**
* Get singleton instance
*/
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Register a widget from a module
*
* @param string $widgetId Unique widget identifier
* @param string $moduleName Module that provides this widget
* @param string $widgetName Display name
* @param string $widgetClass PHP class that renders the widget
* @param array $config Widget configuration
* @return bool Success status
*/
public function registerWidget(
string $widgetId,
string $moduleName,
string $widgetName,
string $widgetClass,
array $config = []
): bool {
try {
$defaultConfig = [
'description' => $config['description'] ?? '',
'method' => $config['method'] ?? 'render',
'size' => $config['size'] ?? 'medium',
'category' => $config['category'] ?? 'general',
'default_config' => $config['default_config'] ?? null
];
$this->getDb()->query("
INSERT INTO dashboard_widgets (
widget_id, module_name, widget_name, widget_description,
widget_class, widget_method, default_config, widget_size,
widget_category, is_active
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
ON DUPLICATE KEY UPDATE
widget_name = VALUES(widget_name),
widget_description = VALUES(widget_description),
widget_class = VALUES(widget_class),
widget_method = VALUES(widget_method),
default_config = VALUES(default_config),
widget_size = VALUES(widget_size),
widget_category = VALUES(widget_category),
updated_at = CURRENT_TIMESTAMP
", [
$widgetId,
$moduleName,
$widgetName,
$defaultConfig['description'],
$widgetClass,
$defaultConfig['method'],
$defaultConfig['default_config'] ? json_encode($defaultConfig['default_config']) : null,
$defaultConfig['size'],
$defaultConfig['category']
]);
$this->getLogger()->info("Widget registered: {$widgetId} from module {$moduleName}");
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
$this->getLogger()->error("Failed to register widget {$widgetId}: " . $e->getMessage());
return false;
}
}
/**
* Get available widgets for a user
*
* @param int $userId User ID
* @return array Available widgets
*/
public function getAvailableWidgets(int $userId): array
{
try {
return $this->getDb()->fetchAll("
SELECT
dw.*,
udw.is_visible,
udw.position_order,
udw.widget_config as user_config,
udw.widget_size as user_size
FROM dashboard_widgets dw
LEFT JOIN user_dashboard_widgets udw ON dw.widget_id = udw.widget_id AND udw.user_id = ?
WHERE dw.is_active = 1
ORDER BY dw.widget_category, dw.widget_name
", [$userId]);
} catch (\Exception $e) {
ErrorReporter::report($e);
return [];
}
}
/**
* Get user's dashboard widgets in display order
*
* @param int $userId User ID
* @return array User's active widgets
*/
public function getUserDashboardWidgets(int $userId): array
{
try {
return $this->getDb()->fetchAll("
SELECT
dw.*,
udw.position_order,
udw.widget_config as user_config,
COALESCE(udw.widget_size, dw.widget_size) as effective_size
FROM dashboard_widgets dw
INNER JOIN user_dashboard_widgets udw ON dw.widget_id = udw.widget_id
WHERE udw.user_id = ? AND udw.is_visible = 1 AND dw.is_active = 1
ORDER BY udw.position_order ASC, dw.widget_name ASC
", [$userId]);
} catch (\Exception $e) {
ErrorReporter::report($e);
return [];
}
}
/**
* Update user widget configuration
*
* @param int $userId User ID
* @param string $widgetId Widget ID
* @param array $config Widget configuration
* @return bool Success status
*/
public function updateUserWidget(int $userId, string $widgetId, array $config): bool
{
try {
$this->getDb()->query("
INSERT INTO user_dashboard_widgets (
user_id, widget_id, position_order, widget_size,
widget_config, is_visible
) VALUES (?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
position_order = VALUES(position_order),
widget_size = VALUES(widget_size),
widget_config = VALUES(widget_config),
is_visible = VALUES(is_visible),
updated_at = CURRENT_TIMESTAMP
", [
$userId,
$widgetId,
$config['position_order'] ?? 0,
$config['widget_size'] ?? null,
isset($config['widget_config']) ? json_encode($config['widget_config']) : null,
$config['is_visible'] ?? 1
]);
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
return false;
}
}
/**
* Render a widget
*
* @param array $widget Widget configuration
* @return string Rendered widget HTML
*/
public function renderWidget(array $widget): string
{
try {
$className = $widget['widget_class'];
$method = $widget['widget_method'] ?? 'render';
if (!class_exists($className)) {
throw new \Exception("Widget class not found: {$className}");
}
$config = [];
if (!empty($widget['user_config'])) {
$config = json_decode($widget['user_config'], true) ?? [];
} elseif (!empty($widget['default_config'])) {
$config = json_decode($widget['default_config'], true) ?? [];
}
// Call the widget render method
if (method_exists($className, $method)) {
return call_user_func([$className, $method], $config);
} else {
return $this->renderErrorWidget("Method {$method} not found in {$className}");
}
} catch (\Exception $e) {
ErrorReporter::report($e);
return $this->renderErrorWidget("Failed to render widget: " . $e->getMessage());
}
}
/**
* Render error widget
*
* @param string $message Error message
* @return string Error widget HTML
*/
private function renderErrorWidget(string $message): string
{
return '<div class="alert alert-danger">
<i class="ri-error-warning-line"></i> Widget Error: ' . htmlspecialchars($message) . '
</div>';
}
/**
* Initialize default widgets for new user
*
* @param int $userId User ID
* @return bool Success status
*/
public function initializeDefaultWidgets(int $userId): bool
{
try {
// Get some default widgets to enable for new users
$defaultWidgets = $this->getDb()->fetchAll("
SELECT widget_id
FROM dashboard_widgets
WHERE is_active = 1
AND widget_category IN ('analytics', 'crm', 'general')
ORDER BY widget_name
LIMIT 6
");
$position = 0;
foreach ($defaultWidgets as $widget) {
$this->updateUserWidget($userId, $widget['widget_id'], [
'position_order' => $position++,
'is_visible' => 1
]);
}
return true;
} catch (\Exception $e) {
ErrorReporter::report($e);
return false;
}
}
}