|
|
| let allEvaluations = [];
|
| let scenariosData = [];
|
| let filteredEvaluations = [];
|
| let reviewsData = [];
|
| let currentReviewEvalId = null;
|
| let chart1 = null;
|
| let chart2 = null;
|
|
|
|
|
| document.addEventListener('DOMContentLoaded', function() {
|
| console.log('Initialisation de l\'analyse croisée...');
|
| loadData();
|
| });
|
|
|
|
|
| function loadData() {
|
| console.log('Début du chargement des données...');
|
|
|
|
|
| showLoadingMessage('Chargement des données...');
|
|
|
|
|
| document.getElementById('helpSection').style.display = 'none';
|
|
|
|
|
| fetch('/api/evaluations')
|
| .then(response => {
|
| if (!response.ok) {
|
| console.warn('API /api/evaluations non disponible, utilisation des données locales');
|
|
|
| return fetch('trust_stats.json').then(r => r.json());
|
| }
|
| return response.json();
|
| })
|
| .then(data => {
|
| allEvaluations = data.evaluations || [];
|
| console.log(`${allEvaluations.length} évaluations chargées`);
|
|
|
| if (allEvaluations.length === 0) {
|
| console.warn('Aucune évaluation trouvée');
|
| showWarningMessage('Aucune donnée d\'évaluation trouvée. Générer des données de test pour commencer.');
|
| document.getElementById('helpSection').style.display = 'block';
|
| } else {
|
| document.getElementById('warningMessage').style.display = 'none';
|
| }
|
|
|
|
|
| return fetch('/api/scenarios')
|
| .then(r => r.ok ? r.json() : fetch('scenarios.json').then(r2 => r2.json()))
|
| .catch(() => fetch('scenarios.json').then(r => r.json()));
|
| })
|
| .then(data => {
|
| scenariosData = data.scenarios || [];
|
| console.log(`${scenariosData.length} scénarios chargés`);
|
|
|
|
|
| return fetch('/api/reviews')
|
| .then(r => r.ok ? r.json() : fetch('review.json').then(r2 => r2.json()))
|
| .catch(() => fetch('review.json').then(r => r.json()));
|
| })
|
| .then(data => {
|
| reviewsData = data.reviews || [];
|
| console.log(`${reviewsData.length} reviews chargés`);
|
|
|
|
|
| processEvaluations();
|
| showSuccessMessage('Données chargées avec succès !');
|
| })
|
| .catch(error => {
|
| console.error('Erreur de chargement:', error);
|
| showErrorMessage(`Erreur de chargement: ${error.message}<br>
|
| <br>
|
| <strong>Solutions possibles :</strong><br>
|
| 1. Vérifiez que les fichiers JSON existent<br>
|
| 2. Générez des données de test avec le bouton ci-dessous<br>
|
| 3. Vérifiez la console du navigateur (F12) pour plus de détails<br>
|
| <br>
|
| <button onclick="generateTestData()" style="margin-top:10px;padding:10px 20px;background:#4CAF50;color:white;border:none;border-radius:5px;cursor:pointer;font-weight:bold;">
|
| 🧪 Générer des données de test
|
| </button>
|
| <button onclick="location.reload()" style="margin-top:10px;margin-left:10px;padding:10px 20px;background:#2196F3;color:white;border:none;border-radius:5px;cursor:pointer;">
|
| 🔄 Réessayer
|
| </button>`);
|
|
|
|
|
| document.getElementById('helpSection').style.display = 'block';
|
| });
|
| }
|
|
|
|
|
| function generateTestData() {
|
| console.log('Génération de données de test...');
|
|
|
| showLoadingMessage('Génération des données de test...');
|
|
|
|
|
| fetch('/api/generate_test_data')
|
| .then(response => {
|
| if (!response.ok) {
|
|
|
| return generateLocalTestData();
|
| }
|
| return response.json();
|
| })
|
| .then(data => {
|
| console.log('Données de test générées:', data);
|
| showSuccessMessage(`✅ Données de test générées avec succès !<br>
|
| - ${data.evaluations || 5} évaluations<br>
|
| - ${data.scenarios || scenariosData.length} scénarios<br>
|
| - ${data.reviews || 3} reviews`);
|
|
|
|
|
| setTimeout(() => {
|
| location.reload();
|
| }, 2000);
|
| })
|
| .catch(error => {
|
| console.error('Erreur génération données test:', error);
|
| generateLocalTestData();
|
| });
|
| }
|
|
|
| function generateLocalTestData() {
|
|
|
| const testEvaluations = [];
|
| const evaluators = ['Expert A', 'Expert B', 'Expert C', 'Anonyme'];
|
| const roles = ['Professeur', 'Psychologue', 'Tuteur', 'Chercheur'];
|
|
|
| for (let i = 0; i < 10; i++) {
|
| const scenarioId = Math.floor(Math.random() * 16) + 1;
|
| const evaluatorIndex = Math.floor(Math.random() * evaluators.length);
|
|
|
| const metrics = {
|
| AR: Math.floor(Math.random() * 6),
|
| AE: Math.floor(Math.random() * 6),
|
| ESR: Math.floor(Math.random() * 6),
|
| SDM: Math.floor(Math.random() * 6),
|
| SM: Math.floor(Math.random() * 6)
|
| };
|
|
|
| const totalScore = (metrics.AR + metrics.AE + metrics.ESR + metrics.SDM + metrics.SM) * 4;
|
|
|
| testEvaluations.push({
|
| id: `test_eval_${Date.now()}_${i}`,
|
| scenario_id: scenarioId,
|
| evaluator_name: evaluators[evaluatorIndex],
|
| evaluator_role: roles[evaluatorIndex],
|
| trust_metrics: metrics,
|
| trust_score: totalScore,
|
| comment: 'Évaluation générée automatiquement pour test',
|
| timestamp: new Date(Date.now() - Math.random() * 10000000000).toISOString(),
|
| cross_reading: Math.random() > 0.7
|
| });
|
| }
|
|
|
|
|
| const testReviews = [];
|
| for (let i = 0; i < 5; i++) {
|
| if (testEvaluations[i]) {
|
| const decisions = ['approved', 'needs_revision', 'rejected'];
|
| const decision = decisions[Math.floor(Math.random() * decisions.length)];
|
|
|
| testReviews.push({
|
| id: `test_review_${Date.now()}_${i}`,
|
| evaluation_id: testEvaluations[i].id,
|
| scenario_id: testEvaluations[i].scenario_id,
|
| evaluator_name: testEvaluations[i].evaluator_name,
|
| evaluator_role: testEvaluations[i].evaluator_role,
|
| original_score: testEvaluations[i].trust_score,
|
| original_comment: testEvaluations[i].comment,
|
| decision: decision,
|
| review_comment: `Review automatique - ${decision === 'approved' ? 'Approuvé' : decision === 'needs_revision' ? 'Nécessite révision' : 'Rejeté'}`,
|
| reviewer: 'Système de test',
|
| timestamp: new Date().toISOString()
|
| });
|
| }
|
| }
|
|
|
|
|
| try {
|
|
|
| allEvaluations = [...allEvaluations, ...testEvaluations];
|
|
|
|
|
| reviewsData = [...reviewsData, ...testReviews];
|
|
|
|
|
| processEvaluations();
|
| filterAllEvaluations();
|
|
|
| showSuccessMessage(`✅ Données de test générées localement !<br>
|
| - ${testEvaluations.length} nouvelles évaluations<br>
|
| - ${testReviews.length} nouveaux reviews`);
|
|
|
| return {
|
| evaluations: testEvaluations.length,
|
| reviews: testReviews.length,
|
| scenarios: scenariosData.length
|
| };
|
| } catch (error) {
|
| console.error('Erreur génération locale:', error);
|
| showErrorMessage('Erreur lors de la génération des données de test');
|
| throw error;
|
| }
|
| }
|
|
|
|
|
| function processEvaluations() {
|
| console.log('Traitement des évaluations...');
|
|
|
|
|
| if (allEvaluations.length === 0) {
|
| showWarningMessage('Aucune évaluation à afficher. Utilisez le bouton "Générer des données de test" pour commencer.');
|
| document.getElementById('helpSection').style.display = 'block';
|
| return;
|
| }
|
|
|
|
|
| allEvaluations.forEach((eval, index) => {
|
|
|
| if (!eval.id) {
|
| eval.id = `eval_${Date.now()}_${index}_${Math.random().toString(36).substr(2, 9)}`;
|
| }
|
|
|
|
|
| if (eval.trust_metrics) {
|
| const normalizedMetrics = {};
|
| Object.keys(eval.trust_metrics).forEach(key => {
|
| const normalizedKey = key.trim().toUpperCase();
|
| if (normalizedKey === 'RA' || normalizedKey === 'AR') normalizedMetrics.AR = eval.trust_metrics[key];
|
| else if (normalizedKey === 'EA' || normalizedKey === 'AE') normalizedMetrics.AE = eval.trust_metrics[key];
|
| else if (normalizedKey === 'RE' || normalizedKey === 'ESR') normalizedMetrics.ESR = eval.trust_metrics[key];
|
| else if (normalizedKey === 'MCS' || normalizedKey === 'SDM') normalizedMetrics.SDM = eval.trust_metrics[key];
|
| else if (normalizedKey === 'MS' || normalizedKey === 'SM') normalizedMetrics.SM = eval.trust_metrics[key];
|
| else normalizedMetrics[key] = eval.trust_metrics[key];
|
| });
|
| eval.trust_metrics = normalizedMetrics;
|
| }
|
|
|
|
|
| if (!eval.trust_metrics) {
|
| eval.trust_metrics = {
|
| AR: 0, AE: 0, ESR: 0, SDM: 0, SM: 0
|
| };
|
| }
|
|
|
|
|
| if (eval.trust_score === undefined || eval.trust_score === null) {
|
|
|
| const metrics = eval.trust_metrics;
|
| const sum = (metrics.AR || 0) + (metrics.AE || 0) + (metrics.ESR || 0) + (metrics.SDM || 0) + (metrics.SM || 0);
|
| eval.trust_score = Math.round((sum / 5) * 20);
|
| }
|
|
|
|
|
| if (!eval.evaluator_name) {
|
| eval.evaluator_name = 'Anonyme';
|
| }
|
|
|
|
|
| if (!eval.timestamp) {
|
| eval.timestamp = new Date().toISOString();
|
| }
|
|
|
|
|
| if (!eval.scenario_id && eval.scenario_id !== 0) {
|
| eval.scenario_id = Math.floor(Math.random() * 16) + 1;
|
| }
|
| });
|
|
|
|
|
| updateGlobalStats();
|
|
|
|
|
| populateScenarioFilter();
|
|
|
|
|
| populateEvaluatorFilter();
|
|
|
|
|
| filterData();
|
| filterAllEvaluations();
|
| }
|
|
|
|
|
| function updateGlobalStats() {
|
| const totalEvaluations = allEvaluations.length;
|
|
|
|
|
| const uniqueScenarios = [...new Set(allEvaluations.map(e => e.scenario_id))].filter(id => id !== undefined && id !== null);
|
|
|
|
|
| const uniqueEvaluators = [...new Set(allEvaluations.map(e => e.evaluator_name || 'Anonyme'))];
|
|
|
|
|
| let totalConflict = 0;
|
| let analyzedScenarios = 0;
|
|
|
| uniqueScenarios.forEach(scenarioId => {
|
| const scenarioEvals = allEvaluations.filter(e => e.scenario_id === scenarioId);
|
| if (scenarioEvals.length > 1) {
|
| const avgScore = scenarioEvals.reduce((sum, e) => sum + (e.trust_score || 0), 0) / scenarioEvals.length;
|
| const variance = scenarioEvals.reduce((sum, e) => sum + Math.pow((e.trust_score || 0) - avgScore, 2), 0) / scenarioEvals.length;
|
| const stdDev = Math.sqrt(variance);
|
| totalConflict += stdDev;
|
| analyzedScenarios++;
|
| }
|
| });
|
|
|
| const avgConflict = analyzedScenarios > 0 ? (totalConflict / analyzedScenarios) : 0;
|
| const conflictRate = Math.min(100, Math.round(avgConflict));
|
|
|
|
|
| document.getElementById('totalEvaluations').textContent = totalEvaluations;
|
| document.getElementById('totalScenarios').textContent = uniqueScenarios.length;
|
| document.getElementById('totalEvaluators').textContent = uniqueEvaluators.length;
|
| document.getElementById('conflictRate').textContent = `${conflictRate}%`;
|
| }
|
|
|
|
|
| function populateScenarioFilter() {
|
| const filter = document.getElementById('scenarioFilter');
|
| filter.innerHTML = '<option value="all">Tous les scénarios</option>';
|
|
|
|
|
| const uniqueScenarios = [...new Set(allEvaluations.map(e => e.scenario_id))]
|
| .filter(id => id !== undefined && id !== null)
|
| .sort((a, b) => a - b);
|
|
|
|
|
| uniqueScenarios.forEach(scenarioId => {
|
| const scenario = scenariosData.find(s => s.id === scenarioId);
|
| const option = document.createElement('option');
|
| option.value = scenarioId;
|
| option.textContent = scenario ? `Scénario ${scenarioId} - ${scenario.title}` : `Scénario ${scenarioId}`;
|
| filter.appendChild(option);
|
| });
|
| }
|
|
|
| function populateEvaluatorFilter() {
|
| const filter = document.getElementById('evaluatorFilter');
|
| filter.innerHTML = '<option value="all">Tous les évaluateurs</option>';
|
|
|
|
|
| const uniqueEvaluators = [...new Set(allEvaluations.map(e => e.evaluator_name || 'Anonyme'))]
|
| .filter(name => name && name.trim() !== '')
|
| .sort();
|
|
|
|
|
| uniqueEvaluators.forEach(evaluator => {
|
| const option = document.createElement('option');
|
| option.value = evaluator;
|
| option.textContent = evaluator;
|
| filter.appendChild(option);
|
| });
|
| }
|
|
|
| function filterData() {
|
| const scenarioFilter = document.getElementById('scenarioFilter').value;
|
| const confidenceFilter = document.getElementById('confidenceFilter').value;
|
| const sortBy = document.getElementById('sortBy').value;
|
|
|
|
|
| if (scenarioFilter === 'all') {
|
| filteredEvaluations = allEvaluations;
|
| } else {
|
| filteredEvaluations = allEvaluations.filter(e => e.scenario_id === parseInt(scenarioFilter));
|
| }
|
|
|
|
|
| const groupedByScenario = {};
|
| filteredEvaluations.forEach(eval => {
|
| if (eval.scenario_id === undefined) return;
|
| if (!groupedByScenario[eval.scenario_id]) {
|
| groupedByScenario[eval.scenario_id] = [];
|
| }
|
| groupedByScenario[eval.scenario_id].push(eval);
|
| });
|
|
|
|
|
| const scenarioMetrics = Object.keys(groupedByScenario).map(scenarioId => {
|
| const evaluations = groupedByScenario[scenarioId];
|
| const scenario = scenariosData.find(s => s.id === parseInt(scenarioId));
|
|
|
|
|
| const avgScore = evaluations.reduce((sum, e) => sum + (e.trust_score || 0), 0) / evaluations.length;
|
|
|
|
|
| let stdDev = 0;
|
| if (evaluations.length > 1) {
|
| const variance = evaluations.reduce((sum, e) => sum + Math.pow((e.trust_score || 0) - avgScore, 2), 0) / evaluations.length;
|
| stdDev = Math.sqrt(variance);
|
| }
|
|
|
|
|
| let conflictLevel = 'low';
|
| if (stdDev > 40) conflictLevel = 'high';
|
| else if (stdDev > 20) conflictLevel = 'medium';
|
|
|
|
|
| if (confidenceFilter !== 'all' && conflictLevel !== confidenceFilter) {
|
| return null;
|
| }
|
|
|
| return {
|
| scenarioId: parseInt(scenarioId),
|
| scenario: scenario,
|
| evaluations: evaluations,
|
| avgScore: avgScore,
|
| stdDev: stdDev,
|
| conflictLevel: conflictLevel,
|
| minScore: Math.min(...evaluations.map(e => e.trust_score || 0)),
|
| maxScore: Math.max(...evaluations.map(e => e.trust_score || 0)),
|
| dateRange: {
|
| min: new Date(Math.min(...evaluations.map(e => new Date(e.timestamp).getTime()))),
|
| max: new Date(Math.max(...evaluations.map(e => new Date(e.timestamp).getTime())))
|
| }
|
| };
|
| }).filter(metric => metric !== null);
|
|
|
|
|
| scenarioMetrics.sort((a, b) => {
|
| switch(sortBy) {
|
| case 'scenario':
|
| return a.scenarioId - b.scenarioId;
|
| case 'conflict':
|
| return b.stdDev - a.stdDev;
|
| case 'evaluations':
|
| return b.evaluations.length - a.evaluations.length;
|
| case 'confidence':
|
| return b.avgScore - a.avgScore;
|
| default:
|
| return a.scenarioId - b.scenarioId;
|
| }
|
| });
|
|
|
|
|
| displayScenarioTable(scenarioMetrics);
|
| updateCharts(scenarioMetrics);
|
| }
|
|
|
|
|
| function displayScenarioTable(scenarioMetrics) {
|
| const tableContainer = document.getElementById('evaluationsTable');
|
|
|
| if (scenarioMetrics.length === 0) {
|
| tableContainer.innerHTML = `
|
| <div style="text-align: center; padding: 40px; background: #FFF3E0; border-radius: 10px; color: #EF6C00;">
|
| <p style="font-size: 18px;">Aucune évaluation correspondant aux filtres sélectionnés</p>
|
| <p>Essayez de modifier vos critères de recherche</p>
|
| </div>
|
| `;
|
| return;
|
| }
|
|
|
| let html = `
|
| <table>
|
| <thead>
|
| <tr>
|
| <th>Scénario</th>
|
| <th>Évaluations</th>
|
| <th>Confiance moyenne</th>
|
| <th>Niveau de conflit</th>
|
| <th>Plage de scores</th>
|
| <th>Période</th>
|
| <th>Actions</th>
|
| </tr>
|
| </thead>
|
| <tbody>
|
| `;
|
|
|
| scenarioMetrics.forEach(metric => {
|
| const conflictClass = `conflict-${metric.conflictLevel}`;
|
| const conflictText = metric.conflictLevel === 'high' ? 'Élevé' :
|
| metric.conflictLevel === 'medium' ? 'Moyen' : 'Faible';
|
|
|
| html += `
|
| <tr>
|
| <td>
|
| <strong>Scénario ${metric.scenarioId}</strong><br>
|
| <small style="color:#666;">${metric.scenario ? metric.scenario.title : 'Non trouvé'}</small>
|
| </td>
|
| <td>
|
| <div style="font-weight:bold;color:#1976D2;">${metric.evaluations.length}</div>
|
| <small>${metric.evaluations.slice(0, 3).map(e => e.evaluator_name || 'Anonyme').join(', ')}${metric.evaluations.length > 3 ? '...' : ''}</small>
|
| </td>
|
| <td>
|
| <div style="font-weight:bold;font-size:18px;color:#1976D2;">${Math.round(metric.avgScore)}%</div>
|
| <div class="confidence-bar">
|
| <div class="confidence-fill ${getConfidenceClass(metric.avgScore)}"
|
| style="width: ${metric.avgScore}%"></div>
|
| </div>
|
| </td>
|
| <td>
|
| <div><span class="conflict-indicator ${conflictClass}"></span> ${conflictText}</div>
|
| <small>Écart-type: ${metric.stdDev.toFixed(1)}%</small>
|
| </td>
|
| <td>
|
| <div>${Math.round(metric.minScore)}% - ${Math.round(metric.maxScore)}%</div>
|
| <small>Différence: ${Math.round(metric.maxScore - metric.minScore)}%</small>
|
| </td>
|
| <td>
|
| <div>${formatDate(metric.dateRange.min)}</div>
|
| <div>à ${formatDate(metric.dateRange.max)}</div>
|
| </td>
|
| <td>
|
| <button onclick="showScenarioDetails(${metric.scenarioId})"
|
| style="padding:5px 10px;background:#1976D2;color:white;border:none;border-radius:5px;cursor:pointer;">
|
| Détails
|
| </button>
|
| </td>
|
| </tr>
|
| `;
|
| });
|
|
|
| html += `</tbody></table>`;
|
| tableContainer.innerHTML = html;
|
| }
|
|
|
|
|
| function filterAllEvaluations() {
|
| const evaluatorFilter = document.getElementById('evaluatorFilter').value;
|
| const scoreFilter = document.getElementById('scoreFilter').value;
|
| const sortBy = document.getElementById('sortEvaluations').value;
|
|
|
| let filteredEvals = [...allEvaluations];
|
|
|
|
|
| if (evaluatorFilter !== 'all') {
|
| filteredEvals = filteredEvals.filter(e =>
|
| (e.evaluator_name || 'Anonyme') === evaluatorFilter
|
| );
|
| }
|
|
|
|
|
| if (scoreFilter !== 'all') {
|
| filteredEvals = filteredEvals.filter(e => {
|
| const score = e.trust_score || 0;
|
| if (scoreFilter === 'high') return score >= 70;
|
| if (scoreFilter === 'medium') return score >= 40 && score < 70;
|
| if (scoreFilter === 'low') return score < 40;
|
| return true;
|
| });
|
| }
|
|
|
|
|
| filteredEvals.sort((a, b) => {
|
| switch(sortBy) {
|
| case 'date_desc':
|
| return new Date(b.timestamp) - new Date(a.timestamp);
|
| case 'date_asc':
|
| return new Date(a.timestamp) - new Date(b.timestamp);
|
| case 'score_desc':
|
| return (b.trust_score || 0) - (a.trust_score || 0);
|
| case 'score_asc':
|
| return (a.trust_score || 0) - (b.trust_score || 0);
|
| case 'scenario':
|
| return (a.scenario_id || 0) - (b.scenario_id || 0);
|
| default:
|
| return new Date(b.timestamp) - new Date(a.timestamp);
|
| }
|
| });
|
|
|
|
|
| displayAllEvaluations(filteredEvals);
|
| }
|
|
|
| function displayAllEvaluations(evaluations) {
|
| const container = document.getElementById('allEvaluationsTable');
|
|
|
| if (evaluations.length === 0) {
|
| container.innerHTML = `
|
| <div style="text-align: center; padding: 40px; background: #FFF3E0; border-radius: 10px; color: #EF6C00;">
|
| <p style="font-size: 18px;">Aucune évaluation correspondant aux filtres</p>
|
| <p>Essayez de modifier les critères de filtrage</p>
|
| </div>
|
| `;
|
| return;
|
| }
|
|
|
| let html = `
|
| <table>
|
| <thead>
|
| <tr>
|
| <th>Évaluateur</th>
|
| <th>Scénario</th>
|
| <th>Score</th>
|
| <th class="metrics-table-cell">Métriques</th>
|
| <th>Commentaire</th>
|
| <th>Review</th>
|
| <th>Actions</th>
|
| </tr>
|
| </thead>
|
| <tbody>
|
| `;
|
|
|
| evaluations.forEach(eval => {
|
| const scenario = scenariosData.find(s => s.id === eval.scenario_id);
|
| const review = reviewsData.find(r => r.evaluation_id === eval.id);
|
|
|
|
|
| const isCrossReading = eval.cross_reading === true;
|
|
|
| html += `
|
| <tr style="${isCrossReading ? 'background: #E3F2FD;' : ''}">
|
| <td>
|
| <strong>${eval.evaluator_name || 'Anonyme'}</strong><br>
|
| <small>${eval.evaluator_role || ''}</small><br>
|
| <small style="color:#666;">${formatDate(new Date(eval.timestamp))}</small>
|
| </td>
|
| <td>
|
| <strong>Scénario ${eval.scenario_id || 'N/A'}</strong><br>
|
| <small style="color:#666;">${scenario ? scenario.title : 'Non trouvé'}</small>
|
| ${isCrossReading ? '<div class="scenario-badge" style="background:#4CAF50;color:white;margin-top:3px;">Cross-Reading</div>' : ''}
|
| </td>
|
| <td>
|
| <div style="font-weight:bold;font-size:18px;color:#1976D2;">${eval.trust_score || 0}%</div>
|
| <div class="confidence-bar">
|
| <div class="confidence-fill ${getConfidenceClass(eval.trust_score || 0)}"
|
| style="width: ${eval.trust_score || 0}%"></div>
|
| </div>
|
| </td>
|
| <td class="metrics-table-cell">
|
| ${displayDetailedMetrics(eval.trust_metrics || {})}
|
| </td>
|
| <td style="max-width: 200px;">
|
| <small style="color:#666;">${eval.comment || 'Aucun commentaire'}</small>
|
| </td>
|
| <td>
|
| ${displayReviewStatus(review)}
|
| </td>
|
| <td>
|
| <button onclick="openReviewModal('${eval.id}')"
|
| style="padding:5px 10px;background:#4CAF50;color:white;border:none;border-radius:5px;cursor:pointer;font-size:12px;">
|
| ✍️ Review
|
| </button>
|
| </td>
|
| </tr>
|
| `;
|
| });
|
|
|
| html += `</tbody></table>`;
|
| container.innerHTML = html;
|
| }
|
|
|
| function displayDetailedMetrics(metrics) {
|
| const metricDefinitions = {
|
| 'AR': {
|
| name: 'AR',
|
| fullName: 'Authenticité Réflexive',
|
| question: 'L\'analyse reflète-t-elle fidèlement la situation réelle de l\'étudiant ?'
|
| },
|
| 'AE': {
|
| name: 'AE',
|
| fullName: 'Alignement Empathique',
|
| question: 'L\'agent comprend-il les émotions, motivations et difficultés de l\'étudiant ?'
|
| },
|
| 'ESR': {
|
| name: 'ESR',
|
| fullName: 'Encouragement Sensible au Risque',
|
| question: 'Les encouragements tiennent-ils compte des risques et difficultés identifiés ?'
|
| },
|
| 'SDM': {
|
| name: 'SDM',
|
| fullName: 'Support aux Défis Mentaux',
|
| question: 'L\'agent aide-t-il l\'étudiant à développer sa pensée critique et ses compétences cognitives ?'
|
| },
|
| 'SM': {
|
| name: 'SM',
|
| fullName: 'Support Métacognitif',
|
| question: 'L\'agent aide-t-il l\'étudiant à réfléchir sur ses propres stratégies d\'apprentissage ?'
|
| }
|
| };
|
|
|
| let html = '';
|
|
|
| Object.entries(metricDefinitions).forEach(([code, def]) => {
|
| const value = metrics[code] || 0;
|
| const stars = getStarsHTML(value);
|
|
|
| html += `
|
| <div class="metric-detail">
|
| <div style="font-weight:bold;color:#1976D2;">${def.fullName} (${def.name})</div>
|
| <div class="stars-container">${stars}</div>
|
| <div class="metric-question">${def.question}</div>
|
| <div style="font-size:11px;color:#666;margin-top:3px;">
|
| Score: ${value}/5
|
| </div>
|
| </div>
|
| `;
|
| });
|
|
|
| return html;
|
| }
|
|
|
| function getStarsHTML(value) {
|
| let stars = '';
|
| const normalizedValue = Math.min(5, Math.max(0, value));
|
| for (let i = 1; i <= 5; i++) {
|
| stars += `<span class="star ${i <= normalizedValue ? '' : 'empty'}">★</span>`;
|
| }
|
| return stars;
|
| }
|
|
|
| function displayReviewStatus(review) {
|
| if (!review) {
|
| return '<small style="color:#666;">Non reviewé</small>';
|
| }
|
|
|
| const decisionText = {
|
| 'approved': '✅ Approuvé',
|
| 'needs_revision': '⚠️ Révision',
|
| 'rejected': '❌ Rejeté'
|
| };
|
|
|
| const decisionClass = {
|
| 'approved': 'review-approved',
|
| 'needs_revision': 'review-revision',
|
| 'rejected': 'review-rejected'
|
| };
|
|
|
| return `
|
| <div>
|
| <span class="review-badge ${decisionClass[review.decision]}">
|
| ${decisionText[review.decision]}
|
| </span><br>
|
| <small style="font-size:10px;">${formatDate(new Date(review.timestamp))}</small><br>
|
| <small style="color:#666;font-size:10px;">${review.reviewer || 'Anonyme'}</small>
|
| </div>
|
| `;
|
| }
|
|
|
|
|
| function openReviewModal(evaluationId) {
|
| const evaluation = allEvaluations.find(e => e.id === evaluationId);
|
| if (!evaluation) {
|
| alert('Évaluation non trouvée');
|
| return;
|
| }
|
|
|
| const scenario = scenariosData.find(s => s.id === evaluation.scenario_id);
|
| currentReviewEvalId = evaluationId;
|
|
|
| document.getElementById('modalEvaluator').textContent =
|
| `${evaluation.evaluator_name || 'Anonyme'} (${evaluation.evaluator_role || ''})`;
|
| document.getElementById('modalScenario').textContent =
|
| `Scénario ${evaluation.scenario_id || 'N/A'} - ${scenario ? scenario.title : 'Non trouvé'}`;
|
| document.getElementById('modalScore').textContent = `${evaluation.trust_score || 0}%`;
|
|
|
|
|
| const existingReview = reviewsData.find(r => r.evaluation_id === evaluationId);
|
| if (existingReview) {
|
| document.getElementById('reviewDecision').value = existingReview.decision;
|
| document.getElementById('reviewComment').value = existingReview.review_comment || '';
|
| } else {
|
| document.getElementById('reviewDecision').value = 'approved';
|
| document.getElementById('reviewComment').value = '';
|
| }
|
|
|
| document.getElementById('reviewModal').style.display = 'flex';
|
| }
|
|
|
| function closeReviewModal() {
|
| document.getElementById('reviewModal').style.display = 'none';
|
| currentReviewEvalId = null;
|
| }
|
|
|
| function saveReview() {
|
| if (!currentReviewEvalId) return;
|
|
|
| const decision = document.getElementById('reviewDecision').value;
|
| const reviewComment = document.getElementById('reviewComment').value.trim();
|
|
|
| const evaluation = allEvaluations.find(e => e.id === currentReviewEvalId);
|
| if (!evaluation) return;
|
|
|
|
|
| const reviewData = {
|
| evaluation_id: currentReviewEvalId,
|
| scenario_id: evaluation.scenario_id,
|
| evaluator_name: evaluation.evaluator_name,
|
| evaluator_role: evaluation.evaluator_role,
|
| original_score: evaluation.trust_score,
|
| original_comment: evaluation.comment,
|
| decision: decision,
|
| review_comment: reviewComment,
|
| reviewer: 'Expert Reviewer',
|
| timestamp: new Date().toISOString()
|
| };
|
|
|
|
|
| fetch('/api/save_review', {
|
| method: 'POST',
|
| headers: {
|
| 'Content-Type': 'application/json',
|
| },
|
| body: JSON.stringify(reviewData)
|
| })
|
| .then(response => {
|
|
|
| const contentType = response.headers.get("content-type");
|
| if (!contentType || !contentType.includes("application/json")) {
|
| return response.text().then(text => {
|
| throw new Error(`Le serveur a renvoyé du HTML au lieu du JSON. Vérifiez que l'API /api/save_review existe.`);
|
| });
|
| }
|
| return response.json();
|
| })
|
| .then(data => {
|
| if (data.status === 'ok') {
|
|
|
| const reviewId = `review_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
| reviewsData.push({
|
| id: reviewId,
|
| ...reviewData
|
| });
|
|
|
|
|
| filterAllEvaluations();
|
|
|
|
|
| closeReviewModal();
|
|
|
| showSuccessMessage(`✅ Review sauvegardé avec succès ! (${reviewsData.length} reviews au total)`);
|
| } else {
|
| throw new Error(data.error || 'Erreur inconnue');
|
| }
|
| })
|
| .catch(error => {
|
| console.error('Erreur sauvegarde review:', error);
|
|
|
|
|
| const reviewId = `review_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
| const localReview = {
|
| id: reviewId,
|
| ...reviewData
|
| };
|
|
|
| reviewsData.push(localReview);
|
|
|
|
|
| filterAllEvaluations();
|
|
|
|
|
| closeReviewModal();
|
|
|
| showSuccessMessage(`✅ Review sauvegardé localement (API non disponible). (${reviewsData.length} reviews)`);
|
|
|
|
|
| showWarningMessage(`Le review a été sauvegardé localement. Pour une sauvegarde permanente,
|
| ajoutez l'endpoint /api/save_review à votre backend Flask.`);
|
| });
|
| }
|
|
|
|
|
| function updateCharts(scenarioMetrics) {
|
|
|
| if (chart1) chart1.destroy();
|
| if (chart2) chart2.destroy();
|
|
|
| if (scenarioMetrics.length === 0) {
|
| document.querySelectorAll('.chart-container').forEach(container => {
|
| container.innerHTML = '<p style="text-align:center;color:#666;padding:40px;">Aucune donnée à afficher</p>';
|
| });
|
| return;
|
| }
|
|
|
|
|
| const labels = scenarioMetrics.map(m => `Scénario ${m.scenarioId}`);
|
| const avgScores = scenarioMetrics.map(m => Math.round(m.avgScore));
|
| const stdDevs = scenarioMetrics.map(m => Math.round(m.stdDev));
|
| const evaluationCounts = scenarioMetrics.map(m => m.evaluations.length);
|
|
|
|
|
| const ctx1 = document.getElementById('confidenceChart').getContext('2d');
|
| chart1 = new Chart(ctx1, {
|
| type: 'bar',
|
| data: {
|
| labels: labels,
|
| datasets: [{
|
| label: 'Confiance moyenne (%)',
|
| data: avgScores,
|
| backgroundColor: avgScores.map(score =>
|
| score >= 70 ? 'rgba(67, 160, 71, 0.7)' :
|
| score >= 40 ? 'rgba(251, 140, 0, 0.7)' :
|
| 'rgba(229, 57, 53, 0.7)'
|
| ),
|
| borderColor: avgScores.map(score =>
|
| score >= 70 ? '#43A047' :
|
| score >= 40 ? '#FB8C00' :
|
| '#E53935'
|
| ),
|
| borderWidth: 1
|
| }]
|
| },
|
| options: {
|
| responsive: true,
|
| maintainAspectRatio: false,
|
| plugins: {
|
| title: {
|
| display: true,
|
| text: 'Confiance moyenne par scénario',
|
| font: { size: 16 }
|
| },
|
| tooltip: {
|
| callbacks: {
|
| label: function(context) {
|
| const scenario = scenarioMetrics[context.dataIndex];
|
| return [
|
| `Confiance: ${context.parsed.y}%`,
|
| `Évaluations: ${scenario.evaluations.length}`,
|
| `Min: ${Math.round(scenario.minScore)}%, Max: ${Math.round(scenario.maxScore)}%`,
|
| `Conflit: ${scenario.conflictLevel === 'high' ? 'Élevé' :
|
| scenario.conflictLevel === 'medium' ? 'Moyen' : 'Faible'}`
|
| ];
|
| }
|
| }
|
| }
|
| },
|
| scales: {
|
| y: {
|
| beginAtZero: true,
|
| max: 100,
|
| title: {
|
| display: true,
|
| text: 'Score de confiance (%)'
|
| }
|
| }
|
| }
|
| }
|
| });
|
|
|
|
|
| const ctx2 = document.getElementById('conflictChart').getContext('2d');
|
| chart2 = new Chart(ctx2, {
|
| type: 'line',
|
| data: {
|
| labels: labels,
|
| datasets: [
|
| {
|
| label: 'Écart-type (conflit)',
|
| data: stdDevs,
|
| borderColor: '#E53935',
|
| backgroundColor: 'rgba(229, 57, 53, 0.1)',
|
| borderWidth: 2,
|
| fill: true,
|
| tension: 0.4
|
| },
|
| {
|
| label: 'Nombre d\'évaluations',
|
| data: evaluationCounts,
|
| borderColor: '#1976D2',
|
| backgroundColor: 'rgba(25, 118, 210, 0.1)',
|
| borderWidth: 2,
|
| fill: true,
|
| tension: 0.4,
|
| yAxisID: 'y1'
|
| }
|
| ]
|
| },
|
| options: {
|
| responsive: true,
|
| maintainAspectRatio: false,
|
| plugins: {
|
| title: {
|
| display: true,
|
| text: 'Niveau de conflit et nombre d\'évaluations',
|
| font: { size: 16 }
|
| }
|
| },
|
| scales: {
|
| y: {
|
| beginAtZero: true,
|
| title: {
|
| display: true,
|
| text: 'Écart-type (%)'
|
| }
|
| },
|
| y1: {
|
| beginAtZero: true,
|
| position: 'right',
|
| title: {
|
| display: true,
|
| text: 'Nombre d\'évaluations'
|
| },
|
| grid: {
|
| drawOnChartArea: false
|
| }
|
| }
|
| }
|
| }
|
| });
|
| }
|
|
|
|
|
| function showScenarioDetails(scenarioId) {
|
| const scenario = scenariosData.find(s => s.id === scenarioId);
|
| const evaluations = allEvaluations.filter(e => e.scenario_id === scenarioId);
|
|
|
| if (!scenario) {
|
| alert('Scénario non trouvé');
|
| return;
|
| }
|
|
|
|
|
| document.getElementById('detailScenarioTitle').textContent = `${scenarioId} - ${scenario.title}`;
|
|
|
|
|
| const avgScore = evaluations.reduce((sum, e) => sum + (e.trust_score || 0), 0) / evaluations.length;
|
| const metricsAvg = {};
|
| const metricsStdDev = {};
|
|
|
|
|
| const metricKeys = ['AR', 'AE', 'ESR', 'SDM', 'SM'];
|
| metricKeys.forEach(key => {
|
| const values = evaluations.map(e => e.trust_metrics[key] || 0);
|
| metricsAvg[key] = values.reduce((sum, v) => sum + v, 0) / values.length;
|
|
|
|
|
| if (values.length > 1) {
|
| const variance = values.reduce((sum, v) => sum + Math.pow(v - metricsAvg[key], 2), 0) / values.length;
|
| metricsStdDev[key] = Math.sqrt(variance);
|
| } else {
|
| metricsStdDev[key] = 0;
|
| }
|
| });
|
|
|
|
|
| let html = `
|
| <div style="margin-bottom: 20px;">
|
| <h3>${scenario.manifest?.manifeste || 'Pas de manifeste'}</h3>
|
| <p><strong>Type:</strong> ${scenario.manifest?.type || 'Non spécifié'}</p>
|
| <p><strong>Description:</strong> ${scenario.manifest?.description || 'Pas de description'}</p>
|
| </div>
|
|
|
| <div class="details-grid">
|
| <div class="details-card">
|
| <h4>📊 Résumé des évaluations</h4>
|
| <p><strong>Nombre d'évaluations:</strong> ${evaluations.length}</p>
|
| <p><strong>Confiance moyenne:</strong> ${Math.round(avgScore)}%</p>
|
| <p><strong>Plage de scores:</strong> ${Math.round(Math.min(...evaluations.map(e => e.trust_score || 0)))}% -
|
| ${Math.round(Math.max(...evaluations.map(e => e.trust_score || 0)))}%</p>
|
| <p><strong>Période:</strong> ${formatDate(new Date(Math.min(...evaluations.map(e => new Date(e.timestamp).getTime()))))}
|
| à ${formatDate(new Date(Math.max(...evaluations.map(e => new Date(e.timestamp).getTime()))))}</p>
|
| </div>
|
|
|
| <div class="details-card">
|
| <h4>🎯 Métriques moyennes</h4>
|
| ${metricKeys.map(key => `
|
| <div style="margin: 5px 0;">
|
| <span style="display:inline-block;width:100px;">${getMetricName(key)}:</span>
|
| <span style="font-weight:bold;color:#1976D2;">${metricsAvg[key].toFixed(1)}/5</span>
|
| <div style="display:inline-block;width:100px;height:10px;background:#e0e0e0;border-radius:5px;margin-left:10px;">
|
| <div style="height:100%;width:${metricsAvg[key] * 20}%;background:#1976D2;border-radius:5px;"></div>
|
| </div>
|
| </div>
|
| `).join('')}
|
| </div>
|
| </div>
|
|
|
| <h3 style="margin-top:30px;">📋 Détail des évaluations</h3>
|
| `;
|
|
|
|
|
| html += `
|
| <table style="margin-top:20px;">
|
| <thead>
|
| <tr>
|
| <th>Évaluateur</th>
|
| <th>Date</th>
|
| <th>Score global</th>
|
| ${metricKeys.map(key => `<th>${getMetricName(key)}</th>`).join('')}
|
| <th>Commentaire</th>
|
| </tr>
|
| </thead>
|
| <tbody>
|
| `;
|
|
|
| evaluations.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp)).forEach(eval => {
|
| html += `
|
| <tr>
|
| <td><strong>${eval.evaluator_name || 'Anonyme'}</strong><br>
|
| <small>${eval.evaluator_role || ''}</small></td>
|
| <td>${formatDate(new Date(eval.timestamp))}</td>
|
| <td>
|
| <div style="font-weight:bold;color:#1976D2;">${eval.trust_score || 0}%</div>
|
| <div class="confidence-bar">
|
| <div class="confidence-fill ${getConfidenceClass(eval.trust_score || 0)}"
|
| style="width: ${eval.trust_score || 0}%"></div>
|
| </div>
|
| </td>
|
| ${metricKeys.map(key => `
|
| <td>
|
| <div style="text-align:center;font-weight:bold;color:#1976D2;">${eval.trust_metrics[key] || 0}/5</div>
|
| <div style="display:flex;justify-content:center;gap:2px;margin-top:5px;">
|
| ${[1,2,3,4,5].map(i => `
|
| <div style="width:12px;height:12px;border-radius:50%;
|
| background:${i <= (eval.trust_metrics[key] || 0) ? '#1976D2' : '#e0e0e0'}"></div>
|
| `).join('')}
|
| </div>
|
| </td>
|
| `).join('')}
|
| <td><small style="color:#666;">${eval.comment || 'Aucun commentaire'}</small></td>
|
| </tr>
|
| `;
|
| });
|
|
|
| html += `</tbody></table>`;
|
|
|
|
|
| if (evaluations.length > 1) {
|
| html += `
|
| <h3 style="margin-top:30px;">🔍 Analyse des divergences</h3>
|
| <div class="comparison-chart">
|
| `;
|
|
|
| metricKeys.forEach(key => {
|
| const values = evaluations.map(e => e.trust_metrics[key] || 0);
|
| const maxDiff = Math.max(...values) - Math.min(...values);
|
|
|
| html += `
|
| <div class="comparison-item">
|
| <h4>${getMetricName(key)}</h4>
|
| <p style="font-size:24px;font-weight:bold;color:${maxDiff >= 3 ? '#E53935' :
|
| maxDiff >= 2 ? '#FB8C00' : '#43A047'}">
|
| ${maxDiff} pts
|
| </p>
|
| <p><small>Différence maximale</small></p>
|
| <p>Moyenne: ${metricsAvg[key].toFixed(1)}/5</p>
|
| <p>Écart-type: ${metricsStdDev[key].toFixed(1)}</p>
|
| </div>
|
| `;
|
| });
|
|
|
| html += `</div>`;
|
| }
|
|
|
|
|
| document.getElementById('scenarioContent').innerHTML = html;
|
| document.getElementById('scenarioDetails').classList.add('active');
|
|
|
|
|
| document.getElementById('scenarioDetails').scrollIntoView({ behavior: 'smooth' });
|
| }
|
|
|
|
|
| function getMetricName(code) {
|
| const names = {
|
| 'AR': 'Authenticité Réflexive',
|
| 'AE': 'Alignement Empathique',
|
| 'ESR': 'Encouragement Sensible au Risque',
|
| 'SDM': 'Support aux Défis Mentaux',
|
| 'SM': 'Support Métacognitif'
|
| };
|
| return names[code] || code;
|
| }
|
|
|
| function getConfidenceClass(score) {
|
| if (score >= 70) return 'high-confidence';
|
| if (score >= 40) return 'medium-confidence';
|
| return 'low-confidence';
|
| }
|
|
|
| function formatDate(date) {
|
| if (!date || isNaN(date.getTime())) {
|
| return 'Date invalide';
|
| }
|
| return date.toLocaleDateString('fr-FR', {
|
| day: '2-digit',
|
| month: '2-digit',
|
| year: 'numeric',
|
| hour: '2-digit',
|
| minute: '2-digit'
|
| });
|
| }
|
|
|
|
|
| function showLoadingMessage(message) {
|
| const loadingDiv = document.querySelector('.loading p') || document.createElement('p');
|
| loadingDiv.textContent = message;
|
| }
|
|
|
| function showSuccessMessage(message) {
|
| const successDiv = document.getElementById('successMessage');
|
| if (successDiv) {
|
| successDiv.innerHTML = `✅ ${message}`;
|
| successDiv.style.display = 'block';
|
| setTimeout(() => {
|
| successDiv.style.display = 'none';
|
| }, 5000);
|
| }
|
| }
|
|
|
| function showErrorMessage(message) {
|
| const tableContainer = document.getElementById('evaluationsTable');
|
| if (tableContainer) {
|
| tableContainer.innerHTML = `
|
| <div class="error-message">
|
| <h3>⚠️ Erreur de chargement</h3>
|
| <div>${message}</div>
|
| </div>
|
| `;
|
| }
|
| }
|
|
|
| function showWarningMessage(message) {
|
| const warningDiv = document.getElementById('warningMessage');
|
| if (warningDiv) {
|
| warningDiv.innerHTML = `
|
| <strong>⚠️ Aucune donnée trouvée</strong>
|
| <p>${message}</p>
|
| <button onclick="generateTestData()" class="test-data-btn">
|
| 🧪 Générer des données de test
|
| </button>
|
| `;
|
| warningDiv.style.display = 'block';
|
| }
|
| }
|
|
|
|
|
| window.filterData = filterData;
|
| window.filterAllEvaluations = filterAllEvaluations;
|
| window.showScenarioDetails = showScenarioDetails;
|
| window.openReviewModal = openReviewModal;
|
| window.closeReviewModal = closeReviewModal;
|
| window.saveReview = saveReview;
|
| window.generateTestData = generateTestData;
|
| window.loadData = loadData; |