+++ /dev/null
-// =========================================================
-// SCRIPT DE TEST - Module Alerts RÉUTILISABLE
-// =========================================================
-// Ce script teste ton module d'alertes avec la nouvelle
-// architecture réutilisable (injection de dépendances)
-// =========================================================
-// USAGE : node test-alerts.js
-// =========================================================
-
-import dotenv from 'dotenv';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-// Charger les variables d'environnement
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-dotenv.config({ path: path.resolve(__dirname, '.env') });
-
-// =========================================================
-// INITIALISATION DU MODULE (nouvelle architecture !)
-// =========================================================
-import db from './config/db.js';
-import { createMySQLAdapter } from './modules/alerts/adapters/mysql.adapter.js';
-import { createAlertsRepo } from './modules/alerts/alerts.repo.js';
-import { createAlertsService } from './modules/alerts/alerts.service.js';
-
-// 1. Créer l'adapter MySQL avec la connexion DB
-const mysqlAdapter = createMySQLAdapter(db);
-
-// 2. Créer le repository avec l'adapter (plus de SQL dans le repo !)
-const alertsRepo = createAlertsRepo(mysqlAdapter);
-
-// 3. Créer le service avec le repository
-const alertsService = createAlertsService(alertsRepo);
-
-// =========================================================
-// FONCTION DE TEST PRINCIPALE
-// =========================================================
-async function runTest() {
- console.log('\n' + '═'.repeat(80));
- console.log('🧪 TEST DU MODULE ALERTS');
- console.log('═'.repeat(80) + '\n');
-
- try {
- // ─────────────────────────────────────────────────
- // ÉTAPE 1 : Vérifier la connexion DB
- // ─────────────────────────────────────────────────
- console.log('📊 ÉTAPE 1 : Test de connexion à la base de données\n');
-
- // Utilise le repository créé avec injection de dépendances
- const rules = await alertsRepo.findActiveRulesForSignal('test', 1);
- console.log(`✅ Connexion DB OK`);
- console.log(` Règles trouvées : ${rules.length}\n`);
-
- if (rules.length === 0) {
- console.log('⚠️ ATTENTION : Aucune règle trouvée en DB');
- console.log(' Pour tester complètement:');
- console.log(' 1. Créer un utilisateur dans la table users');
- console.log(' 2. Créer une règle dans la table alert_rules\n');
- console.log(' Exemple de SQL :');
- console.log(`
- INSERT INTO users (user_id, email, password_hash, display_name,
- notify_on_hold, min_confidence_notify,
- created_at_ms, updated_at_ms)
- VALUES ('test-user', 'test@example.com', 'hash', 'Test User',
- 0, 0.75,
- UNIX_TIMESTAMP()*1000, UNIX_TIMESTAMP()*1000);
-
- INSERT INTO alert_rules (rule_id, user_id, pair_id, enabled,
- rule_type, severity, min_confidence,
- channel, params, cooldown_ms,
- created_at_ms, updated_at_ms)
- VALUES ('test-rule', 'test-user', 1, 1,
- 'SIGNAL_THRESHOLD', 'WARNING', 0.70,
- 'CONSOLE', '{}', 60000,
- UNIX_TIMESTAMP()*1000, UNIX_TIMESTAMP()*1000);
- `);
-
- console.log('\n tester les canaux !\n');
- }
-
- // ─────────────────────────────────────────────────
- // ÉTAPE 2 : Test du canal CONSOLE
- // ─────────────────────────────────────────────────
- console.log('─'.repeat(80));
- console.log('📺 ÉTAPE 2 : Test du canal CONSOLE\n');
-
- const { sendConsoleAlert } = await import('./modules/alerts/channels/console.js');
-
- const testSignalConsole = {
- action: 'BUY',
- pair: 'BTC/EUR',
- confidence: 0.87,
- criticality: 'WARNING',
- reason: 'Test du canal console : Les indicateurs techniques montrent une tendance haussière. Le RSI est à 45, le MACD vient de croiser.'
- };
-
- await sendConsoleAlert(testSignalConsole);
- console.log('✅ Test CONSOLE réussi\n');
-
- // ─────────────────────────────────────────────────
- // ÉTAPE 3 : Test du canal EMAIL (si configuré)
- // ─────────────────────────────────────────────────
- console.log('─'.repeat(80));
- console.log('📧 ÉTAPE 3 : Test du canal EMAIL\n');
-
- if (!process.env.MAIL_USER || !process.env.MAIL_PASS) {
- console.log('⚠️ Email non configuré (MAIL_USER et MAIL_PASS manquants dans .env)');
- console.log(' Pour tester l\'email, configure tes variables dans .env\n');
- } else {
- console.log('📬 Configuration email détectée');
- console.log(` Host : ${process.env.MAIL_HOST}`);
- console.log(` User : ${process.env.MAIL_USER}`);
- console.log(' Envoi d\'un email de test...\n');
-
- const { sendAlertEmail } = await import('./modules/alerts/channels/mailer.js');
-
- const testSignalEmail = {
- action: 'SELL',
- pair: 'ETH/EUR',
- confidence: 0.92,
- criticality: 'CRITICAL',
- reason: 'Test du canal email : Signal de vente critique détecté. Forte baisse imminente selon les indicateurs.'
- };
-
- const status = await sendAlertEmail(process.env.MAIL_TO || 'wallette@outlook.be', testSignalEmail);
-
- if (status === 'SENT') {
- console.log('✅ Test EMAIL réussi ! Vérifiez la boîte mail.\n');
- } else {
- console.log('❌ Test EMAIL échoué. Vérifiez la configuration.\n');
- }
- }
-
- // ─────────────────────────────────────────────────
- // ÉTAPE 4 : Test du service complet (si règles en DB)
- // ─────────────────────────────────────────────────
- if (rules.length > 0) {
- console.log('─'.repeat(80));
- console.log('🔄 ÉTAPE 4 : Test du service complet\n');
-
- const testSignalService = {
- userId: rules[0].user_id,
- pairId: rules[0].pair_id || 1,
- pair: 'BTC/EUR',
- action: 'BUY',
- confidence: 0.85,
- criticality: 'INFO',
- reason: 'Test complet du service : Signal généré automatiquement pour tester le workflow complet.',
- priceAtSignal: 45000.50
- };
-
- // Utilise le service créé avec injection de dépendances
- await alertsService.processSignal(testSignalService);
- console.log('✅ Test SERVICE complet réussi !\n');
- }
-
- // ─────────────────────────────────────────────────
- // RÉSUMÉ FINAL
- // ─────────────────────────────────────────────────
- console.log('═'.repeat(80));
- console.log('✅ TOUS LES TESTS SONT TERMINÉS');
- console.log('═'.repeat(80));
- console.log('\n📋 RÉSUMÉ :');
- console.log(' ✅ Connexion DB');
- console.log(' ✅ Canal CONSOLE');
- console.log(` ${process.env.MAIL_USER ? '✅' : '⚠️ '} Canal EMAIL ${process.env.MAIL_USER ? '' : '(non configuré)'}`);
- console.log(` ${rules.length > 0 ? '✅' : '⚠️ '} Service complet ${rules.length > 0 ? '' : '(pas de règles en DB)'}`);
- } catch (error) {
- console.error('\n❌ ERREUR LORS DU TEST :');
- console.error(error);
- console.error('\n💡 VÉRIFICATIONS :');
- console.error(' - Le fichier .env existe et contient les bonnes valeurs ?');
- console.error(' - La base de données est démarrée ?');
- console.error(' - Les tables sont créées (schema.sql) ?');
- console.error('\n');
- } finally {
- // Quitter proprement
- process.exit();
- }
-}
-// =========================================================
-// LANCEMENT DU TEST
-// =========================================================
-runTest();
+++ /dev/null
-// =========================================================
-// TEST COMPLET DU MODULE ALERTS
-// =========================================================
-// Ce script teste :
-// 1. Connexion à la base de données
-// 2. CRUD des règles (Create, Read, Update, Delete)
-// 3. Canaux de notification
-// 4. Service processSignal
-// =========================================================
-// USAGE : node test-module-complet.js
-// =========================================================
-
-import dotenv from 'dotenv';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-// Charger les variables d'environnement
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-dotenv.config({ path: path.resolve(__dirname, '.env') });
-
-// =========================================================
-// IMPORTS DU MODULE
-// =========================================================
-import db from './config/db.js';
-import { createMySQLAdapter } from './modules/alerts/adapters/mysql.adapter.js';
-import { createAlertsRepo } from './modules/alerts/alerts.repo.js';
-import { createAlertsService } from './modules/alerts/alerts.service.js';
-
-// =========================================================
-// INITIALISATION
-// =========================================================
-const adapter = createMySQLAdapter(db);
-const repo = createAlertsRepo(adapter);
-const service = createAlertsService(repo);
-
-// Variable pour stocker l'ID de la règle créée
-let testRuleId = null;
-let testUserId = null;
-
-// =========================================================
-// FONCTIONS UTILITAIRES
-// =========================================================
-function printHeader(title) {
- console.log('\n' + '─'.repeat(60));
- console.log(`📋 ${title}`);
- console.log('─'.repeat(60));
-}
-
-function printSuccess(message) {
- console.log(` ✅ ${message}`);
-}
-
-function printError(message) {
- console.log(` ❌ ${message}`);
-}
-
-function printInfo(message) {
- console.log(` ℹ️ ${message}`);
-}
-
-// =========================================================
-// TEST 1 : CONNEXION DB
-// =========================================================
-async function testConnection() {
- printHeader('TEST 1 : Connexion à la base de données');
-
- try {
- const [rows] = await db.execute('SELECT 1 as test');
- if (rows[0].test === 1) {
- printSuccess('Connexion DB OK');
- return true;
- }
- } catch (error) {
- printError(`Connexion échouée : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 1.5 : PRÉPARER UN UTILISATEUR DE TEST
-// =========================================================
-async function prepareTestUser() {
- printHeader('TEST 1.5 : Préparation utilisateur de test');
-
- try {
- // D'abord, chercher un utilisateur existant
- const [existingUsers] = await db.execute('SELECT user_id FROM users LIMIT 1');
-
- if (existingUsers.length > 0) {
- testUserId = existingUsers[0].user_id;
- printSuccess(`Utilisateur existant trouvé : ${testUserId}`);
- return true;
- }
-
- // Sinon, créer un utilisateur de test
- printInfo('Aucun utilisateur trouvé, création d\'un utilisateur de test...');
-
- const { v4: uuidv4 } = await import('uuid');
- testUserId = 'test-user-' + uuidv4().substring(0, 8);
-
- await db.execute(`
- INSERT INTO users (user_id, email, password_hash, display_name, created_at_ms, updated_at_ms)
- VALUES (?, ?, ?, ?, ?, ?)
- `, [testUserId, 'test@test.com', 'hash123', 'Test User', Date.now(), Date.now()]);
-
- printSuccess(`Utilisateur de test créé : ${testUserId}`);
- return true;
-
- } catch (error) {
- printError(`Erreur préparation utilisateur : ${error.message}`);
- printInfo('Conseil : Exécute le seed.sql pour créer des données de test');
- return false;
- }
-}
-
-// =========================================================
-// TEST 2 : CREATE - Créer une règle
-// =========================================================
-async function testCreateRule() {
- printHeader('TEST 2 : CRUD - Créer une règle (CREATE)');
-
- if (!testUserId) {
- printError('Pas d\'utilisateur de test disponible');
- return false;
- }
-
- try {
- const ruleData = {
- userId: testUserId, // Utiliser l'utilisateur existant/créé
- pairId: 1,
- channel: 'CONSOLE',
- minConfidence: 0.75,
- severity: 'WARNING',
- ruleType: 'SIGNAL_THRESHOLD',
- cooldownMs: 60000
- };
-
- printInfo(`Création d'une règle pour user: ${ruleData.userId}`);
-
- const result = await repo.createRule(ruleData);
-
- if (result && result.ruleId) {
- testRuleId = result.ruleId;
- printSuccess(`Règle créée avec ID: ${testRuleId}`);
- return true;
- } else {
- printError('Règle créée mais pas d\'ID retourné');
- return false;
- }
- } catch (error) {
- printError(`Erreur création : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 3 : READ - Lire la règle créée
-// =========================================================
-async function testReadRule() {
- printHeader('TEST 3 : CRUD - Lire la règle (READ)');
-
- if (!testRuleId) {
- printError('Pas de règle à lire (test CREATE a échoué)');
- return false;
- }
-
- try {
- printInfo(`Lecture de la règle ID: ${testRuleId}`);
-
- const rule = await repo.findRuleById(testRuleId);
-
- if (rule) {
- printSuccess(`Règle trouvée :`);
- console.log(` - user_id: ${rule.user_id}`);
- console.log(` - channel: ${rule.channel}`);
- console.log(` - min_confidence: ${rule.min_confidence}`);
- console.log(` - enabled: ${rule.enabled}`);
- return true;
- } else {
- printError('Règle non trouvée');
- return false;
- }
- } catch (error) {
- printError(`Erreur lecture : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 4 : UPDATE - Modifier la règle
-// =========================================================
-async function testUpdateRule() {
- printHeader('TEST 4 : CRUD - Modifier la règle (UPDATE)');
-
- if (!testRuleId) {
- printError('Pas de règle à modifier (test CREATE a échoué)');
- return false;
- }
-
- try {
- const updates = {
- minConfidence: 0.90,
- channel: 'EMAIL',
- severity: 'CRITICAL'
- };
-
- printInfo(`Modification de la règle ID: ${testRuleId}`);
- printInfo(`Nouvelles valeurs: confidence=0.90, channel=EMAIL, severity=CRITICAL`);
-
- const updated = await repo.updateRule(testRuleId, updates);
-
- if (updated) {
- // Vérifier la modification
- const rule = await repo.findRuleById(testRuleId);
-
- // Debug : afficher les valeurs réelles
- console.log(` [DEBUG] min_confidence: ${rule.min_confidence} (type: ${typeof rule.min_confidence})`);
- console.log(` [DEBUG] channel: ${rule.channel}`);
- console.log(` [DEBUG] severity: ${rule.severity}`);
-
- // Comparaison tolérante (float peut avoir des imprécisions)
- const confidenceOk = Math.abs(parseFloat(rule.min_confidence) - 0.90) < 0.01;
- const channelOk = rule.channel === 'EMAIL';
-
- if (confidenceOk && channelOk) {
- printSuccess('Règle modifiée et vérifiée');
- return true;
- } else {
- printError(`Modification non appliquée correctement`);
- printError(` → confidence OK: ${confidenceOk}, channel OK: ${channelOk}`);
- return false;
- }
- } else {
- printError('Modification a retourné false');
- return false;
- }
- } catch (error) {
- printError(`Erreur modification : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 5 : DELETE - Supprimer la règle
-// =========================================================
-async function testDeleteRule() {
- printHeader('TEST 5 : CRUD - Supprimer la règle (DELETE)');
-
- if (!testRuleId) {
- printError('Pas de règle à supprimer (test CREATE a échoué)');
- return false;
- }
-
- try {
- printInfo(`Suppression de la règle ID: ${testRuleId}`);
-
- const deleted = await repo.deleteRule(testRuleId);
-
- if (deleted) {
- // Vérifier la suppression
- const rule = await repo.findRuleById(testRuleId);
-
- if (!rule) {
- printSuccess('Règle supprimée et vérifiée');
- return true;
- } else {
- printError('Règle encore présente après suppression');
- return false;
- }
- } else {
- printError('Suppression a retourné false');
- return false;
- }
- } catch (error) {
- printError(`Erreur suppression : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 6 : Canal CONSOLE
-// =========================================================
-async function testConsoleChannel() {
- printHeader('TEST 6 : Canal de notification CONSOLE');
-
- try {
- const { sendConsoleAlert } = await import('./modules/alerts/channels/console.js');
-
- const testSignal = {
- action: 'BUY',
- pair: 'BTC/EUR',
- confidence: 0.85,
- criticality: 'WARNING',
- reason: 'Test du canal console'
- };
-
- await sendConsoleAlert(testSignal);
- printSuccess('Canal CONSOLE fonctionne');
- return true;
- } catch (error) {
- printError(`Erreur canal CONSOLE : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// TEST 7 : Service processSignal (si règles existent)
-// =========================================================
-async function testProcessSignal() {
- printHeader('TEST 7 : Service processSignal');
-
- if (!testUserId) {
- printError('Pas d\'utilisateur de test disponible');
- return false;
- }
-
- try {
- // D'abord créer une règle pour le test
- const ruleData = {
- userId: testUserId, // Utiliser l'utilisateur existant
- pairId: 1,
- channel: 'CONSOLE',
- minConfidence: 0.70,
- severity: 'INFO'
- };
-
- printInfo('Création d\'une règle temporaire pour le test...');
- const rule = await repo.createRule(ruleData);
-
- // Simuler un signal
- const testSignal = {
- userId: testUserId, // Utiliser l'utilisateur existant
- pairId: 1,
- pair: 'BTC/EUR',
- action: 'BUY',
- confidence: 0.85,
- criticality: 'WARNING',
- reason: 'Test du service processSignal'
- };
-
- printInfo('Envoi du signal au service...');
- await service.processSignal(testSignal);
-
- printSuccess('Service processSignal exécuté sans erreur');
-
- // Nettoyer : supprimer la règle de test
- await repo.deleteRule(rule.ruleId);
- printInfo('Règle temporaire supprimée');
-
- return true;
- } catch (error) {
- printError(`Erreur processSignal : ${error.message}`);
- return false;
- }
-}
-
-// =========================================================
-// EXÉCUTION DE TOUS LES TESTS
-// =========================================================
-async function runAllTests() {
- console.log('\n' + '═'.repeat(60));
- console.log('🧪 TESTS COMPLETS DU MODULE ALERTS');
- console.log('═'.repeat(60));
-
- const results = {
- connection: false,
- prepareUser: false,
- create: false,
- read: false,
- update: false,
- delete: false,
- console: false,
- processSignal: false
- };
-
- try {
- // Tests dans l'ordre
- results.connection = await testConnection();
-
- if (results.connection) {
- results.prepareUser = await prepareTestUser();
-
- if (results.prepareUser) {
- results.create = await testCreateRule();
- results.read = await testReadRule();
- results.update = await testUpdateRule();
- results.delete = await testDeleteRule();
- results.processSignal = await testProcessSignal();
- }
-
- results.console = await testConsoleChannel();
- }
-
- } catch (error) {
- console.error('\n❌ ERREUR FATALE:', error);
- }
-
- // =========================================================
- // RÉSUMÉ
- // =========================================================
- console.log('\n' + '═'.repeat(60));
- console.log('📊 RÉSUMÉ DES TESTS');
- console.log('═'.repeat(60));
-
- const tests = [
- { name: 'Connexion DB', result: results.connection },
- { name: 'Préparation User', result: results.prepareUser },
- { name: 'CRUD - Create', result: results.create },
- { name: 'CRUD - Read', result: results.read },
- { name: 'CRUD - Update', result: results.update },
- { name: 'CRUD - Delete', result: results.delete },
- { name: 'Canal Console', result: results.console },
- { name: 'Service processSignal', result: results.processSignal }
- ];
-
- let passed = 0;
- let failed = 0;
-
- tests.forEach(test => {
- const icon = test.result ? '✅' : '❌';
- console.log(` ${icon} ${test.name}`);
- if (test.result) passed++;
- else failed++;
- });
-
- console.log('\n' + '─'.repeat(60));
- console.log(` Total: ${passed}/${tests.length} tests réussis`);
-
- if (failed === 0) {
- console.log('\n 🎉 TOUS LES TESTS SONT PASSÉS !');
- } else {
- console.log(`\n ⚠️ ${failed} test(s) échoué(s)`);
- }
-
- console.log('═'.repeat(60) + '\n');
-
- // Quitter
- process.exit(failed === 0 ? 0 : 1);
-}
-
-// =========================================================
-// LANCEMENT
-// =========================================================
-runAllTests();
+++ /dev/null
-// =========================================================
-// SERVEUR DE TEST AVEC SOCKET.IO
-// =========================================================
-// Lance ce serveur pour tester les alertes temps réel
-// avec Thibault (mobile) ou Océane (web)
-// =========================================================
-// USAGE : node test-server-socket.js
-// =========================================================
-
-import express from 'express';
-import { createServer } from 'http';
-import dotenv from 'dotenv';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-// Charger les variables d'environnement
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-dotenv.config({ path: path.resolve(__dirname, '.env') });
-
-// =========================================================
-// IMPORTS DU MODULE ALERTS
-// =========================================================
-import db from './config/db.js';
-import { createMySQLAdapter } from './modules/alerts/adapters/mysql.adapter.js';
-import { createAlertsRepo } from './modules/alerts/alerts.repo.js';
-import { createAlertsService } from './modules/alerts/alerts.service.js';
-import { createAlertsController } from './modules/alerts/alerts.controller.js';
-import { createAlertsRouter } from './modules/alerts/alerts.router.js';
-import { initSocketIO, sendAlertToUser, broadcastAlert, getConnectedUsersCount } from './modules/alerts/socketManager.js';
-
-// =========================================================
-// CRÉER L'APPLICATION EXPRESS
-// =========================================================
-const app = express();
-app.use(express.json());
-
-// =========================================================
-// CRÉER LE SERVEUR HTTP (nécessaire pour Socket.IO)
-// =========================================================
-const httpServer = createServer(app);
-
-// =========================================================
-// INITIALISER SOCKET.IO
-// =========================================================
-const io = initSocketIO(httpServer, {
- cors: {
- origin: "*", // Accepter toutes les origines pour le test
- methods: ["GET", "POST"]
- }
-});
-
-// =========================================================
-// INITIALISER LE MODULE ALERTS
-// =========================================================
-const adapter = createMySQLAdapter(db);
-const repo = createAlertsRepo(adapter);
-const service = createAlertsService(repo);
-const controller = createAlertsController(service, repo);
-const router = createAlertsRouter(controller);
-
-// =========================================================
-// MONTER LES ROUTES
-// =========================================================
-app.use('/api/alerts', router);
-
-// =========================================================
-// ROUTE DE TEST / HEALTH CHECK
-// =========================================================
-app.get('/', (req, res) => {
- res.json({
- status: 'ok',
- message: 'Serveur Wall-e-tte avec Socket.IO',
- socketConnections: getConnectedUsersCount(),
- timestamp: new Date().toISOString()
- });
-});
-
-// =========================================================
-// ROUTE POUR SIMULER UNE ALERTE (test)
-// =========================================================
-app.post('/test/send-alert', (req, res) => {
- const { userId, broadcast } = req.body;
-
- const testAlert = {
- action: 'BUY',
- pair: 'BTC/EUR',
- confidence: 0.87,
- reason: 'Test manuel depuis le serveur',
- alertLevel: 'WARNING',
- price: 42150.23
- };
-
- if (broadcast) {
- // Envoyer à tous
- const count = broadcastAlert(testAlert);
- res.json({
- success: true,
- message: `Alerte envoyée à ${count} utilisateur(s)`
- });
- } else if (userId) {
- // Envoyer à un utilisateur spécifique
- const sent = sendAlertToUser(userId, testAlert);
- res.json({
- success: sent,
- message: sent ? 'Alerte envoyée' : 'Utilisateur non connecté'
- });
- } else {
- res.status(400).json({
- error: 'userId ou broadcast requis'
- });
- }
-});
-
-// =========================================================
-// ROUTE POUR VOIR LES CONNEXIONS ACTIVES
-// =========================================================
-app.get('/test/connections', (req, res) => {
- const { getConnectedUserIds } = require('./modules/alerts/socketManager.js');
- res.json({
- count: getConnectedUsersCount(),
- users: getConnectedUserIds ? getConnectedUserIds() : 'N/A'
- });
-});
-
-// =========================================================
-// DÉMARRER LE SERVEUR
-// =========================================================
-const PORT = process.env.PORT || 3000;
-
-httpServer.listen(PORT, () => {
- console.log(`
- ╔═══════════════════════════════════════════════════════════╗
- ║ SERVEUR WALL-E-TTE AVEC SOCKET.IO ║
- ╠═══════════════════════════════════════════════════════════╣
- ║ ║
- ║ HTTP Server : http://localhost:${PORT} ║
- ║ Socket.IO : ws://localhost:${PORT} ║
- ║ ║
- ╠═══════════════════════════════════════════════════════════╣
- ║ ROUTES API : ║
- ║ ─────────────────────────────────────────────────────── ║
- ║ GET / → Health check ║
- ║ GET /test/connections → Voir qui est connecté ║
- ║ POST /test/send-alert → Simuler une alerte ║
- ║ POST /api/alerts/rules → Créer une règle ║
- ║ GET /api/alerts/rules/:id → Lister les règles ║
- ║ ║
- ╠═══════════════════════════════════════════════════════════╣
- ║ SOCKET.IO EVENTS : ║
- ║ ─────────────────────────────────────────────────────── ║
- ║ Client → Serveur : ║
- ║ • 'auth' (userId) → S'authentifier ║
- ║ • 'ping_alerts' → Tester la connexion ║
- ║ ║
- ║ Serveur → Client : ║
- ║ • 'auth_success' → Authentification OK ║
- ║ • 'alert' → Réception d'une alerte ║
- ║ • 'pong_alerts' → Réponse au ping ║
- ║ ║
- ╚═══════════════════════════════════════════════════════════╝
-
-
- Pour tester manuellement :
- curl -X POST http://localhost:${PORT}/test/send-alert -H "Content-Type: application/json" -d '{"broadcast": true}'
-
- Ctrl+C pour arrêter.
-`);
-});
+++ /dev/null
-// =========================================================
-// MINI-SERVEUR DE TEST POUR LES ROUTES API
-// =========================================================
-// Ce script démarre un serveur Express pour tester les
-// routes du module Alerts via Postman, curl ou navigateur
-// =========================================================
-// USAGE : node test-server.js
-// =========================================================
-
-import express from 'express';
-import dotenv from 'dotenv';
-import path from 'path';
-import { fileURLToPath } from 'url';
-
-// Charger les variables d'environnement
-const __filename = fileURLToPath(import.meta.url);
-const __dirname = path.dirname(__filename);
-dotenv.config({ path: path.resolve(__dirname, '.env') });
-
-// =========================================================
-// IMPORTS DU MODULE ALERTS
-// =========================================================
-import { initializeAlertsModule } from './modules/init-alerts.js';
-
-// =========================================================
-// CRÉER L'APPLICATION EXPRESS
-// =========================================================
-const app = express();
-app.use(express.json());
-
-// =========================================================
-// INITIALISER LE MODULE ALERTS
-// =========================================================
-console.log('\n🚀 Initialisation du module Alerts...\n');
-
-// Import dynamique pour éviter l'erreur de connexion DB
-import db from './config/db.js';
-import { createMySQLAdapter } from './modules/alerts/adapters/mysql.adapter.js';
-import { createAlertsRepo } from './modules/alerts/alerts.repo.js';
-import { createAlertsService } from './modules/alerts/alerts.service.js';
-import { createAlertsController } from './modules/alerts/alerts.controller.js';
-import { createAlertsRouter } from './modules/alerts/alerts.router.js';
-
-const adapter = createMySQLAdapter(db);
-const repo = createAlertsRepo(adapter);
-const service = createAlertsService(repo);
-const controller = createAlertsController(service, repo);
-const router = createAlertsRouter(controller);
-
-// =========================================================
-// MONTER LES ROUTES
-// =========================================================
-app.use('/api/alerts', router);
-
-// =========================================================
-// ROUTE DE TEST / HEALTH CHECK
-// =========================================================
-app.get('/', (req, res) => {
- res.json({
- status: 'ok',
- message: 'Serveur de test Alerts',
- timestamp: new Date().toISOString(),
- routes: [
- 'GET /api/alerts/rules/:userId - Lister les règles',
- 'GET /api/alerts/rules/detail/:id - Détail d\'une règle',
- 'POST /api/alerts/rules - Créer une règle',
- 'PUT /api/alerts/rules/:id - Modifier une règle',
- 'DELETE /api/alerts/rules/:id - Supprimer une règle',
- 'GET /api/alerts/history/:userId - Historique des alertes',
- 'POST /api/alerts/process-signal - Traiter un signal'
- ]
- });
-});
-
-// =========================================================
-// DÉMARRER LE SERVEUR
-// =========================================================
-const PORT = process.env.PORT || 3000;
-
-app.listen(PORT, () => {
- console.log(`
-╔═══════════════════════════════════════════════════════════╗
-║ 🧪 SERVEUR DE TEST - MODULE ALERTS ║
-╠═══════════════════════════════════════════════════════════╣
-║ ║
-║ Serveur démarré sur : http://localhost:${PORT} ║
-║ ║
-║ Routes disponibles : ║
-║ ─────────────────────────────────────────────────────── ║
-║ GET / → Health check ║
-║ GET /api/alerts/rules/:userId → Lister règles ║
-║ GET /api/alerts/rules/detail/:id → Détail règle ║
-║ POST /api/alerts/rules → Créer règle ║
-║ PUT /api/alerts/rules/:id → Modifier règle ║
-║ DELETE /api/alerts/rules/:id → Supprimer règle ║
-║ GET /api/alerts/history/:userId → Historique ║
-║ POST /api/alerts/process-signal → Traiter signal ║
-║ ║
-╚═══════════════════════════════════════════════════════════╝
-
-📝 Exemples de tests avec curl :
-
-1. Créer une règle :
- curl -X POST http://localhost:${PORT}/api/alerts/rules \\
- -H "Content-Type: application/json" \\
- -d '{"userId":"test-user","pairId":1,"channel":"CONSOLE","minConfidence":0.8}'
-
-2. Lister les règles :
- curl http://localhost:${PORT}/api/alerts/rules/test-user
-
-3. Modifier une règle :
- curl -X PUT http://localhost:${PORT}/api/alerts/rules/RULE_ID \\
- -H "Content-Type: application/json" \\
- -d '{"minConfidence":0.9,"enabled":true}'
-
-4. Supprimer une règle :
- curl -X DELETE http://localhost:${PORT}/api/alerts/rules/RULE_ID
-
-Appuie sur Ctrl+C pour arrêter le serveur.
-`);
-});