Compare commits

..

37 Commits

Author SHA1 Message Date
376844d7e8 renforcement chatbot 2026-03-27 09:58:51 +01:00
3cf1349060 Fix chatbot multi-provider + encryption key + test UI 2026-03-27 09:55:23 +01:00
9e754c1bc0 update modeles 2026-01-05 09:30:37 +01:00
f199ce0653 modif selection chatbot 2026-01-05 09:25:37 +01:00
e3d392bf08 gestion chatbot avec api 2026-01-05 09:00:35 +01:00
a793b680be modif erreur chatbot 2026-01-04 18:19:22 +01:00
b96c9e26ff Fix: session_start et requête SQL id_conversation 2026-01-04 18:10:04 +01:00
0f88e614f8 interface monitoring chatbot 2026-01-04 17:53:54 +01:00
2d58bd0f5c mise en place gestion modele chatbot coté enseignant 2026-01-04 15:43:15 +01:00
b0d2a1d12e changement modele 2026-01-04 10:48:34 +01:00
8c74a843b2 petites erreurs 2026-01-04 10:43:37 +01:00
017cb697ba erreur chatbot 2026-01-04 10:26:53 +01:00
bff66c00ee amelioration latex 2026-01-04 10:08:27 +01:00
a1ef578526 erreur chatbot 2026-01-04 09:47:58 +01:00
b7896e4911 erreur chatbot 2026-01-04 09:29:40 +01:00
deca101d5a erreur sencore pour le chat bot 2026-01-03 16:10:16 +01:00
37833d9cf0 correction chatbot 2026-01-03 15:06:11 +01:00
f207a0f0af correction erreur questions chatbot 2026-01-03 15:02:09 +01:00
a98c8bc1c6 affichage modele chatbot 2026-01-03 14:58:04 +01:00
4ab9900d43 erreur tentative 2026-01-03 14:47:31 +01:00
5e86639948 erreur chatbot 2026-01-03 14:40:38 +01:00
935c8d0f98 erreur bouton 2026-01-03 14:36:53 +01:00
7ab227da1f modif passer!evaluation pour chatbot 2026-01-03 14:19:32 +01:00
f14ffdf35d ajout chatbot.css et .js 2026-01-03 14:12:35 +01:00
f2832a6300 creation chatbot 2026-01-03 14:04:26 +01:00
6d89f99827 correction erreur bouton monitor 2026-01-03 10:07:03 +01:00
21ea13fed3 correction erreur notes 2026-01-03 10:01:19 +01:00
bbb5fdec3a correction ereur note 2026-01-02 17:02:57 +01:00
761c7e76ed amelioration notes 2026-01-02 16:56:35 +01:00
ea8bdc1808 encore une erreur de bdd 2026-01-02 16:41:02 +01:00
1722dd9c7f erreur corrigée 2026-01-02 16:37:21 +01:00
8cad794c83 modification du dashboard eleve avec stats 2026-01-02 16:34:19 +01:00
a5490d8875 modif monitoring petites cellules 2026-01-02 16:24:12 +01:00
1413fe3c9c modification du monitoring enseignant 2026-01-02 16:17:59 +01:00
97427acc7a Add rollback_last.sh (rollback manuel dernier backup) 2026-01-02 15:36:00 +01:00
3603ad5e61 Add deploy_prod.sh (backup + rollback + exclusions) 2026-01-02 15:33:47 +01:00
f8b8c0bf67 Ignore evaluations/ (généré) — conservé en prod 2026-01-02 15:24:17 +01:00
63 changed files with 4612 additions and 248 deletions

4
.gitignore vendored
View File

@ -48,3 +48,7 @@ config/db_credentials.txt
*.bak_* *.bak_*
*.backup *.backup
*~ *~
# Evaluations générées (reconstruites depuis evaluations_transit)
evaluations/*
!evaluations/.gitkeep

267
api/chatbot.php Normal file
View File

@ -0,0 +1,267 @@
<?php
/**
* API Chatbot IA - MVP
* Modèle : qwen2-math:1.5b via Ollama local
*/
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json');
// Vérifier authentification élève
if (!isLoggedIn() || !isEleve()) {
echo json_encode(['error' => 'Non autorisé']);
exit;
}
$user = currentUser();
$db = Database::getInstance();
// Récupérer et valider les données
$id_tentative = filter_input(INPUT_POST, 'id_tentative', FILTER_VALIDATE_INT);
$id_question = filter_input(INPUT_POST, 'id_question', FILTER_VALIDATE_INT);
$message_eleve = trim($_POST['message'] ?? '');
if (!$id_tentative || !$id_question || empty($message_eleve)) {
echo json_encode(['error' => 'Données manquantes']);
exit;
}
// Vérifier que la tentative appartient à l'élève et est en cours
$tentative = $db->fetchOne(
"SELECT id_eleve FROM tentatives_eleves WHERE id_tentative = ? AND statut = 'en_cours'",
[$id_tentative]
);
if (!$tentative || $tentative['id_eleve'] != $user['id_utilisateur']) {
echo json_encode(['error' => 'Tentative invalide']);
exit;
}
// Vérifier limite (3 messages max par question)
$usage = $db->fetchOne(
"SELECT messages_count FROM chat_usage_limits WHERE id_tentative = ? AND id_question = ?",
[$id_tentative, $id_question]
);
$messages_count = $usage['messages_count'] ?? 0;
if ($messages_count >= 3) {
echo json_encode([
'error' => 'Limite atteinte',
'message' => 'Tu as utilisé toute ton aide pour cette question (3/3). Continue, tu peux le faire ! 💪',
'remaining' => 0
]);
exit;
}
// Récupérer l'énoncé de la question (SANS la réponse)
$question = $db->fetchOne(
"SELECT q.enonce, q.type_question, e.titre as titre_eval
FROM questions q
JOIN evaluations e ON q.id_evaluation = e.id_evaluation
WHERE q.id_question = ?",
[$id_question]
);
if (!$question) {
echo json_encode(['error' => 'Question introuvable']);
exit;
}
$enonce_question = $question['enonce'];
$titre_eval = $question['titre_eval'];
$type_question = $question['type_question'];
// Récupérer ou créer la conversation
$conversation = $db->fetchOne(
"SELECT id FROM chat_conversations
WHERE id_tentative = ? AND id_question = ?",
[$id_tentative, $id_question]
);
if (!$conversation) {
// Créer nouvelle conversation
$id_conversation = $db->insert(
"INSERT INTO chat_conversations (id_tentative, id_question, id_eleve, modele_utilise)
VALUES (?, ?, ?, 'qwen2-math:1.5b')",
[$id_tentative, $id_question, $user['id_utilisateur']]
);
} else {
$id_conversation = $conversation['id'];
}
// Récupérer l'historique de la conversation
$historique = $db->fetchAll(
"SELECT role, message FROM chat_messages
WHERE id_conversation = ?
ORDER BY timestamp ASC",
[$id_conversation]
);
// Numéro d'aide actuel (1, 2 ou 3)
$numero_aide = $messages_count + 1;
$system_prompt = "Tu es un assistant pédagogique en mathématiques pour collège/lycée.
L'élève a droit à exactement 3 aides par question. C'est son aide numéro {$numero_aide}/3.
═══════════════════════════════════════
RÈGLE ABSOLUE : NE JAMAIS DONNER LA RÉPONSE
═══════════════════════════════════════
Même si l'élève demande directement, même s'il insiste, même s'il dit avoir cherché :
TU NE DONNES JAMAIS la réponse, ni le résultat, ni le mot/nombre final attendu.
Cela inclut : nommer la transformation, donner le résultat d'un calcul, compléter la phrase avec la solution.
LONGUEUR : Réponds en 2-4 phrases MAXIMUM. Sois direct et concis.
SELON LE NUMÉRO D'AIDE :
- Aide 1/3 : Question ouverte pour faire réfléchir. Ex: \"Qu'est-ce qui change entre la figure de départ et la figure d'arrivée ?\"
- Aide 2/3 : Indice plus ciblé sur la méthode. Ex: \"Regarde si la figure a été déplacée, tournée, ou agrandie...\"
- Aide 3/3 : Démarche pas-à-pas SANS donner le mot final. Ex: \"Compare les coordonnées : le point A(1,2) devient A'(4,2). Que remarques-tu sur x ? Sur y ?\"
CE QUE TU NE FAIS JAMAIS :
\"La réponse est...\" / \"C'est une translation\" / \"Le résultat est 17\"
❌ Confirmer si l'élève a trouvé la bonne réponse
❌ Faire le calcul complet à sa place
❌ Réponses de plus de 4 phrases
CE QUE TU FAIS :
✅ Poser UNE question ciblée
✅ Donner UN indice de méthode
✅ Orienter sans révéler
ÉNONCÉ DE LA QUESTION (contexte uniquement - NE PAS RÉSOUDRE) :
" . strip_tags($enonce_question);
// Construire l'historique pour Ollama
$messages_ollama = [];
foreach ($historique as $msg) {
$messages_ollama[] = [
'role' => $msg['role'],
'content' => $msg['message']
];
}
// Ajouter le nouveau message de l'élève
$messages_ollama[] = [
'role' => 'user',
'content' => $message_eleve
];
// Appel à Ollama (qwen2-math:1.5b)
$start_time = microtime(true);
$ch = curl_init('http://localhost:11434/api/chat');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_TIMEOUT => 30,
CURLOPT_POSTFIELDS => json_encode([
'model' => 'ministral-3:3b',
'messages' => array_merge([
['role' => 'system', 'content' => $system_prompt]
], $messages_ollama),
'stream' => false,
'options' => [
'temperature' => 0.7,
'num_predict' => 200, // Réponses courtes
'top_p' => 0.9
]
])
]);
$response = curl_exec($ch);
$curl_error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$end_time = microtime(true);
$temps_reponse_ms = round(($end_time - $start_time) * 1000);
// Gérer les erreurs
if ($curl_error) {
error_log("Erreur Ollama CURL: $curl_error");
echo json_encode(['error' => 'Service temporairement indisponible (connexion)']);
exit;
}
if ($http_code !== 200) {
error_log("Erreur Ollama HTTP $http_code: $response");
echo json_encode(['error' => 'Service temporairement indisponible (HTTP ' . $http_code . ')']);
exit;
}
$data = json_decode($response, true);
if (!isset($data['message']['content'])) {
error_log("Réponse Ollama invalide: $response");
echo json_encode(['error' => 'Erreur de génération']);
exit;
}
$reponse_ia = trim($data['message']['content']);
// ============================================================
// DÉTECTION : la réponse de l'IA contient-elle la solution ?
// Si oui, on remplace par un message neutre
// ============================================================
function detecterReponseDirecte($texte, $enonce) {
$texte_lower = mb_strtolower($texte);
// Patterns suspects : formulations qui donnent directement la réponse
$patterns_suspects = [
'/la\s+r[eé]ponse\s+est/i',
'/c\'?est\s+(une?\s+)?(translation|rotation|homoth|sym[eé]trie|vecteur)/i',
'/il\s+s\'?agit\s+(d\'?une?|du)/i',
'/on\s+obtient\s*:/i',
'/le\s+r[eé]sultat\s+est/i',
'/donc\s*[=:]\s*\d/i',
'/la\s+solution\s+est/i',
'/r[eé]ponse\s+correcte/i',
];
foreach ($patterns_suspects as $pattern) {
if (preg_match($pattern, $texte)) {
error_log("Chatbot: réponse directe détectée, remplacement. Pattern: $pattern");
return true;
}
}
return false;
}
if (detecterReponseDirecte($reponse_ia, $enonce_question)) {
$reponse_ia = "Je ne peux pas te donner la réponse directement, mais voici un indice : relis bien l'énoncé et demande-toi quelle transformation modifie la position d'une figure sans changer sa forme ni sa taille. Qu'est-ce que tu remarques ?";
}
// Sauvegarder le message de l'élève
$db->query(
"INSERT INTO chat_messages (id_conversation, role, message)
VALUES (?, 'user', ?)",
[$id_conversation, $message_eleve]
);
// Sauvegarder la réponse de l'IA
$db->query(
"INSERT INTO chat_messages (id_conversation, role, message, temps_reponse_ms)
VALUES (?, 'assistant', ?, ?)",
[$id_conversation, $reponse_ia, $temps_reponse_ms]
);
// Incrémenter le compteur d'utilisation
$db->query(
"INSERT INTO chat_usage_limits (id_tentative, id_question, messages_count)
VALUES (?, ?, 1)
ON DUPLICATE KEY UPDATE messages_count = messages_count + 1",
[$id_tentative, $id_question]
);
$messages_restants = 2 - $messages_count;
// Réponse succès
echo json_encode([
'success' => true,
'response' => $reponse_ia,
'remaining' => $messages_restants,
'temps_ms' => $temps_reponse_ms
]);

View File

@ -0,0 +1,36 @@
<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json');
if (!isLoggedIn() || !isEleve()) {
echo json_encode(['error' => 'Non autorisé']);
exit;
}
$id_tentative = filter_input(INPUT_POST, 'id_tentative', FILTER_VALIDATE_INT);
$id_question = filter_input(INPUT_POST, 'id_question', FILTER_VALIDATE_INT);
if (!$id_tentative || !$id_question) {
echo json_encode(['error' => 'Données manquantes']);
exit;
}
$db = Database::getInstance();
// Vérifier limite
$usage = $db->fetchOne(
"SELECT messages_count FROM chat_usage_limits
WHERE id_tentative = ? AND id_question = ?",
[$id_tentative, $id_question]
);
$messages_count = $usage['messages_count'] ?? 0;
$remaining = max(0, 3 - $messages_count);
echo json_encode([
'success' => true,
'remaining' => $remaining,
'used' => $messages_count
]);

311
assets/css/chatbot.css Normal file
View File

@ -0,0 +1,311 @@
/* ====================================
CHATBOT IA - STYLES
==================================== */
/* Bouton flottant */
.chat-bubble {
position: fixed;
bottom: 80px;
right: 20px;
z-index: 1000;
}
.btn-chat {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 15px 25px;
border-radius: 50px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
transition: all 0.3s ease;
display: flex;
align-items: center;
gap: 8px;
}
.btn-chat:hover {
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}
.btn-chat:active {
transform: translateY(-1px);
}
.help-badge {
background: rgba(255, 255, 255, 0.3);
padding: 2px 8px;
border-radius: 12px;
font-size: 12px;
}
/* Modal chat */
#modal-chat {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: none;
z-index: 2000;
align-items: center;
justify-content: center;
animation: fadeIn 0.2s ease;
}
#modal-chat.show {
display: flex;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.chat-container {
background: white;
width: 90%;
max-width: 500px;
height: 600px;
max-height: 80vh;
border-radius: 15px;
display: flex;
flex-direction: column;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from {
transform: translateY(50px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.chat-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 15px 15px 0 0;
display: flex;
justify-content: space-between;
align-items: center;
}
.chat-header h3 {
margin: 0;
font-size: 18px;
font-weight: 600;
}
.btn-close-chat {
background: none;
border: none;
color: white;
font-size: 28px;
cursor: pointer;
padding: 0;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: background 0.2s;
}
.btn-close-chat:hover {
background: rgba(255, 255, 255, 0.2);
}
.chat-messages {
flex: 1;
padding: 20px;
overflow-y: auto;
background: #f5f5f5;
}
.chat-messages::-webkit-scrollbar {
width: 6px;
}
.chat-messages::-webkit-scrollbar-track {
background: #f1f1f1;
}
.chat-messages::-webkit-scrollbar-thumb {
background: #667eea;
border-radius: 3px;
}
.message {
margin-bottom: 15px;
padding: 12px 15px;
border-radius: 12px;
max-width: 85%;
animation: messageAppear 0.3s ease;
word-wrap: break-word;
}
@keyframes messageAppear {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.message-user {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
margin-left: auto;
text-align: right;
border-bottom-right-radius: 4px;
}
.message-assistant {
background: white;
color: #333;
border: 1px solid #e0e0e0;
margin-right: auto;
border-bottom-left-radius: 4px;
}
.message-assistant::before {
content: "🤖 ";
font-size: 14px;
}
.message-system {
background: #e3f2fd;
color: #1976d2;
text-align: center;
font-size: 14px;
padding: 10px;
margin: 10px auto;
border-radius: 8px;
max-width: 90%;
}
.chat-loading {
text-align: center;
padding: 15px;
color: #999;
font-style: italic;
}
.chat-loading::before {
content: "💭 ";
}
.typing-indicator {
display: inline-flex;
gap: 4px;
padding: 10px 15px;
background: white;
border-radius: 12px;
border: 1px solid #e0e0e0;
}
.typing-dot {
width: 8px;
height: 8px;
background: #667eea;
border-radius: 50%;
animation: typing 1.4s infinite;
}
.typing-dot:nth-child(2) {
animation-delay: 0.2s;
}
.typing-dot:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes typing {
0%, 60%, 100% {
transform: translateY(0);
opacity: 0.5;
}
30% {
transform: translateY(-10px);
opacity: 1;
}
}
.chat-input-zone {
padding: 15px;
border-top: 1px solid #e0e0e0;
background: white;
border-radius: 0 0 15px 15px;
}
.chat-input-zone textarea {
width: 100%;
padding: 12px;
border: 2px solid #e0e0e0;
border-radius: 8px;
resize: none;
font-family: inherit;
font-size: 14px;
transition: border-color 0.2s;
}
.chat-input-zone textarea:focus {
outline: none;
border-color: #667eea;
}
.chat-input-zone button {
margin-top: 10px;
width: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px;
border-radius: 8px;
font-weight: 600;
font-size: 14px;
cursor: pointer;
transition: all 0.2s;
}
.chat-input-zone button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.chat-input-zone button:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Responsive */
@media (max-width: 600px) {
.chat-container {
width: 100%;
height: 100%;
max-height: 100%;
border-radius: 0;
}
.chat-header {
border-radius: 0;
}
.chat-input-zone {
border-radius: 0;
}
}

View File

@ -0,0 +1,743 @@
/**
* Styles pour la configuration API Chatbot
* Design moderne avec une palette professionnelle
*/
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
:root {
--primary: #667eea;
--primary-dark: #5568d3;
--secondary: #48bb78;
--danger: #f56565;
--warning: #ed8936;
--bg-main: #f7fafc;
--bg-card: #ffffff;
--text-primary: #2d3748;
--text-secondary: #718096;
--border: #e2e8f0;
--shadow-sm: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
--shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
--radius: 12px;
--transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
background: var(--bg-main);
color: var(--text-primary);
line-height: 1.6;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
padding: 2rem;
}
/* Header */
.page-header {
margin-bottom: 3rem;
}
.header-content {
position: relative;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: var(--text-secondary);
text-decoration: none;
font-size: 0.875rem;
margin-bottom: 1rem;
transition: var(--transition);
}
.back-link:hover {
color: var(--primary);
transform: translateX(-4px);
}
.page-header h1 {
font-size: 2.5rem;
font-weight: 700;
color: var(--text-primary);
margin-bottom: 0.5rem;
}
.subtitle {
font-size: 1.125rem;
color: var(--text-secondary);
}
/* Stats Banner */
.stats-banner {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1.5rem;
margin-bottom: 3rem;
}
.stat-card {
background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);
border-radius: var(--radius);
padding: 1.5rem;
display: flex;
align-items: center;
gap: 1rem;
box-shadow: var(--shadow-md);
transition: var(--transition);
}
.stat-card:hover {
transform: translateY(-4px);
box-shadow: var(--shadow-lg);
}
.stat-icon {
font-size: 2.5rem;
filter: brightness(0) invert(1);
opacity: 0.9;
}
.stat-content {
color: white;
}
.stat-value {
font-size: 2rem;
font-weight: 700;
line-height: 1;
margin-bottom: 0.25rem;
}
.stat-label {
font-size: 0.875rem;
opacity: 0.9;
}
/* Content Grid */
.content-grid {
display: grid;
grid-template-columns: 1fr 350px;
gap: 2rem;
margin-bottom: 3rem;
}
@media (max-width: 1024px) {
.content-grid {
grid-template-columns: 1fr;
}
}
/* Section Styling */
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1.5rem;
}
.section-header h2,
.section-header h3 {
font-size: 1.5rem;
font-weight: 600;
}
/* Buttons */
.btn-primary,
.btn-secondary,
.btn-danger,
.btn-test {
padding: 0.75rem 1.5rem;
border-radius: 8px;
border: none;
font-weight: 600;
font-size: 0.875rem;
cursor: pointer;
transition: var(--transition);
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
.btn-primary {
background: var(--primary);
color: white;
}
.btn-primary:hover {
background: var(--primary-dark);
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.btn-secondary {
background: var(--bg-card);
color: var(--text-primary);
border: 2px solid var(--border);
}
.btn-secondary:hover {
border-color: var(--primary);
color: var(--primary);
}
.btn-danger {
background: var(--danger);
color: white;
}
.btn-danger:hover {
background: #e53e3e;
}
.btn-test {
background: var(--secondary);
color: white;
}
.btn-test:hover {
background: #38a169;
}
.btn-sm {
padding: 0.5rem 1rem;
font-size: 0.8125rem;
}
/* Keys List */
.keys-list {
display: grid;
gap: 1.5rem;
}
.key-card {
background: var(--bg-card);
border-radius: var(--radius);
border: 2px solid var(--border);
overflow: hidden;
transition: var(--transition);
}
.key-card:hover {
box-shadow: var(--shadow-lg);
border-color: var(--primary);
}
.key-card.active {
border-color: var(--secondary);
}
.key-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.25rem;
background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
border-bottom: 1px solid var(--border);
}
.key-provider {
display: flex;
align-items: center;
gap: 0.75rem;
}
.provider-icon {
font-size: 1.5rem;
}
.provider-name {
font-weight: 600;
font-size: 1.125rem;
}
.status-badge {
padding: 0.375rem 0.75rem;
border-radius: 20px;
font-size: 0.8125rem;
font-weight: 600;
}
.status-badge.default {
background: linear-gradient(135deg, #f6d365 0%, #fda085 100%);
color: #744210;
font-weight: 700;
}
.status-badge.active {
background: #c6f6d5;
color: #22543d;
}
.status-badge.inactive {
background: #fed7d7;
color: #742a2a;
}
.status-badge.none {
background: #e2e8f0;
color: #4a5568;
}
.key-body {
padding: 1.25rem;
}
.key-info {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-bottom: 1rem;
}
.info-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 0;
}
.info-row .label {
color: var(--text-secondary);
font-size: 0.875rem;
}
.info-row .value {
font-weight: 500;
font-family: 'JetBrains Mono', monospace;
font-size: 0.875rem;
}
.quota-bar {
display: inline-block;
width: 100px;
height: 6px;
background: var(--border);
border-radius: 3px;
overflow: hidden;
margin-left: 0.5rem;
vertical-align: middle;
}
.quota-fill {
display: block;
height: 100%;
background: var(--secondary);
transition: width 0.3s ease;
}
.key-actions {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
}
.key-empty {
text-align: center;
padding: 2rem 1rem;
color: var(--text-secondary);
}
.key-empty p {
margin-bottom: 1rem;
}
/* Models Sidebar */
.models-sidebar {
background: var(--bg-card);
border-radius: var(--radius);
padding: 1.5rem;
border: 2px solid var(--border);
position: sticky;
top: 2rem;
max-height: calc(100vh - 4rem);
overflow-y: auto;
}
.models-list {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.provider-group h4 {
font-size: 1rem;
font-weight: 600;
margin-bottom: 0.75rem;
color: var(--text-primary);
}
.model-item {
padding: 0.75rem;
background: var(--bg-main);
border-radius: 8px;
border: 1px solid var(--border);
transition: var(--transition);
}
.model-item:hover {
border-color: var(--primary);
background: white;
}
.model-item.recommended {
border-color: var(--secondary);
background: #f0fff4;
}
.model-name {
font-weight: 500;
font-size: 0.875rem;
margin-bottom: 0.5rem;
display: flex;
align-items: center;
gap: 0.5rem;
}
.model-meta {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.badge-recommended,
.badge-free,
.badge-paid,
.badge-speed {
padding: 0.25rem 0.5rem;
border-radius: 4px;
font-size: 0.75rem;
font-weight: 600;
}
.badge-recommended {
background: #fef5e7;
}
.badge-free {
background: #c6f6d5;
color: #22543d;
}
.badge-paid {
background: #fed7d7;
color: #742a2a;
}
.help-box {
margin-top: 1.5rem;
padding: 1rem;
background: #ebf8ff;
border-radius: 8px;
border-left: 4px solid var(--primary);
}
.help-box h4 {
font-size: 0.875rem;
margin-bottom: 0.75rem;
}
.help-box ul {
list-style: none;
font-size: 0.8125rem;
line-height: 1.8;
}
.help-box li {
padding-left: 1rem;
position: relative;
}
.help-box li::before {
content: "→";
position: absolute;
left: 0;
color: var(--primary);
}
/* Stats Table */
.stats-section {
background: var(--bg-card);
border-radius: var(--radius);
padding: 1.5rem;
border: 2px solid var(--border);
}
.stats-table-wrapper {
overflow-x: auto;
}
.stats-table {
width: 100%;
border-collapse: collapse;
}
.stats-table thead {
background: var(--bg-main);
}
.stats-table th {
padding: 0.75rem 1rem;
text-align: left;
font-weight: 600;
font-size: 0.875rem;
color: var(--text-secondary);
border-bottom: 2px solid var(--border);
}
.stats-table td {
padding: 1rem;
border-bottom: 1px solid var(--border);
font-size: 0.875rem;
}
.stats-table tbody tr:hover {
background: var(--bg-main);
}
.provider-badge {
padding: 0.375rem 0.75rem;
background: var(--bg-main);
border-radius: 6px;
font-weight: 500;
display: inline-flex;
align-items: center;
gap: 0.5rem;
}
/* Modal */
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 1000;
backdrop-filter: blur(4px);
animation: fadeIn 0.2s ease;
}
.modal.show {
display: flex;
align-items: center;
justify-content: center;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.modal-content {
background: var(--bg-card);
border-radius: var(--radius);
max-width: 600px;
width: 90%;
max-height: 90vh;
overflow-y: auto;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1);
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.5rem;
border-bottom: 2px solid var(--border);
}
.modal-header h2 {
font-size: 1.5rem;
font-weight: 600;
}
.modal-close {
background: none;
border: none;
font-size: 2rem;
color: var(--text-secondary);
cursor: pointer;
line-height: 1;
transition: var(--transition);
}
.modal-close:hover {
color: var(--danger);
transform: scale(1.1);
}
/* Form */
#keyForm {
padding: 1.5rem;
}
.form-group {
margin-bottom: 1.5rem;
}
.form-group label {
display: block;
font-weight: 600;
margin-bottom: 0.5rem;
color: var(--text-primary);
}
.form-group input[type="text"],
.form-group input[type="password"],
.form-group input[type="number"],
.form-group select {
width: 100%;
padding: 0.75rem 1rem;
border: 2px solid var(--border);
border-radius: 8px;
font-size: 0.875rem;
font-family: 'JetBrains Mono', monospace;
transition: var(--transition);
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.input-with-button {
position: relative;
}
.input-with-button input {
padding-right: 3rem;
}
.btn-toggle-visibility {
position: absolute;
right: 0.5rem;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
font-size: 1.25rem;
cursor: pointer;
padding: 0.5rem;
opacity: 0.6;
transition: var(--transition);
}
.btn-toggle-visibility:hover {
opacity: 1;
}
.help-text {
display: block;
margin-top: 0.5rem;
font-size: 0.8125rem;
color: var(--text-secondary);
}
.form-actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 2rem;
padding-top: 1.5rem;
border-top: 2px solid var(--border);
}
.test-result {
margin-top: 1rem;
padding: 1rem;
border-radius: 8px;
font-size: 0.875rem;
}
.test-result.success {
background: #c6f6d5;
color: #22543d;
border: 2px solid #9ae6b4;
}
.test-result.error {
background: #fed7d7;
color: #742a2a;
border: 2px solid #fc8181;
}
/* Toast */
#toast-container {
position: fixed;
bottom: 2rem;
right: 2rem;
z-index: 2000;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.toast {
background: white;
padding: 1rem 1.5rem;
border-radius: 8px;
box-shadow: var(--shadow-lg);
min-width: 300px;
display: flex;
align-items: center;
gap: 0.75rem;
border-left: 4px solid var(--primary);
animation: slideInRight 0.3s ease;
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(100%);
}
to {
opacity: 1;
transform: translateX(0);
}
}
.toast.success {
border-left-color: var(--secondary);
}
.toast.error {
border-left-color: var(--danger);
}
.toast-icon {
font-size: 1.5rem;
}
.toast-message {
flex: 1;
font-size: 0.875rem;
font-weight: 500;
}

306
assets/js/chatbot.js Normal file
View File

@ -0,0 +1,306 @@
/**
* CHATBOT IA - Client JavaScript
*/
class ChatbotIA {
constructor(tentativeId) {
this.tentativeId = tentativeId;
this.currentQuestionId = null;
this.helpRemaining = 3;
this.isLoading = false;
this.initElements();
this.attachEvents();
}
initElements() {
this.btnOpenChat = document.getElementById('btn-open-chat');
this.modalChat = document.getElementById('modal-chat');
this.btnCloseChat = document.getElementById('btn-close-chat');
this.chatMessages = document.getElementById('chat-messages');
this.chatInput = document.getElementById('chat-input');
this.btnSend = document.getElementById('btn-send');
this.helpRemainingSpan = document.getElementById('help-remaining');
}
attachEvents() {
// Ouvrir chat
this.btnOpenChat?.addEventListener('click', () => this.ouvrirChat());
// Fermer chat
this.btnCloseChat?.addEventListener('click', () => this.fermerChat());
// Clic en dehors du modal
this.modalChat?.addEventListener('click', (e) => {
if (e.target === this.modalChat) this.fermerChat();
});
// Envoyer message
this.btnSend?.addEventListener('click', () => this.envoyerMessage());
// Enter pour envoyer (Shift+Enter pour nouvelle ligne)
this.chatInput?.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
this.envoyerMessage();
}
});
}
ouvrirChat() {
// Utiliser la variable globale currentQuestion du formulaire
if (typeof window.currentQuestion !== 'undefined' && window.questionsIds) {
// currentQuestion est l'index (1-80), on récupère l'ID réel
const questionIndex = window.currentQuestion - 1;
this.currentQuestionId = window.questionsIds[questionIndex];
console.log('💬 Question détectée via currentQuestion:', window.currentQuestion, '→ ID:', this.currentQuestionId);
} else {
// Fallback sur la détection par classe active
this.currentQuestionId = this.detectCurrentQuestion();
}
if (!this.currentQuestionId) {
alert('Erreur : impossible de déterminer la question actuelle');
return;
}
console.log('💬 Ouverture chat - Question:', this.currentQuestionId);
// Charger l'aide restante pour cette question
this.loadHelpRemaining();
this.modalChat.classList.add('show');
this.chatInput.focus();
}
// NOUVELLE MÉTHODE : Détecter la question visible
detectCurrentQuestion() {
// Trouver la question la plus visible dans le viewport
const questionCards = document.querySelectorAll('.question-card[data-question-id]');
if (questionCards.length === 0) {
console.error('❌ Aucune question-card trouvée');
return null;
}
let closestQuestion = null;
let minDistance = Infinity;
const viewportCenter = window.innerHeight / 2;
questionCards.forEach(card => {
const rect = card.getBoundingClientRect();
// La question est visible dans le viewport
if (rect.top < window.innerHeight && rect.bottom > 0) {
const cardCenter = rect.top + (rect.height / 2);
const distance = Math.abs(cardCenter - viewportCenter);
if (distance < minDistance) {
minDistance = distance;
closestQuestion = card;
}
}
});
if (closestQuestion) {
const qId = parseInt(closestQuestion.dataset.questionId);
console.log('✅ Question visible détectée:', qId);
return qId;
}
// Fallback : première question
const firstCard = questionCards[0];
const qId = parseInt(firstCard.dataset.questionId);
console.log('⚠️ Fallback première question:', qId);
return qId;
}
// NOUVELLE MÉTHODE : Charger l'aide restante via AJAX
async loadHelpRemaining() {
try {
const response = await fetch('/mathematiques/api/chatbot_check_limit.php', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: new URLSearchParams({
id_tentative: this.tentativeId,
id_question: this.currentQuestionId
})
});
const data = await response.json();
if (data.success) {
this.helpRemaining = data.remaining;
this.updateHelpBadge();
}
} catch (error) {
console.error('Erreur chargement limite aide:', error);
}
}
fermerChat() {
this.modalChat.classList.remove('show');
}
getCurrentQuestionId() {
// À adapter selon ton code de passer_evaluation.php
// Option 1 : Variable globale JS
if (typeof currentQuestionId !== 'undefined') {
return currentQuestionId;
}
// Option 2 : Data attribute
const questionElement = document.querySelector('[data-question-id]');
if (questionElement) {
return questionElement.dataset.questionId;
}
// Option 3 : Input hidden
const hiddenInput = document.querySelector('input[name="id_question"]');
if (hiddenInput) {
return hiddenInput.value;
}
return null;
}
async envoyerMessage() {
const message = this.chatInput.value.trim();
if (!message || this.isLoading) return;
// Afficher message utilisateur
this.ajouterMessage(message, 'user');
this.chatInput.value = '';
// Loading
this.isLoading = true;
this.btnSend.disabled = true;
this.afficherTypingIndicator();
try {
const response = await fetch('/mathematiques/api/chatbot.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
id_tentative: this.tentativeId,
id_question: this.currentQuestionId,
message: message
})
});
const data = await response.json();
// Retirer typing indicator
this.retirerTypingIndicator();
if (data.error) {
this.ajouterMessage(data.message || data.error, 'system');
if (data.remaining === 0) {
this.helpRemaining = 0;
this.updateHelpBadge();
setTimeout(() => this.fermerChat(), 10000); // 10s au lieu de 3s
}
} else {
this.ajouterMessage(data.response, 'assistant');
this.helpRemaining = data.remaining;
this.updateHelpBadge();
// Afficher info modèle dans console
console.log('✅ Réponse IA -', 'Modèle:', data.modele || 'qwen2-math:1.5b', '- Temps:', data.temps_ms, 'ms');
if (this.helpRemaining === 0) {
setTimeout(() => {
this.ajouterMessage(
'⚠️ Tu as utilisé toute ton aide pour cette question (3/3).\n\nLe chat se fermera dans 10 secondes. Continue, tu peux le faire ! 💪',
'system'
);
// Bouton fermeture manuelle
const btnDiv = document.createElement('div');
btnDiv.className = 'message message-system';
btnDiv.style.textAlign = 'center';
btnDiv.innerHTML = '<button onclick="window.chatbot.fermerChat()" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; margin-top: 10px;">✕ Fermer maintenant</button>';
this.chatMessages.appendChild(btnDiv);
this.scrollToBottom();
// Fermeture auto après 10s
setTimeout(() => this.fermerChat(), 10000);
}, 500);
}
}
} catch (error) {
console.error('Erreur chatbot:', error);
this.retirerTypingIndicator();
this.ajouterMessage('❌ Erreur de connexion au serveur.', 'system');
} finally {
this.isLoading = false;
this.btnSend.disabled = false;
this.chatInput.focus();
}
}
ajouterMessage(texte, type) {
const msgDiv = document.createElement('div');
msgDiv.className = `message message-${type}`;
// Convertir le texte brut en HTML avec support LaTeX
const htmlContent = this.formatMathText(texte);
msgDiv.innerHTML = htmlContent;
this.chatMessages.appendChild(msgDiv);
// Rendre les formules mathématiques avec KaTeX
if (typeof renderMathInElement !== 'undefined') {
renderMathInElement(msgDiv, {
delimiters: [
{left: '$$', right: '$$', display: true}, // Mode display (centré)
{left: '$', right: '$', display: false}, // Mode inline
{left: '\\(', right: '\\)', display: false},
{left: '\\[', right: '\\]', display: true}
],
throwOnError: false,
trust: true
});
}
this.scrollToBottom();
}
// NOUVELLE MÉTHODE : Formater le texte avec support maths
formatMathText(texte) {
// Juste convertir \n en <br>
// Le reste (LaTeX) est géré par KaTeX
return texte.replace(/\n/g, '<br>');
}
afficherTypingIndicator() {
const typingDiv = document.createElement('div');
typingDiv.className = 'typing-indicator';
typingDiv.id = 'typing-indicator';
typingDiv.innerHTML = `
<span class="typing-dot"></span>
<span class="typing-dot"></span>
<span class="typing-dot"></span>
`;
this.chatMessages.appendChild(typingDiv);
this.scrollToBottom();
}
retirerTypingIndicator() {
document.getElementById('typing-indicator')?.remove();
}
scrollToBottom() {
this.chatMessages.scrollTop = this.chatMessages.scrollHeight;
}
updateHelpBadge() {
if (this.helpRemainingSpan) {
this.helpRemainingSpan.textContent = this.helpRemaining;
}
}
}

View File

@ -0,0 +1,439 @@
/**
* JavaScript pour la gestion des clés API du chatbot
*/
// État global
let currentProvider = null;
let editMode = false;
// Helper URLs
const API_HELP_URLS = {
'gemini': 'https://aistudio.google.com/apikey',
'mistral': 'https://console.mistral.ai/api-keys/',
'openai': 'https://platform.openai.com/api-keys'
};
// ========== Modal Management ==========
function openAddKeyModal(provider = null) {
const modal = document.getElementById('keyModal');
const title = document.getElementById('modalTitle');
const form = document.getElementById('keyForm');
const providerSelect = document.getElementById('provider');
const testResult = document.getElementById('testResult');
// Reset form
form.reset();
testResult.style.display = 'none';
document.getElementById('keyAction').value = 'add';
editMode = false;
// Important : activer le select AVANT de définir la valeur
providerSelect.disabled = false;
// Pre-select provider if provided
if (provider) {
providerSelect.value = provider;
providerSelect.dispatchEvent(new Event('change')); // Trigger updateModelsList
}
title.textContent = 'Ajouter une clé API';
modal.classList.add('show');
}
function editKey(provider) {
currentProvider = provider;
editMode = true;
// Récupérer les infos de la clé
fetch(`chatbot_api_ajax.php?action=get&provider=${provider}`)
.then(response => response.json())
.then(data => {
if (data.success) {
const modal = document.getElementById('keyModal');
const title = document.getElementById('modalTitle');
const form = document.getElementById('keyForm');
const providerSelect = document.getElementById('provider');
const modelSelect = document.getElementById('model_default');
const testResult = document.getElementById('testResult');
testResult.style.display = 'none';
document.getElementById('keyAction').value = 'edit';
// Remplir le formulaire
providerSelect.value = provider;
providerSelect.disabled = true;
// Champ hidden pour envoyer provider même si disabled
let hiddenProvider = document.getElementById('hidden_provider');
if (!hiddenProvider) {
hiddenProvider = document.createElement('input');
hiddenProvider.type = 'hidden';
hiddenProvider.name = 'provider';
hiddenProvider.id = 'hidden_provider';
document.getElementById('keyForm').appendChild(hiddenProvider);
}
hiddenProvider.value = provider;
updateModelsList();
// Attendre que la liste des modèles soit chargée
setTimeout(() => {
modelSelect.value = data.data.model_default;
if (data.data.quota_max) {
document.getElementById('set_quota').checked = true;
document.getElementById('quota_max').value = data.data.quota_max;
toggleQuotaInput();
}
}, 100);
title.textContent = `Modifier la clé ${provider}`;
modal.classList.add('show');
} else {
showToast(data.error || 'Erreur lors du chargement', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showToast('Erreur de connexion', 'error');
});
}
function closeKeyModal() {
const modal = document.getElementById('keyModal');
modal.classList.remove('show');
currentProvider = null;
editMode = false;
}
// ========== Form Handling ==========
function updateModelsList() {
const provider = document.getElementById('provider').value;
const modelSelect = document.getElementById('model_default');
const keyHelp = document.getElementById('keyHelp');
// Clear current options
modelSelect.innerHTML = '<option value="">-- Sélectionner un modèle --</option>';
if (!provider) {
keyHelp.innerHTML = '';
return;
}
// Populate models for selected provider
if (models[provider]) {
models[provider].forEach(model => {
const option = document.createElement('option');
option.value = model.model_id;
option.textContent = model.display_name;
if (model.recommended) {
option.textContent += ' ⭐';
}
modelSelect.appendChild(option);
});
// Auto-select first recommended model
const recommended = models[provider].find(m => m.recommended);
if (recommended) {
modelSelect.value = recommended.model_id;
}
}
// Update help text
if (API_HELP_URLS[provider]) {
keyHelp.innerHTML = `💡 Obtenir une clé : <a href="${API_HELP_URLS[provider]}" target="_blank">${API_HELP_URLS[provider]}</a>`;
} else {
keyHelp.innerHTML = '';
}
}
function toggleQuotaInput() {
const checkbox = document.getElementById('set_quota');
const quotaGroup = document.getElementById('quotaGroup');
quotaGroup.style.display = checkbox.checked ? 'block' : 'none';
}
function toggleKeyVisibility() {
const input = document.getElementById('api_key');
const button = event.target;
if (input.type === 'password') {
input.type = 'text';
button.textContent = '🙈';
} else {
input.type = 'password';
button.textContent = '👁️';
}
}
// ========== Form Submission ==========
document.getElementById('keyForm').addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
formData.append('action', 'save');
// Show loading
const submitBtn = this.querySelector('button[type="submit"]');
const originalText = submitBtn.innerHTML;
submitBtn.innerHTML = '⏳ Enregistrement...';
submitBtn.disabled = true;
fetch('chatbot_api_ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showToast(data.message || 'Clé enregistrée avec succès', 'success');
closeKeyModal();
// Reload page to show updated keys
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
showToast(data.error || 'Erreur lors de l\'enregistrement', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showToast('Erreur de connexion', 'error');
})
.finally(() => {
submitBtn.innerHTML = originalText;
submitBtn.disabled = false;
});
});
// ========== Test Connection ==========
function testKeyBeforeSave() {
const provider = document.getElementById('provider').value;
const apiKey = document.getElementById('api_key').value;
const model = document.getElementById('model_default').value;
if (!provider || !apiKey || !model) {
showToast('Veuillez remplir tous les champs obligatoires', 'error');
return;
}
testConnectionWithParams(provider, apiKey, model);
}
function testConnection(provider) {
testConnectionWithParams(provider, null, null);
}
function testConnectionWithParams(provider, apiKey = null, model = null) {
const testResult = document.getElementById('testResult');
testResult.style.display = 'block';
testResult.className = 'test-result';
testResult.innerHTML = '🔄 Test en cours...';
const formData = new FormData();
formData.append('action', 'test');
formData.append('provider', provider);
if (apiKey) formData.append('api_key', apiKey);
if (model) formData.append('model', model);
fetch('chatbot_api_ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
testResult.className = 'test-result success';
testResult.innerHTML = `${data.message}<br><small>Latence: ${data.latency_ms}ms</small>`;
} else {
testResult.className = 'test-result error';
testResult.innerHTML = `${data.message}`;
}
})
.catch(error => {
console.error('Error:', error);
testResult.className = 'test-result error';
testResult.innerHTML = '❌ Erreur de connexion au serveur';
});
}
// ========== Delete Key ==========
function deleteKey(provider) {
if (!confirm(`Êtes-vous sûr de vouloir supprimer la clé ${provider} ?\n\nCette action est irréversible.`)) {
return;
}
const formData = new FormData();
formData.append('action', 'delete');
formData.append('provider', provider);
fetch('chatbot_api_ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showToast('Clé supprimée avec succès', 'success');
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
showToast(data.error || 'Erreur lors de la suppression', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showToast('Erreur de connexion', 'error');
});
}
// ========== Set Default Provider ==========
function setAsDefault(provider, model) {
const formData = new FormData();
formData.append('action', 'set_default');
formData.append('provider', provider);
formData.append('model', model);
fetch('chatbot_api_ajax.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
showToast(data.message || 'Provider par défaut mis à jour', 'success');
setTimeout(() => {
window.location.reload();
}, 1000);
} else {
showToast(data.error || 'Erreur', 'error');
}
})
.catch(error => {
console.error('Error:', error);
showToast('Erreur de connexion', 'error');
});
}
// ========== Configure Ollama ==========
function configureOllama() {
const availableModels = models['ollama'] || [];
if (availableModels.length === 0) {
showToast('Aucun modèle Ollama disponible', 'error');
return;
}
// Créer une liste des modèles
let modelOptions = '<select id="ollama-model-select" style="width: 100%; padding: 0.5rem; margin: 1rem 0; border: 2px solid #e2e8f0; border-radius: 8px;">';
availableModels.forEach(model => {
modelOptions += `<option value="${model.model_id}">${model.display_name}</option>`;
});
modelOptions += '</select>';
// Simple prompt
const modelHtml = `
<div style="padding: 1rem;">
<p style="margin-bottom: 1rem;">Choisir le modèle Ollama par défaut :</p>
${modelOptions}
</div>
`;
// Utiliser une confirm box simple pour l'instant
// (dans une vraie app, utiliser le modal existant)
const modal = document.getElementById('keyModal');
const modalContent = modal.querySelector('.modal-content');
const originalContent = modalContent.innerHTML;
modalContent.innerHTML = `
<div class="modal-header">
<h2>Configuration Ollama</h2>
<button class="modal-close" onclick="closeKeyModal()">×</button>
</div>
<div style="padding: 1.5rem;">
<p style="margin-bottom: 1rem;">Choisir le modèle Ollama à utiliser par défaut :</p>
<select id="ollama-model-select" style="width: 100%; padding: 0.75rem; border: 2px solid #e2e8f0; border-radius: 8px; font-family: 'JetBrains Mono', monospace;">
${availableModels.map(m => `<option value="${m.model_id}">${m.display_name}</option>`).join('')}
</select>
<div style="display: flex; gap: 1rem; justify-content: flex-end; margin-top: 1.5rem; padding-top: 1.5rem; border-top: 2px solid #e2e8f0;">
<button class="btn-secondary" onclick="closeKeyModal(); document.querySelector('.modal-content').innerHTML = \`${originalContent.replace(/`/g, '\\`')}\`;">Annuler</button>
<button class="btn-primary" onclick="saveOllamaConfig()">💾 Enregistrer</button>
</div>
</div>
`;
modal.classList.add('show');
}
function saveOllamaConfig() {
const select = document.getElementById('ollama-model-select');
const model = select.value;
if (!model) {
showToast('Veuillez sélectionner un modèle', 'error');
return;
}
setAsDefault('ollama', model);
}
// ========== Toast Notifications ==========
function showToast(message, type = 'info') {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast ${type}`;
const icons = {
'success': '✅',
'error': '❌',
'warning': '⚠️',
'info': ''
};
toast.innerHTML = `
<span class="toast-icon">${icons[type] || icons.info}</span>
<span class="toast-message">${message}</span>
`;
container.appendChild(toast);
// Auto-remove after 4 seconds
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(100%)';
setTimeout(() => toast.remove(), 300);
}, 4000);
}
// ========== Close modal on outside click ==========
document.getElementById('keyModal').addEventListener('click', function(e) {
if (e.target === this) {
closeKeyModal();
}
});
// ========== Keyboard shortcuts ==========
document.addEventListener('keydown', function(e) {
// ESC to close modal
if (e.key === 'Escape') {
const modal = document.getElementById('keyModal');
if (modal.classList.contains('show')) {
closeKeyModal();
}
}
});
// ========== Initialize ==========
console.log('✅ Chatbot Settings JS loaded');
console.log('Available models:', models);

455
config/api_key_manager.php Normal file
View File

@ -0,0 +1,455 @@
<?php
/**
* Gestionnaire de clés API pour le chatbot
* Chiffrement AES-256-CBC des clés API
*
* @author WebVal
* @date 2026-01-04
*/
class APIKeyManager {
private static $encryption_key = null;
private static $db = null;
/**
* Initialiser la connexion BDD
*/
private static function init() {
if (self::$db === null) {
self::$db = Database::getInstance();
}
}
/**
* Récupérer la clé de chiffrement
* Ordre de priorité : ENV > Fichier > Génération
*/
private static function getEncryptionKey() {
if (self::$encryption_key !== null) {
return self::$encryption_key;
}
// 1. Variable d'environnement
$key = getenv('WEBVAL_API_ENCRYPTION_KEY');
// 2. Fichier externe (hors webroot)
if (!$key && file_exists('/etc/webval/encryption.key')) {
$key = file_get_contents('/etc/webval/encryption.key');
}
// 3. Fichier dans config (fallback)
$keyFile = __DIR__ . '/../config/.encryption_key';
if (!$key && file_exists($keyFile)) {
$key = file_get_contents($keyFile);
}
// 4. Générer une nouvelle clé si aucune n'existe
if (!$key) {
$key = bin2hex(random_bytes(32));
// Essayer de sauvegarder
if (is_writable(__DIR__ . '/../config/')) {
file_put_contents($keyFile, $key);
chmod($keyFile, 0600);
}
error_log("⚠️ Nouvelle clé de chiffrement générée. Sauvegarde recommandée.");
}
self::$encryption_key = $key;
return $key;
}
/**
* Chiffrer une clé API
*
* @param string $plaintext Clé API en clair
* @return string Clé chiffrée (base64)
*/
public static function encrypt($plaintext) {
if (empty($plaintext)) {
return null;
}
$key = hash('sha256', self::getEncryptionKey(), true);
$iv = random_bytes(16);
$ciphertext = openssl_encrypt(
$plaintext,
'AES-256-CBC',
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($ciphertext === false) {
throw new Exception("Erreur de chiffrement");
}
// Format: IV (16 bytes) + Ciphertext
return base64_encode($iv . $ciphertext);
}
/**
* Déchiffrer une clé API
*
* @param string $encrypted Clé chiffrée (base64)
* @return string|null Clé API en clair
*/
public static function decrypt($encrypted) {
if (empty($encrypted)) {
return null;
}
$key = hash('sha256', self::getEncryptionKey(), true);
$data = base64_decode($encrypted);
if ($data === false || strlen($data) < 16) {
throw new Exception("Données chiffrées invalides");
}
$iv = substr($data, 0, 16);
$ciphertext = substr($data, 16);
$plaintext = openssl_decrypt(
$ciphertext,
'AES-256-CBC',
$key,
OPENSSL_RAW_DATA,
$iv
);
if ($plaintext === false) {
throw new Exception("Erreur de déchiffrement");
}
return $plaintext;
}
/**
* Sauvegarder une clé API
*
* @param int $id_enseignant ID de l'enseignant
* @param string $provider Provider (gemini, mistral, etc.)
* @param string $api_key Clé API en clair
* @param string $model_default Modèle par défaut
* @return bool Succès
*/
public static function saveKey($id_enseignant, $provider, $api_key, $model_default = null) {
self::init();
// Chiffrer la clé
$encrypted = self::encrypt($api_key);
// Upsert (INSERT ... ON DUPLICATE KEY UPDATE)
$query = "INSERT INTO api_keys
(id_enseignant, provider, api_key_encrypted, model_default, is_active, quota_reset_date)
VALUES (?, ?, ?, ?, TRUE, DATE_ADD(CURDATE(), INTERVAL 1 MONTH))
ON DUPLICATE KEY UPDATE
api_key_encrypted = VALUES(api_key_encrypted),
model_default = VALUES(model_default),
is_active = TRUE,
updated_at = CURRENT_TIMESTAMP";
return self::$db->query($query, [
$id_enseignant,
$provider,
$encrypted,
$model_default
]);
}
/**
* Récupérer une clé API déchiffrée
*
* @param int $id_enseignant ID de l'enseignant
* @param string $provider Provider
* @return array|null ['api_key' => '...', 'model_default' => '...']
*/
public static function getKey($id_enseignant, $provider) {
self::init();
$result = self::$db->fetchOne(
"SELECT api_key_encrypted, model_default, is_active
FROM api_keys
WHERE id_enseignant = ? AND provider = ?",
[$id_enseignant, $provider]
);
if (!$result || !$result['is_active']) {
return null;
}
return [
'api_key' => self::decrypt($result['api_key_encrypted']),
'model_default' => $result['model_default']
];
}
/**
* Supprimer une clé API
*
* @param int $id_enseignant ID de l'enseignant
* @param string $provider Provider
* @return bool Succès
*/
public static function deleteKey($id_enseignant, $provider) {
self::init();
return self::$db->query(
"DELETE FROM api_keys WHERE id_enseignant = ? AND provider = ?",
[$id_enseignant, $provider]
);
}
/**
* Lister toutes les clés d'un enseignant
*
* @param int $id_enseignant ID de l'enseignant
* @return array Liste des clés (sans les clés déchiffrées)
*/
public static function listKeys($id_enseignant) {
self::init();
return self::$db->fetchAll(
"SELECT
id,
provider,
model_default,
is_active,
quota_max,
quota_used,
quota_reset_date,
last_used,
created_at
FROM api_keys
WHERE id_enseignant = ?
ORDER BY provider",
[$id_enseignant]
);
}
/**
* Incrémenter le quota utilisé
*
* @param int $id_enseignant ID de l'enseignant
* @param string $provider Provider
* @param int $tokens_used Nombre de tokens utilisés
*/
public static function incrementQuota($id_enseignant, $provider, $tokens_used = 1) {
self::init();
// Reset quota si date dépassée
self::$db->query(
"UPDATE api_keys
SET quota_used = 0, quota_reset_date = DATE_ADD(CURDATE(), INTERVAL 1 MONTH)
WHERE id_enseignant = ? AND provider = ? AND quota_reset_date < CURDATE()",
[$id_enseignant, $provider]
);
// Incrémenter
return self::$db->query(
"UPDATE api_keys
SET quota_used = quota_used + ?, last_used = NOW()
WHERE id_enseignant = ? AND provider = ?",
[$tokens_used, $id_enseignant, $provider]
);
}
/**
* Vérifier si le quota est dépassé
*
* @param int $id_enseignant ID de l'enseignant
* @param string $provider Provider
* @return bool True si quota OK
*/
public static function checkQuota($id_enseignant, $provider) {
self::init();
$result = self::$db->fetchOne(
"SELECT quota_max, quota_used FROM api_keys
WHERE id_enseignant = ? AND provider = ?",
[$id_enseignant, $provider]
);
if (!$result || $result['quota_max'] === null) {
return true; // Pas de limite
}
return $result['quota_used'] < $result['quota_max'];
}
/**
* Tester une connexion API
*
* @param string $provider Provider à tester
* @param string $api_key Clé API
* @param string $model Modèle à tester
* @return array ['success' => bool, 'message' => string, 'latency_ms' => int]
*/
public static function testConnection($provider, $api_key, $model = null) {
$start = microtime(true);
try {
switch ($provider) {
case 'gemini':
$result = self::testGemini($api_key, $model ?? 'gemini-2.0-flash-exp');
break;
case 'mistral':
$result = self::testMistral($api_key, $model ?? 'ministral-3b-latest');
break;
case 'openai':
$result = self::testOpenAI($api_key, $model ?? 'gpt-4o-mini');
break;
case 'ollama':
$result = self::testOllama($model ?? 'ministral-3:3b');
break;
default:
return ['success' => false, 'message' => 'Provider inconnu'];
}
$latency = round((microtime(true) - $start) * 1000);
$result['latency_ms'] = $latency;
return $result;
} catch (Exception $e) {
return [
'success' => false,
'message' => 'Erreur: ' . $e->getMessage(),
'latency_ms' => 0
];
}
}
/**
* Tester connexion Gemini
*/
private static function testGemini($api_key, $model) {
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => json_encode([
'contents' => [['parts' => [['text' => 'Test']]]]
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
return ['success' => true, 'message' => 'Connexion Gemini réussie'];
} elseif ($http_code === 400) {
return ['success' => false, 'message' => 'Clé API invalide'];
} elseif ($http_code === 429) {
return ['success' => false, 'message' => 'Quota dépassé'];
} else {
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
}
}
/**
* Tester connexion Mistral
*/
private static function testMistral($api_key, $model) {
$ch = curl_init('https://api.mistral.ai/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
],
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'messages' => [['role' => 'user', 'content' => 'Test']],
'max_tokens' => 10
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
return ['success' => true, 'message' => 'Connexion Mistral réussie'];
} elseif ($http_code === 401) {
return ['success' => false, 'message' => 'Clé API invalide'];
} else {
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
}
}
/**
* Tester connexion OpenAI
*/
private static function testOpenAI($api_key, $model) {
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $api_key
],
CURLOPT_TIMEOUT => 10,
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'messages' => [['role' => 'user', 'content' => 'Test']],
'max_tokens' => 10
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
return ['success' => true, 'message' => 'Connexion OpenAI réussie'];
} elseif ($http_code === 401) {
return ['success' => false, 'message' => 'Clé API invalide'];
} else {
return ['success' => false, 'message' => "Erreur HTTP $http_code"];
}
}
/**
* Tester connexion Ollama (local)
*/
private static function testOllama($model) {
$ch = curl_init('http://localhost:11434/api/generate');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_TIMEOUT => 5,
CURLOPT_POSTFIELDS => json_encode([
'model' => $model,
'prompt' => 'Test',
'stream' => false
])
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
return ['success' => true, 'message' => 'Connexion Ollama réussie'];
} else {
return ['success' => false, 'message' => 'Ollama non disponible'];
}
}
}

155
deploy_prod.sh Executable file
View File

@ -0,0 +1,155 @@
#!/usr/bin/env bash
set -euo pipefail
# =========================
# Deploy PROD webval (Jetson)
# Repo -> /var/www/mathematiques
# Backup + exclusions + rollback
# =========================
APP_NAME="webval"
SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DST_DIR="/var/www/mathematiques"
# Dossier backups (hors web)
BACKUP_ROOT="/var/backups/${APP_NAME}"
TS="$(date +%Y%m%d_%H%M%S)"
BACKUP_DIR="${BACKUP_ROOT}/prev_${TS}"
# URL de check (adapte si besoin)
HEALTH_URL="http://127.0.0.1/"
HEALTH_TIMEOUT=10
# Exclusions: runtime + config sensible + git
RSYNC_EXCLUDES=(
".git/"
"evaluations/"
"evaluations_transit/"
"uploads/"
"logs/"
"temp/"
"backup/"
"backups/"
"config/database.php"
"config/secrets.php"
"config/db_credentials.txt"
)
# --- helpers ---
die() { echo "ERREUR: $*" >&2; exit 1; }
print_excludes() {
for e in "${RSYNC_EXCLUDES[@]}"; do
echo " - $e"
done
}
rsync_exclude_args() {
for e in "${RSYNC_EXCLUDES[@]}"; do
printf -- "--exclude=%q " "$e"
done
}
need_cmd() {
command -v "$1" >/dev/null 2>&1 || die "Commande manquante: $1"
}
healthcheck() {
# Healthcheck simple: HTTP 200/301/302 attendu sur la home
# (Si ton app a une URL spécifique de health, mets-la dans HEALTH_URL)
if curl -fsS -m "${HEALTH_TIMEOUT}" -o /dev/null -I "${HEALTH_URL}"; then
return 0
fi
return 1
}
rollback() {
echo
echo "=== ROLLBACK ==="
echo "Restauration depuis: ${BACKUP_DIR}"
if [[ ! -d "${BACKUP_DIR}" ]]; then
die "Backup introuvable, rollback impossible: ${BACKUP_DIR}"
fi
sudo rsync -a --delete "${BACKUP_DIR}/" "${DST_DIR}/"
sudo systemctl reload php8.1-fpm >/dev/null 2>&1 || true
sudo systemctl reload nginx >/dev/null 2>&1 || true
echo "Rollback terminé."
}
# --- prérequis ---
need_cmd rsync
need_cmd curl
need_cmd date
echo "=== Deploy PROD (${APP_NAME}) ==="
echo "Source: ${SRC_DIR}"
echo "Dest : ${DST_DIR}"
echo "Backup: ${BACKUP_DIR}"
echo
echo "Exclusions:"
print_excludes
echo
[[ -d "${SRC_DIR}/.git" ]] || die "Pas de .git dans ${SRC_DIR} (pas un repo ?)."
[[ -d "${DST_DIR}" ]] || die "Destination inexistante: ${DST_DIR}"
# Si tu veux empêcher un deploy avec un working tree sale:
if ! git -C "${SRC_DIR}" diff --quiet || ! git -C "${SRC_DIR}" diff --cached --quiet; then
echo "AVERTISSEMENT: ton repo a des modifications non commit."
echo "Tu peux quand même déployer, mais c'est risqué."
read -r -p "Continuer malgré tout ? (oui/non) " ans_dirty
[[ "${ans_dirty}" == "oui" ]] || exit 0
fi
# --- aperçu ---
echo "--- Aperçu (dry-run) ---"
# shellcheck disable=SC2046
sudo rsync -a --delete --dry-run \
$(rsync_exclude_args) \
"${SRC_DIR}/" "${DST_DIR}/" | sed -n '1,200p'
echo "(aperçu tronqué à 200 lignes)"
echo
read -r -p "Lancer le backup + déploiement maintenant ? (oui/non) " ans
[[ "${ans}" == "oui" ]] || { echo "Annulé."; exit 0; }
# --- backup ---
echo
echo "--- Backup PROD -> ${BACKUP_DIR} ---"
sudo mkdir -p "${BACKUP_ROOT}"
sudo rsync -a --delete "${DST_DIR}/" "${BACKUP_DIR}/"
# --- deploy ---
echo
echo "--- Déploiement ---"
# shellcheck disable=SC2046
sudo rsync -a --delete \
$(rsync_exclude_args) \
"${SRC_DIR}/" "${DST_DIR}/"
# --- reload ---
echo
echo "--- Reload services ---"
sudo systemctl reload php8.1-fpm >/dev/null 2>&1 || true
sudo systemctl reload nginx >/dev/null 2>&1 || true
# --- healthcheck ---
echo
echo "--- Healthcheck: ${HEALTH_URL} ---"
if healthcheck; then
echo "OK: deploy réussi."
echo "Backup conservé: ${BACKUP_DIR}"
exit 0
fi
echo "ECHEC: healthcheck KO. On rollback."
rollback
echo
echo "Après rollback, je te conseille de regarder :"
echo " - sudo tail -n 80 /var/log/nginx/error.log"
echo " - sudo journalctl -u php8.1-fpm -n 80 --no-pager"
exit 2

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* Dashboard élève (classe fixe + libre) * Dashboard élève - VERSION FINALE CORRECTE
* Fichier : eleve/dashboard.php * Basé sur la structure BDD réelle analysée le 02/01/2026
*/ */
require_once __DIR__ . '/../config/config.php'; require_once __DIR__ . '/../config/config.php';
@ -27,12 +27,12 @@ $db = Database::getInstance();
$isEleveLibre = ($user['id_type'] == 3); $isEleveLibre = ($user['id_type'] == 3);
$isEleveClasse = ($user['id_type'] == 2); $isEleveClasse = ($user['id_type'] == 2);
// Récupérer les évaluations disponibles // Récupérer les évaluations disponibles (non encore passées)
if ($isEleveLibre) { if ($isEleveLibre) {
// Élève libre : évaluations de type soutien uniquement
$queryEvals = "SELECT DISTINCT e.*, $queryEvals = "SELECT DISTINCT e.*,
COALESCE(t.statut, 'non_commence') as statut_tentative, COALESCE(t.statut, 'non_commence') as statut_tentative,
t.note as note_obtenue, t.note as note_obtenue,
t.note_sur as note_sur_obtenue,
t.date_debut as date_tentative t.date_debut as date_tentative
FROM evaluations e FROM evaluations e
INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation
@ -48,13 +48,13 @@ if ($isEleveLibre) {
$evaluations = $db->fetchAll($queryEvals, [$user['id_utilisateur']]); $evaluations = $db->fetchAll($queryEvals, [$user['id_utilisateur']]);
} else { } else {
// Élève classe fixe : évaluations de sa classe
if ($user['id_classe']) { if ($user['id_classe']) {
$queryEvals = "SELECT DISTINCT e.*, $queryEvals = "SELECT DISTINCT e.*,
ae.date_debut as debut_acces, ae.date_debut as debut_acces,
ae.date_fin as fin_acces, ae.date_fin as fin_acces,
COALESCE(t.statut, 'non_commence') as statut_tentative, COALESCE(t.statut, 'non_commence') as statut_tentative,
t.note as note_obtenue, t.note as note_obtenue,
t.note_sur as note_sur_obtenue,
t.date_debut as date_tentative t.date_debut as date_tentative
FROM evaluations e FROM evaluations e
INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation INNER JOIN acces_evaluations ae ON e.id_evaluation = ae.id_evaluation
@ -72,17 +72,63 @@ if ($isEleveLibre) {
} }
} }
// Récupérer les statistiques de l'élève // Récupérer les 4 dernières évaluations terminées
$query4Dernieres = "SELECT
e.id_evaluation,
e.titre,
e.description,
te.note,
te.note_sur,
te.pourcentage,
te.temps_passe,
te.date_fin,
(SELECT COUNT(*) FROM questions WHERE id_evaluation = e.id_evaluation) as nb_questions
FROM tentatives_eleves te
INNER JOIN evaluations e ON te.id_evaluation = e.id_evaluation
WHERE te.id_eleve = ?
AND te.statut = 'terminee'
ORDER BY te.date_fin DESC
LIMIT 4";
$dernieresEvals = $db->fetchAll($query4Dernieres, [$user['id_utilisateur']]);
// Calculer la moyenne des 4 dernières (arrondie au demi-point supérieur)
$moyenne4Dernieres = 0;
if (!empty($dernieresEvals)) {
$somme_notes_sur_20 = 0;
foreach ($dernieresEvals as $eval) {
$note_sur_20 = $eval['note_sur'] > 0 ? ($eval['note'] / $eval['note_sur']) * 20 : 0;
$somme_notes_sur_20 += $note_sur_20;
}
$moyenne_brute = $somme_notes_sur_20 / count($dernieresEvals);
$moyenne4Dernieres = ceil($moyenne_brute * 2) / 2; // Arrondi demi-point sup
}
// Récupérer TOUTES les évaluations terminées pour le graphique
$queryToutesEvals = "SELECT
e.id_evaluation,
e.titre,
e.description,
te.note,
te.note_sur,
te.pourcentage,
te.date_fin
FROM tentatives_eleves te
INNER JOIN evaluations e ON te.id_evaluation = e.id_evaluation
WHERE te.id_eleve = ?
AND te.statut = 'terminee'
ORDER BY te.date_fin ASC";
$toutesEvals = $db->fetchAll($queryToutesEvals, [$user['id_utilisateur']]);
// Récupérer les statistiques générales
$queryStats = "SELECT $queryStats = "SELECT
COUNT(DISTINCT t.id_evaluation) as nb_evaluations_passees, COUNT(DISTINCT t.id_evaluation) as nb_evaluations_passees,
COUNT(CASE WHEN t.statut = 'terminee' THEN 1 END) as nb_evaluations_terminees, COUNT(CASE WHEN t.statut = 'terminee' THEN 1 END) as nb_evaluations_terminees,
AVG( AVG(CASE WHEN t.statut = 'terminee' AND t.note_sur > 0
CASE WHEN t.statut = 'terminee' THEN (t.note / t.note_sur) * 20
THEN CEILING((t.note / e.note_totale * 20) * 2) / 2 ELSE NULL END) as moyenne_generale
ELSE NULL END
) as moyenne_generale
FROM tentatives_eleves t FROM tentatives_eleves t
INNER JOIN evaluations e ON t.id_evaluation = e.id_evaluation
WHERE t.id_eleve = ?"; WHERE t.id_eleve = ?";
$stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
@ -91,6 +137,11 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
'moyenne_generale' => null 'moyenne_generale' => null
]; ];
// Arrondir la moyenne générale au demi-point supérieur
if ($stats['moyenne_generale'] !== null) {
$stats['moyenne_generale'] = ceil($stats['moyenne_generale'] * 2) / 2;
}
?> ?>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="fr"> <html lang="fr">
@ -98,6 +149,7 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard Élève - <?= htmlspecialchars($user['prenom'] . ' ' . $user['nom']) ?></title> <title>Dashboard Élève - <?= htmlspecialchars($user['prenom'] . ' ' . $user['nom']) ?></title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style> <style>
* { * {
margin: 0; margin: 0;
@ -119,7 +171,7 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
} }
.header-content { .header-content {
max-width: 1200px; max-width: 1400px;
margin: 0 auto; margin: 0 auto;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
@ -161,14 +213,14 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
} }
.container { .container {
max-width: 1200px; max-width: 1400px;
margin: 30px auto; margin: 30px auto;
padding: 0 20px; padding: 0 20px;
} }
.stats-grid { .stats-grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 20px; gap: 20px;
margin-bottom: 30px; margin-bottom: 30px;
} }
@ -195,6 +247,130 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
color: #333; color: #333;
} }
.stat-card .sub-value {
font-size: 14px;
color: #999;
margin-top: 5px;
}
/* Historique 4 dernières évaluations */
.historique-section {
background: white;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.section-title {
font-size: 20px;
color: #333;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #f0f0f0;
}
.dernieres-evals-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
}
.eval-card-small {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border-radius: 10px;
padding: 20px;
transition: all 0.3s;
border: 2px solid transparent;
}
.eval-card-small:hover {
border-color: #667eea;
transform: translateY(-3px);
box-shadow: 0 6px 15px rgba(102, 126, 234, 0.2);
}
.eval-card-small h4 {
color: #333;
font-size: 15px;
margin-bottom: 10px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.eval-card-small .description {
font-size: 11px;
color: #666;
margin-bottom: 12px;
height: 32px;
overflow: hidden;
}
.note-display-large {
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 8px;
}
.note-fraction {
font-size: 13px;
color: #666;
font-weight: 600;
}
.note-sur-20 {
font-size: 28px;
font-weight: 700;
color: #667eea;
}
.eval-card-small .date {
font-size: 11px;
color: #999;
text-align: right;
margin-top: 5px;
}
.moyenne-4 {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 10px;
text-align: center;
display: flex;
flex-direction: column;
justify-content: center;
}
.moyenne-4 h3 {
font-size: 14px;
margin-bottom: 10px;
opacity: 0.9;
}
.moyenne-4 .value {
font-size: 42px;
font-weight: 700;
}
/* Graphique progression */
.graph-section {
background: white;
border-radius: 12px;
padding: 25px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
margin-bottom: 30px;
}
.chart-container {
position: relative;
height: 300px;
margin-top: 20px;
}
/* Évaluations disponibles */
.section { .section {
background: white; background: white;
border-radius: 12px; border-radius: 12px;
@ -203,14 +379,6 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
margin-bottom: 30px; margin-bottom: 30px;
} }
.section-title {
font-size: 22px;
color: #333;
margin-bottom: 20px;
padding-bottom: 10px;
border-bottom: 2px solid #f0f0f0;
}
.eval-grid { .eval-grid {
display: grid; display: grid;
gap: 15px; gap: 15px;
@ -347,7 +515,7 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
</div> </div>
<div class="container"> <div class="container">
<!-- STATISTIQUES --> <!-- STATISTIQUES GLOBALES -->
<div class="stats-grid"> <div class="stats-grid">
<div class="stat-card"> <div class="stat-card">
<h3>📚 Évaluations passées</h3> <h3>📚 Évaluations passées</h3>
@ -363,9 +531,14 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
<h3>📊 Moyenne générale</h3> <h3>📊 Moyenne générale</h3>
<div class="value"> <div class="value">
<?= $stats['moyenne_generale'] !== null <?= $stats['moyenne_generale'] !== null
? number_format($stats['moyenne_generale'], 2) . '/20' ? number_format($stats['moyenne_generale'], 1) . '/20'
: '-' ?> : '-' ?>
</div> </div>
<?php if (!empty($toutesEvals) && count($toutesEvals) > 1): ?>
<div class="sub-value">
Sur <?= count($toutesEvals) ?> évaluation<?= count($toutesEvals) > 1 ? 's' : '' ?>
</div>
<?php endif; ?>
</div> </div>
</div> </div>
@ -378,6 +551,75 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
</div> </div>
<?php endif; ?> <?php endif; ?>
<!-- HISTORIQUE 4 DERNIÈRES ÉVALUATIONS -->
<?php if (!empty($dernieresEvals)): ?>
<div class="historique-section">
<h2 class="section-title">📋 Mes 4 dernières évaluations</h2>
<div class="dernieres-evals-grid">
<?php foreach ($dernieresEvals as $eval):
// Convertir la note brute en note sur 20 en utilisant le barème réel
// note_sur = barème total (80, 50, 20, etc.)
$note_sur_20 = $eval['note_sur'] > 0 ? ($eval['note'] / $eval['note_sur']) * 20 : 0;
// Arrondir au demi-point supérieur
$note_arrondie = ceil($note_sur_20 * 2) / 2;
// Le nombre de questions réussies = la note brute elle-même !
$questions_reussies = $eval['note'];
?>
<div class="eval-card-small">
<h4 title="<?= htmlspecialchars($eval['titre']) ?>">
<?= htmlspecialchars($eval['titre']) ?>
</h4>
<div class="description">
<?= htmlspecialchars($eval['description'] ?? '') ?>
</div>
<div class="note-display-large">
<div>
<div class="note-fraction">
<?= number_format($questions_reussies, 1) ?>/<?= number_format($eval['note_sur'], 0) ?> points
</div>
<div class="note-sur-20">
<?= number_format($note_arrondie, 1) ?>/20
</div>
</div>
<div style="text-align: right;">
<div class="note-fraction">
<?= round($eval['pourcentage']) ?>%
</div>
<div style="font-size: 11px; color: #999; margin-top: 3px;">
⏱️ <?= gmdate('i:s', $eval['temps_passe'] ?? 0) ?>
</div>
</div>
</div>
<div class="date">
<?= date('d/m/Y à H:i', strtotime($eval['date_fin'])) ?>
</div>
</div>
<?php endforeach; ?>
<!-- Moyenne des 4 dernières -->
<div class="moyenne-4">
<h3>Moyenne sur ces 4 évaluations</h3>
<div class="value"><?= number_format($moyenne4Dernieres, 1) ?>/20</div>
</div>
</div>
</div>
<?php endif; ?>
<!-- GRAPHIQUE PROGRESSION -->
<?php if (!empty($toutesEvals) && count($toutesEvals) > 1): ?>
<div class="graph-section">
<h2 class="section-title">📈 Ma progression</h2>
<div class="chart-container">
<canvas id="progressionChart"></canvas>
</div>
</div>
<?php endif; ?>
<!-- ÉVALUATIONS DISPONIBLES --> <!-- ÉVALUATIONS DISPONIBLES -->
<div class="section"> <div class="section">
<h2 class="section-title">📝 Évaluations disponibles</h2> <h2 class="section-title">📝 Évaluations disponibles</h2>
@ -399,8 +641,7 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
<p><?= htmlspecialchars($eval['description']) ?></p> <p><?= htmlspecialchars($eval['description']) ?></p>
<?php endif; ?> <?php endif; ?>
<p> <p>
<strong>Chapitre :</strong> <?= htmlspecialchars($eval['chapitre'] ?? 'Non spécifié') ?> <strong>Durée :</strong> <?= $eval['duree_minutes'] ?? 'Libre' ?> min
| <strong>Durée :</strong> <?= $eval['duree_minutes'] ?? 'Libre' ?> min
| <strong>Note :</strong> /<?= $eval['note_totale'] ?? 20 ?> | <strong>Note :</strong> /<?= $eval['note_totale'] ?? 20 ?>
</p> </p>
<?php if (isset($eval['fin_acces'])): ?> <?php if (isset($eval['fin_acces'])): ?>
@ -416,11 +657,24 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
?> ?>
<?php if ($statut === 'terminee'): ?> <?php if ($statut === 'terminee'): ?>
<?php
// Utiliser note_sur si disponible, sinon calculer avec nb questions
if (isset($eval['note_sur_obtenue']) && $eval['note_sur_obtenue'] > 0) {
$note_sur_20 = ($eval['note_obtenue'] / $eval['note_sur_obtenue']) * 20;
} else {
// Fallback : calculer avec nb questions
$queryNbQ = "SELECT COUNT(*) as nb FROM questions WHERE id_evaluation = ?";
$resultNbQ = $db->fetchOne($queryNbQ, [$eval['id_evaluation']]);
$nb_q = $resultNbQ['nb'] ?? 1;
$note_sur_20 = ($eval['note_obtenue'] / $nb_q) * 20;
}
$note_affichee = ceil($note_sur_20 * 2) / 2;
?>
<span class="note-display"> <span class="note-display">
<?= number_format($eval['note_obtenue'], 2) ?>/<?= $eval['note_totale'] ?? 20 ?> <?= number_format($note_affichee, 1) ?>/20
</span> </span>
<span class="status-badge status-termine">✅ Terminé</span> <span class="status-badge status-termine">✅ Terminé</span>
<a href="../resultats.php?id_evaluation=<?= $eval['id_evaluation'] ?>" <a href="../voir_resultat.php?id_evaluation=<?= $eval['id_evaluation'] ?>"
class="btn btn-secondary"> class="btn btn-secondary">
Voir le résultat Voir le résultat
</a> </a>
@ -446,5 +700,158 @@ $stats = $db->fetchOne($queryStats, [$user['id_utilisateur']]) ?? [
<?php endif; ?> <?php endif; ?>
</div> </div>
</div> </div>
<?php if (!empty($toutesEvals) && count($toutesEvals) > 1): ?>
<script>
// Données pour le graphique
const toutesEvaluations = <?= json_encode($toutesEvals) ?>;
// Préparer les labels
const labels = toutesEvaluations.map((e, index) => {
const date = new Date(e.date_fin);
return `Eval ${index + 1}\n${date.getDate()}/${date.getMonth() + 1}`;
});
// Récupérer le nombre de questions pour chaque évaluation
// Utiliser note_sur (barème total) pour calculer la note sur 20
const notes = toutesEvaluations.map(e => {
// note / note_sur * 20
const note_sur_20 = (parseFloat(e.note) / parseFloat(e.note_sur)) * 20;
return Math.ceil(note_sur_20 * 2) / 2; // Arrondir demi-point sup
});
// Calculer la moyenne mobile (sur 3 évaluations)
const moyennesMobiles = notes.map((note, index, arr) => {
if (index < 2) return null;
const sum = arr[index - 2] + arr[index - 1] + arr[index];
const avg = sum / 3;
return Math.ceil(avg * 2) / 2;
});
// Créer le graphique
const ctx = document.getElementById('progressionChart').getContext('2d');
new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: 'Note (/20)',
data: notes,
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
borderWidth: 3,
pointRadius: 6,
pointBackgroundColor: '#667eea',
pointBorderColor: '#fff',
pointBorderWidth: 2,
pointHoverRadius: 8,
tension: 0.3,
fill: true
},
{
label: 'Moyenne mobile (3 évals)',
data: moyennesMobiles,
borderColor: '#28a745',
backgroundColor: 'rgba(40, 167, 69, 0.05)',
borderWidth: 2,
borderDash: [5, 5],
pointRadius: 4,
pointBackgroundColor: '#28a745',
pointBorderColor: '#fff',
pointBorderWidth: 2,
tension: 0.3,
fill: false
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
position: 'top',
labels: {
usePointStyle: true,
padding: 15,
font: {
size: 12,
weight: '600'
}
}
},
tooltip: {
backgroundColor: 'rgba(0, 0, 0, 0.8)',
padding: 12,
titleFont: {
size: 13,
weight: 'bold'
},
bodyFont: {
size: 12
},
callbacks: {
title: function(context) {
const index = context[0].dataIndex;
return toutesEvaluations[index].titre;
},
label: function(context) {
const index = context.dataIndex;
const eval = toutesEvaluations[index];
if (context.datasetIndex === 0) {
return `Note: ${context.parsed.y.toFixed(1)}/20 (${Math.round(eval.pourcentage)}%)`;
} else {
return context.parsed.y ? `Moyenne mobile: ${context.parsed.y.toFixed(1)}/20` : '';
}
},
afterLabel: function(context) {
if (context.datasetIndex === 0) {
const index = context.dataIndex;
const eval = toutesEvaluations[index];
const date = new Date(eval.date_fin);
return `Date: ${date.toLocaleDateString('fr-FR')}`;
}
return '';
}
}
}
},
scales: {
y: {
beginAtZero: true,
max: 20,
ticks: {
stepSize: 2,
callback: function(value) {
return value + '/20';
},
font: {
size: 11
}
},
grid: {
color: 'rgba(0, 0, 0, 0.05)'
}
},
x: {
ticks: {
font: {
size: 10
}
},
grid: {
display: false
}
}
},
interaction: {
intersect: false,
mode: 'index'
}
}
});
</script>
<?php endif; ?>
</body> </body>
</html> </html>

View File

@ -0,0 +1,229 @@
<?php
/**
* API AJAX pour la gestion des clés API du chatbot
* Actions : save, test, delete, get
*/
header('Content-Type: application/json');
require_once '../config/config.php';
require_once '../config/database.php';
require_once '../config/session.php';
require_once '../config/api_key_manager.php';
// Vérifier authentification
if (!SessionManager::isLoggedIn() || !SessionManager::isEnseignant()) {
echo json_encode(['error' => 'Non autorisé']);
exit;
}
$user = SessionManager::getUser();
$action = $_GET['action'] ?? $_POST['action'] ?? null;
try {
switch ($action) {
case 'save':
// Sauvegarder une clé API
$provider = $_POST['provider'] ?? null;
$api_key = $_POST['api_key'] ?? null;
$model_default = $_POST['model_default'] ?? null;
$quota_max = !empty($_POST['quota_max']) ? (int)$_POST['quota_max'] : null;
if (!$provider || !$api_key || !$model_default) {
throw new Exception('Paramètres manquants');
}
// Valider le provider
$valid_providers = ['gemini', 'mistral', 'openai', 'ollama'];
if (!in_array($provider, $valid_providers)) {
throw new Exception('Provider invalide');
}
// Sauvegarder
$result = APIKeyManager::saveKey(
$user['id_utilisateur'],
$provider,
$api_key,
$model_default
);
if (!$result) {
throw new Exception('Erreur lors de la sauvegarde');
}
// Mettre à jour le quota si défini
if ($quota_max !== null) {
$db = Database::getInstance();
$db->query(
"UPDATE api_keys SET quota_max = ? WHERE id_enseignant = ? AND provider = ?",
[$quota_max, $user['id_utilisateur'], $provider]
);
}
echo json_encode([
'success' => true,
'message' => 'Clé API enregistrée avec succès'
]);
break;
case 'test':
// Tester une connexion API
$provider = $_POST['provider'] ?? null;
$api_key = $_POST['api_key'] ?? null;
$model = $_POST['model'] ?? null;
if (!$provider) {
throw new Exception('Provider manquant');
}
// Si pas de clé fournie, récupérer celle enregistrée
if (!$api_key) {
$key_data = APIKeyManager::getKey($user['id_utilisateur'], $provider);
if (!$key_data) {
throw new Exception('Aucune clé enregistrée pour ce provider');
}
$api_key = $key_data['api_key'];
$model = $model ?? $key_data['model_default'];
}
// Tester la connexion
$result = APIKeyManager::testConnection($provider, $api_key, $model);
echo json_encode($result);
break;
case 'delete':
// Supprimer une clé API
$provider = $_POST['provider'] ?? null;
if (!$provider) {
throw new Exception('Provider manquant');
}
$result = APIKeyManager::deleteKey($user['id_utilisateur'], $provider);
if (!$result) {
throw new Exception('Erreur lors de la suppression');
}
echo json_encode([
'success' => true,
'message' => 'Clé API supprimée'
]);
break;
case 'get':
// Récupérer une clé API (pour édition)
$provider = $_GET['provider'] ?? null;
if (!$provider) {
throw new Exception('Provider manquant');
}
$db = Database::getInstance();
$key_data = $db->fetchOne(
"SELECT provider, model_default, quota_max, is_active
FROM api_keys
WHERE id_enseignant = ? AND provider = ?",
[$user['id_utilisateur'], $provider]
);
if (!$key_data) {
throw new Exception('Clé non trouvée');
}
// Ne pas retourner la clé API elle-même
echo json_encode([
'success' => true,
'data' => $key_data
]);
break;
case 'toggle':
// Activer/désactiver une clé
$provider = $_POST['provider'] ?? null;
$active = isset($_POST['active']) ? (bool)$_POST['active'] : null;
if (!$provider || $active === null) {
throw new Exception('Paramètres manquants');
}
$db = Database::getInstance();
$result = $db->query(
"UPDATE api_keys SET is_active = ? WHERE id_enseignant = ? AND provider = ?",
[$active, $user['id_utilisateur'], $provider]
);
echo json_encode([
'success' => true,
'message' => $active ? 'Clé activée' : 'Clé désactivée'
]);
break;
case 'set_default':
// Définir le provider par défaut
$provider = $_POST['provider'] ?? null;
$model = $_POST['model'] ?? null;
if (!$provider || !$model) {
throw new Exception('Paramètres manquants');
}
$db = Database::getInstance();
// Upsert dans chatbot_default_provider
$result = $db->query(
"INSERT INTO chatbot_default_provider (id_enseignant, provider, model_default)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE provider = VALUES(provider), model_default = VALUES(model_default)",
[$user['id_utilisateur'], $provider, $model]
);
if (!$result) {
throw new Exception('Erreur lors de la mise à jour');
}
echo json_encode([
'success' => true,
'message' => 'Provider par défaut mis à jour'
]);
break;
case 'stats':
// Récupérer les statistiques d'utilisation
$db = Database::getInstance();
$stats = $db->fetchAll(
"SELECT
provider,
model_used,
SUM(total_conversations) as conversations,
SUM(total_messages) as messages,
AVG(avg_response_time_ms) as avg_latency,
month
FROM v_chatbot_usage_stats
WHERE id_enseignant = ?
GROUP BY provider, model_used, month
ORDER BY month DESC, conversations DESC
LIMIT 50",
[$user['id_utilisateur']]
);
echo json_encode([
'success' => true,
'stats' => $stats
]);
break;
default:
throw new Exception('Action inconnue');
}
} catch (Exception $e) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => $e->getMessage()
]);
}

View File

@ -0,0 +1,430 @@
<?php
/**
* Configuration des clés API pour le chatbot
* Interface de gestion pour les enseignants
*/
require_once '../config/config.php';
require_once '../config/database.php';
require_once '../config/session.php';
require_once '../config/api_key_manager.php';
// Vérifier authentification et type enseignant
if (!SessionManager::isLoggedIn() || !SessionManager::isEnseignant()) {
header('Location: ../login.php');
exit;
}
$user = SessionManager::getUser();
$db = Database::getInstance();
// Récupérer les clés API de l'enseignant
$api_keys = APIKeyManager::listKeys($user['id_utilisateur']);
// Récupérer le provider par défaut configuré
$default_config = $db->fetchOne(
"SELECT provider, model_default FROM chatbot_default_provider WHERE id_enseignant = ?",
[$user['id_utilisateur']]
);
// Si pas de config, initialiser avec Ollama
if (!$default_config) {
$db->query(
"INSERT INTO chatbot_default_provider (id_enseignant, provider, model_default) VALUES (?, 'ollama', 'ministral-3:3b')",
[$user['id_utilisateur']]
);
$default_config = ['provider' => 'ollama', 'model_default' => 'ministral-3:3b'];
}
$default_provider = $default_config['provider'];
$default_model = $default_config['model_default'];
// Récupérer les modèles disponibles groupés par provider
$models_by_provider = [];
$all_models = $db->fetchAll(
"SELECT * FROM available_models WHERE active = TRUE ORDER BY provider, recommended DESC, display_name"
);
foreach ($all_models as $model) {
$models_by_provider[$model['provider']][] = $model;
}
// Récupérer les statistiques d'utilisation (requête directe)
$stats = $db->fetchOne(
"SELECT
COUNT(DISTINCT cc.id) as total_conversations,
COUNT(cm.id) as total_messages,
cc.provider,
cc.model_used
FROM chat_conversations cc
LEFT JOIN chat_messages cm ON cm.id_conversation = cc.id
WHERE cc.id_enseignant = ?
GROUP BY cc.provider, cc.model_used
ORDER BY total_conversations DESC
LIMIT 1",
[$user['id_utilisateur']]
);
$stats_detail = $db->fetchAll(
"SELECT
cc.provider,
cc.model_used,
COUNT(DISTINCT cc.id) as conversations,
COUNT(cm.id) as messages,
DATE_FORMAT(cc.date_debut, '%Y-%m') as month
FROM chat_conversations cc
LEFT JOIN chat_messages cm ON cm.id_conversation = cc.id
WHERE cc.id_enseignant = ?
GROUP BY cc.provider, cc.model_used, month
ORDER BY month DESC, conversations DESC",
[$user['id_utilisateur']]
);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Configuration API Chatbot - WebVal</title>
<link rel="stylesheet" href="../assets/css/chatbot_settings.css">
</head>
<body>
<div class="container">
<!-- Header -->
<header class="page-header">
<div class="header-content">
<a href="dashboard.php" class="back-link">← Retour au dashboard</a>
<h1>⚙️ Configuration API Chatbot</h1>
<p class="subtitle">Gérez vos clés API et choisissez les modèles pour vos évaluations</p>
</div>
</header>
<!-- Stats overview -->
<?php if ($stats): ?>
<div class="stats-banner">
<div class="stat-card">
<div class="stat-icon">💬</div>
<div class="stat-content">
<div class="stat-value"><?= number_format($stats['total_conversations'] ?? 0) ?></div>
<div class="stat-label">Conversations</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">📨</div>
<div class="stat-content">
<div class="stat-value"><?= number_format($stats['total_messages'] ?? 0) ?></div>
<div class="stat-label">Messages</div>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">🤖</div>
<div class="stat-content">
<div class="stat-value"><?= htmlspecialchars($stats['provider'] ?? 'Aucun') ?></div>
<div class="stat-label">Provider actuel</div>
</div>
</div>
</div>
<?php endif; ?>
<!-- Main content -->
<div class="content-grid">
<!-- Section clés API -->
<section class="api-keys-section">
<div class="section-header">
<h2>🔑 Mes clés API</h2>
<button class="btn-primary" onclick="openAddKeyModal()">
Ajouter une clé
</button>
</div>
<div class="keys-list">
<?php
$providers = ['gemini' => 'Gemini', 'mistral' => 'Mistral', 'openai' => 'OpenAI', 'ollama' => 'Ollama'];
$provider_icons = [
'gemini' => '✨',
'mistral' => '⚡',
'openai' => '🧠',
'ollama' => '🏠'
];
foreach ($providers as $provider_id => $provider_name):
$key_info = null;
foreach ($api_keys as $key) {
if ($key['provider'] === $provider_id) {
$key_info = $key;
break;
}
}
$is_configured = $key_info !== null;
$is_active = $is_configured && $key_info['is_active'];
?>
<div class="key-card <?= $is_active ? 'active' : 'inactive' ?>">
<div class="key-header">
<div class="key-provider">
<span class="provider-icon"><?= $provider_icons[$provider_id] ?></span>
<span class="provider-name"><?= $provider_name ?></span>
</div>
<div class="key-status">
<?php if ($is_active): ?>
<span class="status-badge active">🟢 Active</span>
<?php elseif ($is_configured): ?>
<span class="status-badge inactive">🟠 Désactivée</span>
<?php else: ?>
<span class="status-badge none">⚪ Aucune</span>
<?php endif; ?>
</div>
</div>
<div class="key-body">
<?php if ($provider_id === 'ollama'): ?>
<!-- Card spéciale Ollama (pas de clé API nécessaire) -->
<div class="key-info">
<div class="info-row">
<span class="label">Type :</span>
<span class="value">🏠 Local (Jetson)</span>
</div>
<div class="info-row">
<span class="label">Modèle actuel :</span>
<span class="value"><?= $default_provider === 'ollama' ? htmlspecialchars($default_model) : 'ministral-3:3b' ?></span>
</div>
<div class="info-row">
<span class="label">Coût :</span>
<span class="value">Gratuit ✅</span>
</div>
</div>
<div class="key-actions">
<button class="btn-secondary btn-sm" onclick="testConnection('ollama')">
🔍 Tester
</button>
<button class="btn-secondary btn-sm" onclick="configureOllama()">
⚙️ Changer le modèle
</button>
<?php if ($default_provider !== 'ollama'): ?>
<button class="btn-primary btn-sm" onclick="setAsDefault('ollama', 'ministral-3:3b')">
⭐ Définir par défaut
</button>
<?php endif; ?>
</div>
<?php elseif ($is_configured): ?>
<div class="key-info">
<div class="info-row">
<span class="label">Modèle par défaut :</span>
<span class="value"><?= htmlspecialchars($key_info['model_default'] ?? '-') ?></span>
</div>
<?php if ($key_info['quota_max']): ?>
<div class="info-row">
<span class="label">Quota :</span>
<span class="value">
<?= number_format($key_info['quota_used']) ?> / <?= number_format($key_info['quota_max']) ?>
<span class="quota-bar">
<span class="quota-fill" style="width: <?= min(100, ($key_info['quota_used'] / $key_info['quota_max']) * 100) ?>%"></span>
</span>
</span>
</div>
<?php endif; ?>
<div class="info-row">
<span class="label">Dernière utilisation :</span>
<span class="value">
<?= $key_info['last_used'] ? date('d/m/Y H:i', strtotime($key_info['last_used'])) : 'Jamais' ?>
</span>
</div>
</div>
<div class="key-actions">
<button class="btn-secondary btn-sm" onclick="testConnection('<?= $provider_id ?>')">
🔍 Tester
</button>
<button class="btn-secondary btn-sm" onclick="editKey('<?= $provider_id ?>')">
✏️ Modifier
</button>
<?php if ($default_provider !== $provider_id): ?>
<button class="btn-primary btn-sm" onclick="setAsDefault('<?= $provider_id ?>', '<?= htmlspecialchars($key_info['model_default']) ?>')">
⭐ Définir par défaut
</button>
<?php endif; ?>
<button class="btn-danger btn-sm" onclick="deleteKey('<?= $provider_id ?>')">
🗑️ Supprimer
</button>
</div>
<?php else: ?>
<div class="key-empty">
<p>Aucune clé configurée pour <?= $provider_name ?></p>
<button class="btn-primary btn-sm" onclick="openAddKeyModal('<?= $provider_id ?>')">
Ajouter
</button>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
</section>
<!-- Section modèles disponibles -->
<aside class="models-sidebar">
<div class="section-header">
<h3>📚 Modèles disponibles</h3>
</div>
<div class="models-list">
<?php foreach ($models_by_provider as $provider => $models): ?>
<div class="provider-group">
<h4><?= $provider_icons[$provider] ?? '🤖' ?> <?= ucfirst($provider) ?></h4>
<?php foreach ($models as $model): ?>
<div class="model-item <?= $model['recommended'] ? 'recommended' : '' ?>">
<div class="model-name">
<?= htmlspecialchars($model['display_name']) ?>
<?php if ($model['recommended']): ?>
<span class="badge-recommended">⭐</span>
<?php endif; ?>
</div>
<div class="model-meta">
<?php if ($model['is_free']): ?>
<span class="badge-free">🆓 Gratuit</span>
<?php else: ?>
<span class="badge-paid">💰 <?= number_format($model['cost_per_1m_tokens'], 2) ?>€/1M</span>
<?php endif; ?>
<span class="badge-speed">
<?php
$speed_icons = ['⏱️', '🐌', '🚶', '🏃', '🚀', '⚡'];
echo $speed_icons[$model['speed_rating']] ?? '🚶';
?>
</span>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</div>
<div class="help-box">
<h4>💡 Recommandations</h4>
<ul>
<li><strong>Gemini 2.0 Flash</strong> : Gratuit, rapide, excellent pour les évaluations</li>
<li><strong>Ministral 8B</strong> : Bon rapport qualité/prix</li>
<li><strong>Ollama local</strong> : Gratuit mais 1 élève à la fois</li>
</ul>
</div>
</aside>
</div>
<!-- Section statistiques détaillées -->
<?php if (!empty($stats_detail)): ?>
<section class="stats-section">
<div class="section-header">
<h2>📊 Historique d'utilisation</h2>
</div>
<div class="stats-table-wrapper">
<table class="stats-table">
<thead>
<tr>
<th>Mois</th>
<th>Provider</th>
<th>Modèle</th>
<th>Conversations</th>
<th>Messages</th>
</tr>
</thead>
<tbody>
<?php foreach ($stats_detail as $stat): ?>
<tr>
<td><?= date('M Y', strtotime($stat['month'] . '-01')) ?></td>
<td>
<span class="provider-badge">
<?= $provider_icons[$stat['provider']] ?? '🤖' ?>
<?= ucfirst($stat['provider']) ?>
</span>
</td>
<td><?= htmlspecialchars($stat['model_used']) ?></td>
<td><?= number_format($stat['conversations']) ?></td>
<td><?= number_format($stat['messages']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</section>
<?php endif; ?>
</div>
<!-- Modal ajout/modification clé API -->
<div id="keyModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2 id="modalTitle">Ajouter une clé API</h2>
<button class="modal-close" onclick="closeKeyModal()">×</button>
</div>
<form id="keyForm">
<input type="hidden" id="keyAction" value="add">
<div class="form-group">
<label for="provider">Provider *</label>
<select id="provider" name="provider" required onchange="updateModelsList()">
<option value="">-- Choisir --</option>
<option value="gemini">✨ Gemini (Google)</option>
<option value="mistral">⚡ Mistral</option>
<option value="openai">🧠 OpenAI</option>
</select>
</div>
<div class="form-group">
<label for="api_key">Clé API *</label>
<div class="input-with-button">
<input type="password" id="api_key" name="api_key" required
placeholder="AIza... ou sk-... ou votre clé">
<button type="button" class="btn-toggle-visibility" onclick="toggleKeyVisibility()">
👁️
</button>
</div>
<small class="help-text" id="keyHelp"></small>
</div>
<div class="form-group">
<label for="model_default">Modèle par défaut *</label>
<select id="model_default" name="model_default" required>
<option value="">-- Sélectionner un provider d'abord --</option>
</select>
</div>
<div class="form-group">
<label>
<input type="checkbox" id="set_quota" onchange="toggleQuotaInput()">
Limiter le quota mensuel
</label>
</div>
<div class="form-group" id="quotaGroup" style="display: none;">
<label for="quota_max">Limite mensuelle (requêtes)</label>
<input type="number" id="quota_max" name="quota_max" min="1" placeholder="ex: 1000">
</div>
<div class="form-actions">
<button type="button" class="btn-secondary" onclick="closeKeyModal()">
Annuler
</button>
<button type="button" class="btn-test" onclick="testKeyBeforeSave()">
🔍 Tester la connexion
</button>
<button type="submit" class="btn-primary">
💾 Enregistrer
</button>
</div>
<div id="testResult" class="test-result" style="display: none;"></div>
</form>
</div>
</div>
<!-- Toast notifications -->
<div id="toast-container"></div>
<script>
const models = <?= json_encode($models_by_provider) ?>;
const userId = <?= $user['id_utilisateur'] ?>;
</script>
<script src="../assets/js/chatbot_settings.js"></script>
</body>
</html>

View File

@ -472,6 +472,9 @@ try {
<a href="statistiques/index.php" class="btn btn-secondary"> <a href="statistiques/index.php" class="btn btn-secondary">
📊 Statistiques détaillées 📊 Statistiques détaillées
</a> </a>
<a href="chatbot_api_settings.php" class="btn btn-secondary">
🤖 Configuration IA Chatbot
</a>
</div> </div>
</div> </div>
@ -502,13 +505,12 @@ try {
<a href="../resultat_evaluation.php?id=<?= $eval['id_evaluation'] ?>" class="btn btn-info btn-sm"> <a href="../resultat_evaluation.php?id=<?= $eval['id_evaluation'] ?>" class="btn btn-info btn-sm">
📊 Résultats 📊 Résultats
</a> </a>
<a href="monitoring.php?id_evaluation=<?= $eval['id_evaluation'] ?>"
class="btn btn-primary btn-sm"
title="Monitoring temps réel">
📊 Monitoring
</a>
<a href="../passer_evaluation.php?id_evaluation=<?= $eval['id_evaluation'] ?>&apercu=1" target="_blank" class="btn btn-secondary btn-sm"> <a href="../passer_evaluation.php?id_evaluation=<?= $eval['id_evaluation'] ?>&apercu=1" target="_blank" class="btn btn-secondary btn-sm">
<a href="monitoring.php?id_evaluation=<?= $eval['id_evaluation'] ?>"
class="btn-action"
style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;"
title="Monitoring temps réel">
📊 Monitoring
</a>
👁️ Aperçu 👁️ Aperçu
</a> </a>
<a href="export.php?id_evaluation=<?= $eval['id_evaluation'] ?>&format=csv" <a href="export.php?id_evaluation=<?= $eval['id_evaluation'] ?>&format=csv"

View File

@ -1,7 +1,7 @@
<?php <?php
/** /**
* MATRICE MONITORING TEMPS RÉEL - ENSEIGNANT * MATRICE MONITORING TEMPS RÉEL - VERSION AMÉLIORÉE
* Supervision élèves pendant passage évaluation * Affichage matriciel des questions pour éviter débordement horizontal
*/ */
require_once '../config/config.php'; require_once '../config/config.php';
@ -42,6 +42,10 @@ try {
$questions = $stmt->fetchAll(PDO::FETCH_ASSOC); $questions = $stmt->fetchAll(PDO::FETCH_ASSOC);
$nb_questions = count($questions); $nb_questions = count($questions);
// Calculer dimensions matrice optimales (proche du carré)
$cols = ceil(sqrt($nb_questions));
$rows = ceil($nb_questions / $cols);
} catch (Exception $e) { } catch (Exception $e) {
die('Erreur: ' . $e->getMessage()); die('Erreur: ' . $e->getMessage());
} }
@ -63,20 +67,20 @@ try {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh; min-height: 100vh;
padding: 20px; padding: 10px;
} }
.container { .container {
max-width: 1400px; max-width: 1600px;
margin: 0 auto; margin: 0 auto;
} }
.header { .header {
background: white; background: white;
padding: 20px 30px; padding: 12px 20px;
border-radius: 10px; border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1); box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 20px; margin-bottom: 12px;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
@ -84,23 +88,23 @@ try {
.header h1 { .header h1 {
color: #333; color: #333;
font-size: 24px; font-size: 18px;
display: flex;
align-items: center;
gap: 10px;
}
.refresh-indicator {
padding: 8px 16px;
background: #f0f0f0;
border-radius: 5px;
font-size: 14px;
color: #666;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
} }
.refresh-indicator {
padding: 5px 10px;
background: #f0f0f0;
border-radius: 4px;
font-size: 10px;
color: #666;
display: flex;
align-items: center;
gap: 5px;
}
.refresh-indicator.active { .refresh-indicator.active {
background: #d4edda; background: #d4edda;
color: #155724; color: #155724;
@ -108,13 +112,13 @@ try {
.stats-bar { .stats-bar {
background: white; background: white;
padding: 15px 30px; padding: 10px 20px;
border-radius: 10px; border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1); box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-bottom: 20px; margin-bottom: 12px;
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
gap: 20px; gap: 12px;
} }
.stat-item { .stat-item {
@ -122,90 +126,88 @@ try {
} }
.stat-value { .stat-value {
font-size: 32px; font-size: 22px;
font-weight: bold; font-weight: bold;
color: #667eea; color: #667eea;
} }
.stat-label { .stat-label {
font-size: 14px; font-size: 10px;
color: #666; color: #666;
margin-top: 5px; margin-top: 2px;
} }
.monitoring-table { /* Cards élèves - VERSION COMPACTE */
.eleves-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 12px;
}
.eleve-card {
background: white; background: white;
border-radius: 10px; border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1); box-shadow: 0 2px 4px rgba(0,0,0,0.1);
overflow: hidden; padding: 12px;
transition: transform 0.2s, box-shadow 0.2s;
} }
table { .eleve-card:hover {
width: 100%; transform: translateY(-3px);
border-collapse: collapse; box-shadow: 0 4px 8px rgba(0,0,0,0.15);
} }
thead { .eleve-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); display: flex;
color: white; justify-content: space-between;
align-items: center;
margin-bottom: 8px;
padding-bottom: 8px;
border-bottom: 1px solid #f0f0f0;
} }
thead th { .eleve-info {
padding: 15px 10px; flex: 1;
text-align: left; min-width: 0; /* Pour ellipsis */
}
.eleve-name {
font-size: 13px;
font-weight: 600;
color: #333;
margin-bottom: 2px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.eleve-classe {
font-size: 10px;
color: #666;
}
.status-badge {
padding: 3px 8px;
border-radius: 12px;
font-size: 9px;
font-weight: 600; font-weight: 600;
font-size: 14px;
white-space: nowrap; white-space: nowrap;
} }
thead th.question-col { .status-en-ligne { background: #d4edda; color: #155724; }
text-align: center; .status-en-cours { background: #fff3cd; color: #856404; }
min-width: 40px; .status-inactif { background: #fff3cd; color: #856404; }
} .status-hors-ligne { background: #f8d7da; color: #721c24; }
.status-termine { background: #e2e3e5; color: #383d41; }
tbody tr { .progress-section {
border-bottom: 1px solid #f0f0f0; margin-bottom: 8px;
transition: background 0.2s;
}
tbody tr:hover {
background: #f8f9fa;
}
tbody td {
padding: 12px 10px;
font-size: 14px;
}
.status-indicator {
width: 12px;
height: 12px;
border-radius: 50%;
display: inline-block;
margin-right: 8px;
}
.status-en-ligne { background: #28a745; }
.status-en-cours { background: #ffc107; }
.status-inactif { background: #fd7e14; }
.status-hors-ligne { background: #dc3545; }
.status-termine { background: #6c757d; }
.question-cell {
text-align: center;
font-size: 18px;
cursor: pointer;
transition: transform 0.2s;
}
.question-cell:hover {
transform: scale(1.2);
} }
.progress-bar-container { .progress-bar-container {
background: #e9ecef; background: #e9ecef;
border-radius: 10px; border-radius: 6px;
height: 20px; height: 16px;
overflow: hidden; overflow: hidden;
position: relative; position: relative;
} }
@ -213,73 +215,117 @@ try {
.progress-bar { .progress-bar {
height: 100%; height: 100%;
background: linear-gradient(90deg, #28a745 0%, #20c997 100%); background: linear-gradient(90deg, #28a745 0%, #20c997 100%);
transition: width 0.3s ease; transition: width 0.5s ease;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
color: white; color: white;
font-size: 11px; font-size: 9px;
font-weight: bold; font-weight: bold;
} }
.progress-text { .progress-text {
font-size: 12px; font-size: 9px;
color: #666; color: #666;
margin-top: 3px; margin-top: 3px;
} text-align: center;
.eleve-name {
font-weight: 600;
color: #333;
}
.eleve-classe {
font-size: 12px;
color: #666;
display: block;
} }
.time-info { .time-info {
font-size: 12px; display: flex;
justify-content: space-between;
font-size: 9px;
color: #666;
margin-bottom: 8px;
gap: 4px;
}
.time-info span {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/* Matrice questions - VERSION ULTRA COMPACTE */
.questions-matrix {
display: grid;
grid-template-columns: repeat(<?= $cols ?>, 1fr);
gap: 2px;
margin-top: 6px;
}
.question-cell {
aspect-ratio: 1;
display: flex;
align-items: center;
justify-content: center;
font-size: 10px;
border-radius: 2px;
cursor: pointer;
transition: transform 0.15s, box-shadow 0.15s;
background: #f8f9fa;
position: relative;
min-height: 18px;
}
.question-cell:hover {
transform: scale(1.3);
box-shadow: 0 2px 6px rgba(0,0,0,0.25);
z-index: 10;
}
.question-cell.repondu {
background: #cce5ff;
}
.question-cell.correct {
background: #d4edda;
}
.question-cell.incorrect {
background: #f8d7da;
}
.question-number {
position: absolute;
top: 1px;
left: 2px;
font-size: 6px;
font-weight: 600;
color: #666;
line-height: 1;
}
.matrix-legend {
display: flex;
justify-content: center;
gap: 15px;
margin-top: 10px;
font-size: 11px;
color: #666; color: #666;
} }
.legende { .matrix-legend-item {
background: white;
padding: 15px 30px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin-top: 20px;
display: flex;
gap: 30px;
flex-wrap: wrap;
align-items: center;
}
.legende-title {
font-weight: 600;
color: #333;
}
.legende-item {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 5px;
font-size: 14px;
} }
.btn-retour { .btn-retour {
background: #6c757d; background: white;
color: white; color: #667eea;
padding: 10px 20px; border: 2px solid #667eea;
border-radius: 5px; padding: 6px 12px;
border-radius: 6px;
text-decoration: none; text-decoration: none;
font-size: 14px; font-weight: 600;
transition: background 0.2s; font-size: 11px;
transition: all 0.3s;
} }
.btn-retour:hover { .btn-retour:hover {
background: #5a6268; background: #667eea;
color: white;
} }
@keyframes spin { @keyframes spin {
@ -292,9 +338,51 @@ try {
.no-data { .no-data {
text-align: center; text-align: center;
padding: 40px; padding: 60px 20px;
color: #666; color: #666;
font-size: 16px; font-size: 16px;
background: white;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
/* Légende globale */
.legende {
background: white;
padding: 10px 15px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
margin-top: 12px;
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: center;
font-size: 10px;
}
.legende-title {
font-weight: 600;
color: #333;
font-size: 11px;
}
.legende-item {
display: flex;
align-items: center;
gap: 5px;
}
.tooltip {
position: absolute;
background: rgba(0,0,0,0.9);
color: white;
padding: 8px 12px;
border-radius: 6px;
font-size: 12px;
white-space: nowrap;
pointer-events: none;
z-index: 1000;
display: none;
} }
</style> </style>
</head> </head>
@ -303,10 +391,13 @@ try {
<!-- Header --> <!-- Header -->
<div class="header"> <div class="header">
<h1> <h1>
📊 Monitoring Temps Réel 📊 Monitoring
<span style="font-size: 18px; font-weight: normal; color: #666;"> <span style="font-size: 14px; font-weight: normal; color: #666;">
- <?= htmlspecialchars($evaluation['titre']) ?> - <?= htmlspecialchars($evaluation['titre']) ?>
</span> </span>
<span style="font-size: 11px; font-weight: normal; color: #999;">
(<?= $nb_questions ?>Q - <?= $rows ?>×<?= $cols ?>)
</span>
</h1> </h1>
<div style="display: flex; gap: 15px; align-items: center;"> <div style="display: flex; gap: 15px; align-items: center;">
<div class="refresh-indicator" id="refreshIndicator"> <div class="refresh-indicator" id="refreshIndicator">
@ -341,68 +432,51 @@ try {
</div> </div>
</div> </div>
<!-- Tableau monitoring --> <!-- Grille élèves -->
<div class="monitoring-table"> <div class="eleves-grid" id="elevesGrid">
<table> <div class="no-data">
<thead> 🔄 Chargement des données...
<tr> </div>
<th style="width: 40px;">Statut</th>
<th style="width: 200px;">Élève</th>
<th style="width: 200px;">Progression</th>
<th style="width: 120px;">Temps écoulé</th>
<th style="width: 120px;">Dernière activité</th>
<?php foreach ($questions as $q): ?>
<th class="question-col" title="<?= htmlspecialchars($q['enonce']) ?>">
Q<?= $q['ordre'] ?>
</th>
<?php endforeach; ?>
</tr>
</thead>
<tbody id="monitoringBody">
<tr>
<td colspan="<?= 5 + $nb_questions ?>" class="no-data">
🔄 Chargement des données...
</td>
</tr>
</tbody>
</table>
</div> </div>
<!-- Légende --> <!-- Légende -->
<div class="legende"> <div class="legende">
<div class="legende-title">Légende :</div> <div class="legende-title">Légende :</div>
<div class="legende-item"> <div class="legende-item">
<span class="status-indicator status-en-ligne"></span> <span style="display: inline-block; width: 14px; height: 14px; background: #f8f9fa; border-radius: 2px;"></span>
<span>En ligne (&lt;1 min)</span> <span>Non répondu</span>
</div> </div>
<div class="legende-item"> <div class="legende-item">
<span class="status-indicator status-en-cours"></span> <span style="display: inline-block; width: 14px; height: 14px; background: #cce5ff; border-radius: 2px;"></span>
<span>En cours (&lt;3 min)</span> <span>✅ Répondu</span>
</div> </div>
<div class="legende-item"> <div class="legende-item">
<span class="status-indicator status-inactif"></span> <span style="display: inline-block; width: 14px; height: 14px; background: #d4edda; border-radius: 2px;"></span>
<span>Inactif (3-5 min)</span> <span>✔️ Correct</span>
</div> </div>
<div class="legende-item"> <div class="legende-item">
<span class="status-indicator status-hors-ligne"></span> <span style="display: inline-block; width: 14px; height: 14px; background: #f8d7da; border-radius: 2px;"></span>
<span>Hors ligne (&gt;5 min)</span> <span>❌ Incorrect</span>
</div>
<div class="legende-item" style="margin-left: 15px;">
<span>🟢 En ligne (&lt;1min)</span>
</div> </div>
<div class="legende-item"> <div class="legende-item">
<span class="status-indicator status-termine"></span> <span>🟡 En cours (&lt;3min)</span>
<span>Terminé</span>
</div> </div>
<div class="legende-item" style="margin-left: 30px;"> <div class="legende-item">
<span>⬜ Vide</span> <span>🔴 Inactif (&gt;3min)</span>
<span style="margin-left: 15px;">✅ Répondu</span>
<span style="margin-left: 15px;">✔️ Correct</span>
<span style="margin-left: 15px;">❌ Incorrect</span>
</div> </div>
</div> </div>
</div> </div>
<!-- Tooltip -->
<div class="tooltip" id="tooltip"></div>
<script> <script>
const ID_EVALUATION = <?= $id_evaluation ?>; const ID_EVALUATION = <?= $id_evaluation ?>;
const NB_QUESTIONS = <?= $nb_questions ?>; const NB_QUESTIONS = <?= $nb_questions ?>;
const MATRIX_COLS = <?= $cols ?>;
let refreshInterval; let refreshInterval;
// Charger données initiales // Charger données initiales
@ -426,7 +500,7 @@ try {
.then(data => { .then(data => {
if (data.success) { if (data.success) {
updateStats(data.stats); updateStats(data.stats);
updateTable(data.tentatives); updateElevesGrid(data.tentatives);
// Animation succès // Animation succès
refreshIcon.textContent = '✅'; refreshIcon.textContent = '✅';
@ -460,50 +534,111 @@ try {
document.getElementById('statTermines').textContent = stats.termine; document.getElementById('statTermines').textContent = stats.termine;
} }
function updateTable(tentatives) { function updateElevesGrid(tentatives) {
const tbody = document.getElementById('monitoringBody'); const grid = document.getElementById('elevesGrid');
if (tentatives.length === 0) { if (tentatives.length === 0) {
tbody.innerHTML = ` grid.innerHTML = `
<tr> <div class="no-data">
<td colspan="${5 + NB_QUESTIONS}" class="no-data"> 📭 Aucun élève n'a encore commencé cette évaluation
📭 Aucun élève n'a encore commencé cette évaluation </div>
</td>
</tr>
`; `;
return; return;
} }
tbody.innerHTML = tentatives.map(t => ` grid.innerHTML = tentatives.map(t => createEleveCard(t)).join('');
<tr>
<td> // Ajouter tooltips sur cellules questions
<span class="status-indicator status-${t.statut_connexion}"></span> addQuestionTooltips();
</td> }
<td>
<div class="eleve-name">${escapeHtml(t.nom)} ${escapeHtml(t.prenom)}</div> function createEleveCard(tentative) {
<span class="eleve-classe">${escapeHtml(t.classe || 'Libre')}</span> const statusLabels = {
</td> 'en-ligne': '🟢 En ligne',
<td> 'en-cours': '🟡 En cours',
'inactif': '🟠 Inactif',
'hors-ligne': '🔴 Hors ligne',
'termine': '⚫ Terminé'
};
return `
<div class="eleve-card">
<!-- Header -->
<div class="eleve-header">
<div class="eleve-info">
<div class="eleve-name">${escapeHtml(tentative.nom)} ${escapeHtml(tentative.prenom)}</div>
<div class="eleve-classe">${escapeHtml(tentative.classe || 'Libre')}</div>
</div>
<div class="status-badge status-${tentative.statut_connexion}">
${statusLabels[tentative.statut_connexion] || tentative.statut_connexion}
</div>
</div>
<!-- Progression -->
<div class="progress-section">
<div class="progress-bar-container"> <div class="progress-bar-container">
<div class="progress-bar" style="width: ${t.pourcentage_progression}%"> <div class="progress-bar" style="width: ${tentative.pourcentage_progression}%">
${t.pourcentage_progression}% ${tentative.pourcentage_progression}%
</div> </div>
</div> </div>
<div class="progress-text">${t.nb_reponses}/${NB_QUESTIONS} questions</div> <div class="progress-text">${tentative.nb_reponses}/${NB_QUESTIONS} questions répondues</div>
</td> </div>
<td class="time-info">
⏱️ ${t.temps_ecoule} <!-- Temps -->
</td> <div class="time-info">
<td class="time-info"> <span>⏱️ Temps écoulé: ${tentative.temps_ecoule}</span>
${t.derniere_activite} <span>🕐 Activité: ${tentative.derniere_activite}</span>
</td> </div>
${t.reponses_details.map(r => `
<td class="question-cell" title="${r.tooltip}"> <!-- Matrice questions -->
${r.icone} <div class="questions-matrix">
</td> ${createQuestionsMatrix(tentative.reponses_details)}
`).join('')} </div>
</tr> </div>
`).join(''); `;
}
function createQuestionsMatrix(reponses) {
let html = '';
for (let i = 0; i < NB_QUESTIONS; i++) {
const reponse = reponses[i] || {};
const classe = reponse.classe || '';
const icone = reponse.icone || '⬜';
const tooltip = reponse.tooltip || `Question ${i + 1}`;
html += `
<div class="question-cell ${classe}"
data-question="${i + 1}"
data-tooltip="${escapeHtml(tooltip)}">
<span class="question-number">${i + 1}</span>
<span>${icone}</span>
</div>
`;
}
return html;
}
function addQuestionTooltips() {
const tooltip = document.getElementById('tooltip');
const cells = document.querySelectorAll('.question-cell');
cells.forEach(cell => {
cell.addEventListener('mouseenter', (e) => {
const tooltipText = cell.dataset.tooltip;
tooltip.textContent = tooltipText;
tooltip.style.display = 'block';
const rect = cell.getBoundingClientRect();
tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
tooltip.style.top = rect.top - tooltip.offsetHeight - 5 + 'px';
});
cell.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
});
} }
function escapeHtml(text) { function escapeHtml(text) {

0
evaluations/.gitkeep Normal file
View File

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 380 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 438 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 433 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 410 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 443 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 244 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 331 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 396 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 453 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 355 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

View File

@ -162,6 +162,7 @@ $stmt->execute([$id_evaluation, $user['id_utilisateur']]);
$tentative = $stmt->fetch(PDO::FETCH_ASSOC); $tentative = $stmt->fetch(PDO::FETCH_ASSOC);
// Si pas de tentative en cours, en créer une (CORRECTION: utilise nb_tentatives_terminees) // Si pas de tentative en cours, en créer une (CORRECTION: utilise nb_tentatives_terminees)
// APRÈS (CORRIGÉ)
if (!$tentative) { if (!$tentative) {
$stmt = $db->prepare(" $stmt = $db->prepare("
INSERT INTO tentatives_eleves ( INSERT INTO tentatives_eleves (
@ -176,6 +177,9 @@ if (!$tentative) {
$stmt = $db->prepare("SELECT * FROM tentatives_eleves WHERE id_tentative = ?"); $stmt = $db->prepare("SELECT * FROM tentatives_eleves WHERE id_tentative = ?");
$stmt->execute([$id_tentative]); $stmt->execute([$id_tentative]);
$tentative = $stmt->fetch(PDO::FETCH_ASSOC); $tentative = $stmt->fetch(PDO::FETCH_ASSOC);
} else {
// Reprendre la tentative existante
$id_tentative = $tentative['id_tentative'];
} }
// Calculer temps restant // Calculer temps restant
@ -589,6 +593,11 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
} }
} }
</style> </style>
<!-- Chatbot IA Styles -->
<link rel="stylesheet" href="assets/css/chatbot.css">
<!-- KaTeX pour le rendu mathématique -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
</head> </head>
<body> <body>
<?php if ($apercu_mode): ?> <?php if ($apercu_mode): ?>
@ -619,8 +628,7 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
<input type="hidden" name="id_evaluation" value="<?= $id_evaluation ?>"> <input type="hidden" name="id_evaluation" value="<?= $id_evaluation ?>">
<?php foreach ($questions as $index => $q): ?> <?php foreach ($questions as $index => $q): ?>
<div class="question-card" data-question="<?= $index + 1 ?>" data-id="<?= $q['id_question'] ?>"> <div class="question-card" data-question="<?= $index + 1 ?>" data-id="<?= $q['id_question'] ?>" data-question-id="<?= $q['id_question'] ?>"> <div class="question-header">
<div class="question-header">
<div class="question-number">Question <?= $index + 1 ?> / <?= count($questions) ?></div> <div class="question-number">Question <?= $index + 1 ?> / <?= count($questions) ?></div>
<div class="question-meta"> <div class="question-meta">
<span class="badge badge-points"><?= $q['points'] ?> pts</span> <span class="badge badge-points"><?= $q['points'] ?> pts</span>
@ -965,5 +973,83 @@ $reponses_sauvegardees = json_decode($tentative['reponses_json'] ?? '{}', true)
window.addEventListener('beforeunload', handleBeforeUnload); window.addEventListener('beforeunload', handleBeforeUnload);
</script> </script>
<!-- Chatbot IA Widget -->
<div class="chat-bubble">
<button class="btn-chat" id="btn-open-chat">
💬 Besoin d'aide ? <span class="help-badge"><span id="help-remaining">3</span>/3</span>
</button>
</div>
<div id="modal-chat">
<div class="chat-container">
<div class="chat-header">
<h3>🤖 Assistant Mathématiques</h3>
<button class="btn-close-chat" id="btn-close-chat">×</button>
</div>
<div class="chat-messages" id="chat-messages">
<div class="message message-assistant">
Bonjour ! 👋 Je suis là pour t'aider sur cette question.
<br><br>
Pose-moi une question et je te guiderai étape par étape, sans te donner la réponse directement. Tu as droit à <strong>3 aides</strong> par question.
</div>
</div>
<div class="chat-input-zone">
<textarea id="chat-input" placeholder="Pose ta question ici..." rows="3"></textarea>
<button id="btn-send">📤 Envoyer</button>
</div>
</div>
</div>
<!-- KaTeX JS -->
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<!-- Chatbot IA Scripts -->
<script src="assets/js/chatbot.js"></script>
<script>
// Variables globales pour le chatbot
const tentativeId = <?= $id_tentative ?? 'null' ?>;
const questionsIds = <?= json_encode(array_column($questions ?? [], 'id_question')) ?>;
console.log('Init chatbot - tentativeId:', tentativeId);
console.log('Questions disponibles:', questionsIds);
// Initialiser le chatbot
document.addEventListener('DOMContentLoaded', () => {
if (tentativeId && questionsIds.length > 0) {
try {
window.chatbot = new ChatbotIA(tentativeId);
// Fonction pour obtenir la question actuelle
window.chatbot.getCurrentQuestionId = function() {
// Chercher l'input radio/checkbox sélectionné ou le dernier input
const inputs = document.querySelectorAll('input[name^="reponse_"]');
if (inputs.length > 0) {
// Prendre la première question visible
for (let input of inputs) {
const match = input.name.match(/reponse_(\d+)/);
if (match) {
const qId = parseInt(match[1]);
console.log('Question actuelle détectée:', qId);
return qId;
}
}
}
// Fallback : première question
console.log('Fallback: première question');
return questionsIds[0];
};
console.log('✅ Chatbot initialisé avec succès');
} catch (error) {
console.error('❌ Erreur initialisation chatbot:', error);
}
} else {
console.warn('⚠️ Chatbot non initialisé:', {tentativeId, questionsCount: questionsIds.length});
}
});
</script>
</body> </body>
</html> </html>

34
rollback_last.sh Executable file
View File

@ -0,0 +1,34 @@
#!/usr/bin/env bash
set -euo pipefail
APP_NAME="webval"
DST_DIR="/var/www/mathematiques"
BACKUP_ROOT="/var/backups/${APP_NAME}"
die() { echo "ERREUR: $*" >&2; exit 1; }
[[ -d "${DST_DIR}" ]] || die "Destination inexistante: ${DST_DIR}"
[[ -d "${BACKUP_ROOT}" ]] || die "Aucun backup trouvé: ${BACKUP_ROOT}"
# Trouver le backup le plus récent (ordre lexicographique OK grâce au timestamp)
LAST_BACKUP="$(ls -1d "${BACKUP_ROOT}"/prev_* 2>/dev/null | sort | tail -n 1 || true)"
[[ -n "${LAST_BACKUP}" && -d "${LAST_BACKUP}" ]] || die "Aucun dossier prev_* valide dans ${BACKUP_ROOT}"
echo "=== ROLLBACK MANUEL (${APP_NAME}) ==="
echo "Restore depuis : ${LAST_BACKUP}"
echo "Vers : ${DST_DIR}"
echo
read -r -p "Confirmer le rollback ? (oui/non) " ans
[[ "${ans}" == "oui" ]] || { echo "Annulé."; exit 0; }
sudo rsync -a --delete "${LAST_BACKUP}/" "${DST_DIR}/"
# Reload services (sans faire échouer si un service n'existe pas)
sudo systemctl reload php8.1-fpm >/dev/null 2>&1 || true
sudo systemctl reload nginx >/dev/null 2>&1 || true
echo "OK: rollback terminé."
echo "Logs utiles si besoin :"
echo " sudo tail -n 80 /var/log/nginx/error.log"
echo " sudo journalctl -u php8.1-fpm -n 80 --no-pager"

View File

@ -0,0 +1,136 @@
-- ============================================
-- WebVal - Gestion API Chatbot
-- Tables pour la gestion des clés API et modèles
-- Date: 2026-01-04
-- ============================================
-- Table des clés API des enseignants
CREATE TABLE IF NOT EXISTS api_keys (
id INT AUTO_INCREMENT PRIMARY KEY,
id_enseignant INT NOT NULL,
provider ENUM('gemini', 'mistral', 'openai', 'anthropic', 'ollama') NOT NULL,
api_key_encrypted TEXT, -- Clé chiffrée avec AES-256-CBC
model_default VARCHAR(100), -- Modèle par défaut (ex: 'gemini-2.0-flash-exp')
is_active BOOLEAN DEFAULT TRUE,
quota_max INT DEFAULT NULL, -- Limite mensuelle optionnelle
quota_used INT DEFAULT 0,
quota_reset_date DATE, -- Date de reset du quota
last_used TIMESTAMP NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
UNIQUE KEY unique_provider (id_enseignant, provider),
INDEX idx_enseignant (id_enseignant),
INDEX idx_active (is_active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Table des modèles disponibles (catalogue)
CREATE TABLE IF NOT EXISTS available_models (
id INT AUTO_INCREMENT PRIMARY KEY,
provider VARCHAR(50) NOT NULL,
model_id VARCHAR(100) NOT NULL, -- ID technique du modèle
display_name VARCHAR(150) NOT NULL, -- Nom affiché
description TEXT,
context_length INT DEFAULT 4096, -- Taille contexte en tokens
is_free BOOLEAN DEFAULT FALSE,
cost_per_1m_tokens DECIMAL(10,4) DEFAULT NULL, -- Coût par million de tokens
recommended BOOLEAN DEFAULT FALSE,
speed_rating TINYINT DEFAULT 3, -- 1=lent, 5=très rapide
quality_rating TINYINT DEFAULT 3, -- 1=basique, 5=excellent
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY unique_model (provider, model_id),
INDEX idx_provider (provider),
INDEX idx_recommended (recommended),
INDEX idx_active (active)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Table de configuration chatbot par évaluation
CREATE TABLE IF NOT EXISTS chatbot_eval_config (
id INT AUTO_INCREMENT PRIMARY KEY,
id_evaluation INT NOT NULL,
id_enseignant INT NOT NULL,
provider_default VARCHAR(50) DEFAULT 'ollama',
model_default VARCHAR(100) DEFAULT 'ministral-3:3b',
allow_student_override BOOLEAN DEFAULT FALSE, -- L'élève peut-il choisir ?
max_messages_per_question INT DEFAULT 3,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (id_evaluation) REFERENCES evaluations(id_evaluation) ON DELETE CASCADE,
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
UNIQUE KEY unique_eval (id_evaluation),
INDEX idx_enseignant (id_enseignant)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Table de configuration par élève (override)
CREATE TABLE IF NOT EXISTS chatbot_student_config (
id INT AUTO_INCREMENT PRIMARY KEY,
id_evaluation INT NOT NULL,
id_eleve INT NOT NULL,
provider_override VARCHAR(50),
model_override VARCHAR(100),
created_by INT NOT NULL, -- ID enseignant qui a fait l'override
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (id_evaluation) REFERENCES evaluations(id_evaluation) ON DELETE CASCADE,
FOREIGN KEY (id_eleve) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
FOREIGN KEY (created_by) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
UNIQUE KEY unique_student_eval (id_evaluation, id_eleve),
INDEX idx_evaluation (id_evaluation),
INDEX idx_eleve (id_eleve)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Pré-remplir les modèles disponibles
INSERT INTO available_models
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
VALUES
-- Gemini (Google)
('gemini', 'gemini-2.0-flash-exp', 'Gemini 2.0 Flash (Expérimental)', 'Modèle ultra-rapide de Google, gratuit avec quotas généreux', 1000000, TRUE, 0, TRUE, 5, 4),
('gemini', 'gemini-1.5-flash', 'Gemini 1.5 Flash', 'Modèle rapide et équilibré', 1000000, TRUE, 0, FALSE, 4, 4),
('gemini', 'gemini-1.5-pro', 'Gemini 1.5 Pro', 'Modèle le plus puissant de Google', 2000000, FALSE, 1.25, FALSE, 3, 5),
-- Mistral
('mistral', 'mistral-small-latest', 'Mistral Small', 'Modèle compact et rapide', 32000, FALSE, 0.20, FALSE, 5, 3),
('mistral', 'ministral-3b-latest', 'Ministral 3B', 'Petit modèle efficace pour le raisonnement', 128000, FALSE, 0.04, TRUE, 5, 3),
('mistral', 'ministral-8b-latest', 'Ministral 8B', 'Meilleur équilibre qualité/vitesse', 128000, FALSE, 0.10, TRUE, 4, 4),
('mistral', 'mistral-large-latest', 'Mistral Large', 'Modèle le plus puissant de Mistral', 128000, FALSE, 2.00, FALSE, 3, 5),
-- OpenAI
('openai', 'gpt-4o-mini', 'GPT-4o Mini', 'Petit modèle rapide et économique', 128000, FALSE, 0.15, TRUE, 5, 4),
('openai', 'gpt-4o', 'GPT-4o', 'Modèle multimodal puissant', 128000, FALSE, 2.50, FALSE, 4, 5),
('openai', 'gpt-4-turbo', 'GPT-4 Turbo', 'Modèle GPT-4 optimisé', 128000, FALSE, 10.00, FALSE, 3, 5),
-- Ollama (local)
('ollama', 'ministral-3:3b', 'Ministral 3B (Local)', 'Modèle local rapide', 128000, TRUE, 0, TRUE, 4, 3),
('ollama', 'qwen2-math:1.5b', 'Qwen2 Math 1.5B (Local)', 'Spécialisé en mathématiques', 32000, TRUE, 0, FALSE, 5, 3),
('ollama', 'llama3.2:3b', 'Llama 3.2 3B (Local)', 'Modèle généraliste compact', 128000, TRUE, 0, FALSE, 3, 4);
-- Ajouter colonne provider à la table chat_conversations pour tracking
ALTER TABLE chat_conversations
ADD COLUMN IF NOT EXISTS provider VARCHAR(50) DEFAULT 'ollama',
ADD COLUMN IF NOT EXISTS model_used VARCHAR(100) DEFAULT 'ministral-3:3b',
ADD COLUMN IF NOT EXISTS api_response_time_ms INT DEFAULT NULL,
ADD INDEX idx_provider (provider);
-- Ajouter colonne provider à la table chat_messages pour analytics
ALTER TABLE chat_messages
ADD COLUMN IF NOT EXISTS api_cost DECIMAL(10,6) DEFAULT 0.000000;
-- Vue pour les stats d'utilisation enseignant
CREATE OR REPLACE VIEW v_chatbot_usage_stats AS
SELECT
cc.id_enseignant,
cc.provider,
cc.model_used,
COUNT(DISTINCT cc.id_conversation) as total_conversations,
COUNT(cm.id) as total_messages,
AVG(cc.api_response_time_ms) as avg_response_time_ms,
SUM(cm.api_cost) as total_cost,
DATE_FORMAT(cc.date_debut, '%Y-%m') as month
FROM chat_conversations cc
LEFT JOIN chat_messages cm ON cc.id_conversation = cm.id_conversation
GROUP BY cc.id_enseignant, cc.provider, cc.model_used, month;
-- ============================================
-- FIN DU SCRIPT
-- ============================================

View File

@ -0,0 +1,36 @@
-- ============================================
-- WebVal - Configuration provider par défaut
-- Table pour stocker le choix de l'enseignant
-- ============================================
-- Table de configuration par défaut par enseignant
CREATE TABLE IF NOT EXISTS chatbot_default_provider (
id INT AUTO_INCREMENT PRIMARY KEY,
id_enseignant INT NOT NULL,
provider VARCHAR(50) NOT NULL,
model_default VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE CASCADE,
UNIQUE KEY unique_enseignant (id_enseignant)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Initialiser Ollama comme défaut pour les enseignants existants
INSERT IGNORE INTO chatbot_default_provider (id_enseignant, provider, model_default)
SELECT DISTINCT id_utilisateur, 'ollama', 'ministral-3:3b'
FROM utilisateurs
WHERE id_type = 1; -- Type enseignant
-- Mettre à jour pour ceux qui ont déjà une clé cloud active
UPDATE chatbot_default_provider cdp
JOIN (
SELECT id_enseignant, provider, model_default
FROM api_keys
WHERE is_active = 1
ORDER BY created_at ASC
LIMIT 1
) ak ON cdp.id_enseignant = ak.id_enseignant
SET cdp.provider = ak.provider,
cdp.model_default = ak.model_default;
SELECT '✅ Table chatbot_default_provider créée et initialisée' as Status;

44
sql/update_all_models.sql Normal file
View File

@ -0,0 +1,44 @@
-- ============================================
-- WebVal - Mise à jour complète des modèles
-- Gemini, Mistral, OpenAI, Ollama
-- ============================================
-- Supprimer les anciens modèles
DELETE FROM available_models WHERE provider IN ('gemini', 'mistral', 'openai');
-- GEMINI (Google) - Modèles gratuits et puissants
INSERT INTO available_models
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
VALUES
('gemini', 'gemini-2.5-flash', 'Gemini 2.5 Flash', 'Dernier modèle rapide de Google (juin 2025)', 1048576, TRUE, 0, TRUE, 5, 5),
('gemini', 'gemini-2.0-flash', 'Gemini 2.0 Flash', 'Modèle rapide et polyvalent', 1048576, TRUE, 0, FALSE, 5, 4),
('gemini', 'gemini-2.5-pro', 'Gemini 2.5 Pro', 'Modèle le plus puissant (juin 2025)', 1048576, FALSE, 1.25, FALSE, 3, 5);
-- MISTRAL - Modèles français performants
INSERT INTO available_models
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
VALUES
('mistral', 'mistral-small-latest', 'Mistral Small', 'Modèle compact et rapide', 32000, FALSE, 0.20, FALSE, 5, 3),
('mistral', 'ministral-3b-latest', 'Ministral 3B', 'Petit modèle efficace pour le raisonnement', 128000, FALSE, 0.04, TRUE, 5, 3),
('mistral', 'ministral-8b-latest', 'Ministral 8B', 'Meilleur équilibre qualité/vitesse', 128000, FALSE, 0.10, TRUE, 4, 4),
('mistral', 'mistral-large-latest', 'Mistral Large', 'Modèle le plus puissant de Mistral', 128000, FALSE, 2.00, FALSE, 3, 5);
-- OPENAI - Modèles de référence
INSERT INTO available_models
(provider, model_id, display_name, description, context_length, is_free, cost_per_1m_tokens, recommended, speed_rating, quality_rating)
VALUES
('openai', 'gpt-4o-mini', 'GPT-4o Mini', 'Petit modèle rapide et économique', 128000, FALSE, 0.15, TRUE, 5, 4),
('openai', 'gpt-4o', 'GPT-4o', 'Modèle multimodal puissant', 128000, FALSE, 2.50, FALSE, 4, 5),
('openai', 'gpt-4-turbo', 'GPT-4 Turbo', 'Modèle GPT-4 optimisé', 128000, FALSE, 10.00, FALSE, 3, 5);
-- Vérification
SELECT
provider,
COUNT(*) as nb_modeles,
SUM(CASE WHEN recommended = 1 THEN 1 ELSE 0 END) as nb_recommandes
FROM available_models
WHERE provider IN ('gemini', 'mistral', 'openai', 'ollama')
GROUP BY provider
ORDER BY provider;
SELECT '✅ Modèles mis à jour : Gemini (3), Mistral (4), OpenAI (3), Ollama (3)' as Status;

109
sql/update_chat_tables.sql Normal file
View File

@ -0,0 +1,109 @@
-- ============================================
-- WebVal - Mise à jour chat_conversations
-- Ajout colonnes pour tracking API (sécurisé)
-- ============================================
-- Désactiver les erreurs temporairement
SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0;
-- Ajouter colonnes une par une (ignore si existe déjà)
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND column_name = 'provider') > 0,
'SELECT ''Column provider already exists''',
'ALTER TABLE chat_conversations ADD COLUMN provider VARCHAR(50) DEFAULT ''ollama'''
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND column_name = 'model_used') > 0,
'SELECT ''Column model_used already exists''',
'ALTER TABLE chat_conversations ADD COLUMN model_used VARCHAR(100) DEFAULT ''ministral-3:3b'''
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND column_name = 'api_response_time_ms') > 0,
'SELECT ''Column api_response_time_ms already exists''',
'ALTER TABLE chat_conversations ADD COLUMN api_response_time_ms INT DEFAULT NULL'
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND column_name = 'id_enseignant') > 0,
'SELECT ''Column id_enseignant already exists''',
'ALTER TABLE chat_conversations ADD COLUMN id_enseignant INT DEFAULT NULL'
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Index
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND index_name = 'idx_provider') > 0,
'SELECT ''Index idx_provider already exists''',
'ALTER TABLE chat_conversations ADD INDEX idx_provider (provider)'
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Foreign key (plus complexe, on teste avec SHOW CREATE TABLE)
SET @fk_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE table_schema = DATABASE()
AND table_name = 'chat_conversations'
AND referenced_table_name = 'utilisateurs'
AND column_name = 'id_enseignant');
SET @s = IF(@fk_exists > 0,
'SELECT ''Foreign key already exists''',
'ALTER TABLE chat_conversations ADD FOREIGN KEY (id_enseignant) REFERENCES utilisateurs(id_utilisateur) ON DELETE SET NULL'
);
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Colonne api_cost dans chat_messages
SET @s = (SELECT IF(
(SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = DATABASE()
AND table_name = 'chat_messages'
AND column_name = 'api_cost') > 0,
'SELECT ''Column api_cost already exists''',
'ALTER TABLE chat_messages ADD COLUMN api_cost DECIMAL(10,6) DEFAULT 0.000000'
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
-- Restaurer les notes SQL
SET SQL_NOTES=@OLD_SQL_NOTES;
-- Remplir id_enseignant rétroactivement
UPDATE chat_conversations cc
JOIN tentatives_eleves te ON cc.id_tentative = te.id_tentative
JOIN evaluations e ON te.id_evaluation = e.id_evaluation
SET cc.id_enseignant = e.id_enseignant
WHERE cc.id_enseignant IS NULL;
SELECT '✅ Colonnes ajoutées avec succès' as Status;